ariankhalfani commited on
Commit
ea7d15b
1 Parent(s): 1ecf910

Create cataract.py

Browse files
Files changed (1) hide show
  1. cataract.py +296 -0
cataract.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ from PIL import Image, ImageDraw, ImageFont
5
+ from ultralytics import YOLO
6
+ import sqlite3
7
+ from io import BytesIO
8
+ from scipy.stats import norm
9
+
10
+ # Load YOLO models
11
+ try:
12
+ yolo_model_cataract = YOLO('best-cataract-seg.pt')
13
+ yolo_model_object_detection = YOLO('best-cataract-od.pt')
14
+ print("YOLO models loaded successfully.")
15
+ except Exception as e:
16
+ print(f"Error loading YOLO models: {e}")
17
+
18
+ def calculate_ratios(red_values, green_values, blue_values, total_pixels):
19
+ if total_pixels == 0:
20
+ return 0, 0, 0
21
+
22
+ red_ratio = np.sum(red_values) / total_pixels
23
+ green_ratio = np.sum(green_values) / total_pixels
24
+ blue_ratio = np.sum(blue_values) / total_pixels
25
+
26
+ total_ratio = red_ratio + green_ratio + blue_ratio
27
+
28
+ if total_ratio > 0:
29
+ red_quantity = (red_ratio / total_ratio) * 255
30
+ green_quantity = (green_ratio / total_ratio) * 255
31
+ blue_quantity = (blue_ratio / total_ratio) * 255
32
+ else:
33
+ red_quantity, green_quantity, blue_quantity = 0, 0, 0
34
+
35
+ return red_quantity, green_quantity, blue_quantity
36
+
37
+ def cataract_staging(red_quantity, green_quantity, blue_quantity):
38
+ # Assuming you have already defined your mean and std for each class and each RGB channel
39
+ # Example mean and std based on earlier discussion
40
+ mean_mature_red = 73.37
41
+ std_mature_red = (90.12 - 41.49) / 4
42
+ mean_mature_green = 89.48
43
+ std_mature_green = (97.67 - 83.39) / 4
44
+ mean_mature_blue = 92.15
45
+ std_mature_blue = (117.82 - 75.37) / 4
46
+
47
+ mean_normal_red = 67.84
48
+ std_normal_red = (107.02 - 56.19) / 4
49
+ mean_normal_green = 84.85
50
+ std_normal_green = (89.89 - 80.74) / 4
51
+ mean_normal_blue = 102.31
52
+ std_normal_blue = (111.34 - 65.58) / 4
53
+
54
+ mean_immature_red = 68.83
55
+ std_immature_red = (85.95 - 41.49) / 4
56
+ mean_immature_green = 89.43
57
+ std_immature_green = (97.67 - 83.39) / 4
58
+ mean_immature_blue = 96.74
59
+ std_immature_blue = (117.82 - 78.41) / 4
60
+
61
+ # Calculate likelihoods for each class
62
+ likelihood_mature = (
63
+ norm.pdf(red_quantity, mean_mature_red, std_mature_red) *
64
+ norm.pdf(green_quantity, mean_mature_green, std_mature_green) *
65
+ norm.pdf(blue_quantity, mean_mature_blue, std_mature_blue)
66
+ )
67
+
68
+ likelihood_normal = (
69
+ norm.pdf(red_quantity, mean_normal_red, std_normal_red) *
70
+ norm.pdf(green_quantity, mean_normal_green, std_normal_green) *
71
+ norm.pdf(blue_quantity, mean_normal_blue, std_normal_blue)
72
+ )
73
+
74
+ likelihood_immature = (
75
+ norm.pdf(red_quantity, mean_immature_red, std_immature_red) *
76
+ norm.pdf(green_quantity, mean_immature_green, std_immature_green) *
77
+ norm.pdf(blue_quantity, mean_immature_blue, std_immature_blue)
78
+ )
79
+
80
+ # Define prior probabilities (assuming equal prior for simplicity)
81
+ prior_mature = 1/3
82
+ prior_normal = 1/3
83
+ prior_immature = 1/3
84
+
85
+ # Apply Bayes' theorem to compute posterior probabilities
86
+ posterior_mature = likelihood_mature * prior_mature
87
+ posterior_normal = likelihood_normal * prior_normal
88
+ posterior_immature = likelihood_immature * prior_immature
89
+
90
+ # Determine the stage based on maximum posterior probability
91
+ stages = {
92
+ posterior_mature: "Mature",
93
+ posterior_normal: "Normal",
94
+ posterior_immature: "Immature"
95
+ }
96
+ max_posterior = max(posterior_mature, posterior_normal, posterior_immature)
97
+ stage = stages[max_posterior]
98
+
99
+ return stage
100
+
101
+ def add_watermark(image):
102
+ try:
103
+ logo = Image.open('image-logo.png').convert("RGBA")
104
+ image = image.convert("RGBA")
105
+
106
+ # Resize logo
107
+ basewidth = 100
108
+ wpercent = (basewidth / float(logo.size[0]))
109
+ hsize = int((float(wpercent) * logo.size[1]))
110
+ logo = logo.resize((basewidth, hsize), Image.LANCZOS)
111
+
112
+ # Position logo
113
+ position = (image.width - logo.width - 10, image.height - logo.height - 10)
114
+
115
+ # Composite image
116
+ transparent = Image.new('RGBA', (image.width, image.height), (0, 0, 0, 0))
117
+ transparent.paste(image, (0, 0))
118
+ transparent.paste(logo, position, mask=logo)
119
+
120
+ return transparent.convert("RGB")
121
+ except Exception as e:
122
+ print(f"Error adding watermark: {e}")
123
+ return image
124
+
125
+
126
+ def predict_and_visualize(image):
127
+ try:
128
+ pil_image = Image.fromarray(image.astype('uint8'), 'RGB')
129
+ orig_size = pil_image.size
130
+ results = yolo_model_cataract(pil_image)
131
+
132
+ raw_response = str(results)
133
+ masked_image = np.array(pil_image)
134
+ mask_image = np.zeros_like(masked_image)
135
+
136
+ red_quantity, green_quantity, blue_quantity = 0, 0, 0
137
+ total_pixels = 0
138
+
139
+ if len(results) > 0:
140
+ result = results[0]
141
+ if hasattr(result, 'masks') and result.masks is not None and len(result.masks) > 0:
142
+ mask = np.array(result.masks.data.cpu().squeeze().numpy())
143
+ mask_resized = np.array(Image.fromarray(mask).resize(orig_size, Image.NEAREST))
144
+
145
+ red_mask = np.zeros_like(masked_image)
146
+ red_mask[mask_resized > 0.5] = [255, 0, 0]
147
+ alpha = 0.5
148
+ blended_image = cv2.addWeighted(masked_image, 1 - alpha, red_mask, alpha, 0)
149
+
150
+ pupil_pixels = np.array(pil_image)[mask_resized > 0.5]
151
+ total_pixels = pupil_pixels.shape[0]
152
+
153
+ red_values = pupil_pixels[:, 0]
154
+ green_values = pupil_pixels[:, 1]
155
+ blue_values = pupil_pixels[:, 2]
156
+
157
+ red_quantity, green_quantity, blue_quantity = calculate_ratios(red_values, green_values, blue_values, total_pixels)
158
+ stage = cataract_staging(red_quantity, green_quantity, blue_quantity)
159
+
160
+ # Add text to the blended image
161
+ combined_pil_image = Image.fromarray(blended_image)
162
+ draw = ImageDraw.Draw(combined_pil_image)
163
+
164
+ # Load a larger font (adjust the size as needed)
165
+ font_size = 48 # Example font size
166
+ try:
167
+ font = ImageFont.truetype("font.ttf", size=font_size)
168
+ except IOError:
169
+ font = ImageFont.load_default()
170
+ print("Error: cannot open resource, using default font.")
171
+
172
+ text = f"Red quantity: {red_quantity:.2f}\nGreen quantity: {green_quantity:.2f}\nBlue quantity: {blue_quantity:.2f}\nStage: {stage}"
173
+
174
+ # Calculate text bounding box
175
+ text_bbox = draw.textbbox((0, 0), text, font=font)
176
+ text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
177
+ text_x = 20
178
+ text_y = 40
179
+ padding = 10
180
+
181
+ # Draw a filled rectangle for the background
182
+ draw.rectangle(
183
+ [text_x - padding, text_y - padding, text_x + text_width + padding, text_y + text_height + padding],
184
+ fill="black"
185
+ )
186
+
187
+ # Draw text on top of the rectangle
188
+ draw.text((text_x, text_y), text, fill=(255, 255, 255, 255), font=font)
189
+
190
+ # Add watermark to the image
191
+ combined_pil_image_with_watermark = add_watermark(combined_pil_image)
192
+
193
+ return np.array(combined_pil_image_with_watermark), red_quantity, green_quantity, blue_quantity, raw_response, stage
194
+
195
+ return image, 0, 0, 0, "No mask detected.", "Unknown"
196
+
197
+ except Exception as e:
198
+ print("Error:", e)
199
+ return np.zeros_like(image), 0, 0, 0, str(e), "Error"
200
+
201
+ def check_duplicate_entry(conn, red_quantity, green_quantity, blue_quantity, stage):
202
+ cursor = conn.cursor()
203
+ query = '''SELECT COUNT(*) FROM cataract_results WHERE red_quantity=? AND green_quantity=? AND blue_quantity=? AND stage=?'''
204
+ cursor.execute(query, (red_quantity, green_quantity, blue_quantity, stage))
205
+ count = cursor.fetchone()[0]
206
+ return count > 0
207
+
208
+ def save_cataract_prediction_to_db(image, red_quantity, green_quantity, blue_quantity, stage):
209
+ database = "cataract_results.db"
210
+ conn = create_connection(database)
211
+ if conn:
212
+ create_cataract_table(conn)
213
+
214
+ # Check for duplicate entries
215
+ if check_duplicate_entry(conn, red_quantity, green_quantity, blue_quantity, stage):
216
+ conn.close()
217
+ return "Duplicate entry found, not saving.", "Duplicate entry detected."
218
+
219
+ sql = '''INSERT INTO cataract_results(image, red_quantity, green_quantity, blue_quantity, stage) VALUES(?,?,?,?,?)'''
220
+ cur = conn.cursor()
221
+
222
+ # Convert the image to bytes
223
+ buffered = BytesIO()
224
+ image.save(buffered, format="PNG")
225
+ img_bytes = buffered.getvalue()
226
+
227
+ cur.execute(sql, (img_bytes, red_quantity, green_quantity, blue_quantity, stage))
228
+ conn.commit()
229
+ conn.close()
230
+ return "Data saved successfully", f"Red: {red_quantity}, Green: {green_quantity}, Blue: {blue_quantity}, Stage: {stage}"
231
+
232
+ return "Failed to save data", "No connection to the database."
233
+
234
+ def combined_prediction(image):
235
+ blended_image, red_quantity, green_quantity, blue_quantity, raw_response, stage = predict_and_visualize(image)
236
+ save_message, debug_info = save_cataract_prediction_to_db(Image.fromarray(blended_image), red_quantity, green_quantity, blue_quantity, stage)
237
+ return blended_image, red_quantity, green_quantity, blue_quantity, raw_response, stage, save_message, debug_info
238
+
239
+ def create_connection(db_file):
240
+ """ Create a database connection to the SQLite database """
241
+ conn = None
242
+ try:
243
+ conn = sqlite3.connect(db_file)
244
+ return conn
245
+ except sqlite3.Error as e:
246
+ print(e)
247
+ return conn
248
+
249
+ def create_cataract_table(conn):
250
+ """ Create the cataract results table if it does not exist """
251
+ create_table_sql = """ CREATE TABLE IF NOT EXISTS cataract_results (
252
+ id integer PRIMARY KEY,
253
+ image blob,
254
+ red_quantity real,
255
+ green_quantity real,
256
+ blue_quantity real,
257
+ stage text
258
+ ); """
259
+ try:
260
+ cursor = conn.cursor()
261
+ cursor.execute(create_table_sql)
262
+ except sqlite3.Error as e:
263
+ print(e)
264
+
265
+ def predict_object_detection(image):
266
+ try:
267
+ image_np = np.array(image)
268
+ results = yolo_model_object_detection(image_np)
269
+
270
+ image_with_boxes = image_np.copy()
271
+ raw_predictions = []
272
+ for result in results[0].boxes:
273
+ label = "Normal" if result.cls.item() == 1 else "Cataract"
274
+ confidence = result.conf.item()
275
+ xmin, ymin, xmax, ymax = map(int, result.xyxy[0])
276
+ cv2.rectangle(image_with_boxes, (xmin, ymin), (xmax, ymax), (255, 0, 0), 2)
277
+
278
+ font_scale = 1.0
279
+ thickness = 2
280
+ text = f'{label} {confidence:.2f}'
281
+ (text_width, text_height), baseline = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness)
282
+ cv2.rectangle(image_with_boxes, (xmin, ymin - text_height - baseline), (xmin + text_width, ymin), (0, 0, 0), cv2.FILLED)
283
+ cv2.putText(image_with_boxes, text, (xmin, ymin - baseline), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), thickness)
284
+
285
+ raw_predictions.append(f"Label: {label}, Confidence: {confidence:.2f}, Box: [{xmin}, {ymin}, {xmax}, {ymax}]")
286
+
287
+ raw_predictions_str = "\n".join(raw_predictions)
288
+
289
+ # Convert image_with_boxes to PIL image and add watermark
290
+ image_with_boxes_pil = Image.fromarray(image_with_boxes)
291
+ image_with_boxes_pil_with_watermark = add_watermark(image_with_boxes_pil)
292
+
293
+ return np.array(image_with_boxes_pil_with_watermark), raw_predictions_str
294
+ except Exception as e:
295
+ print("Error in object detection:", e)
296
+ return np.zeros_like(image), str(e)