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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 3 |
+
import cv2
|
| 4 |
+
from ultralytics import YOLO
|
| 5 |
+
from database import save_prediction_to_db
|
| 6 |
+
|
| 7 |
+
# Load YOLO models
|
| 8 |
+
try:
|
| 9 |
+
yolo_model_glaucoma = YOLO('best-glaucoma-seg.pt')
|
| 10 |
+
yolo_model_od = YOLO("best-glaucoma-od.pt")
|
| 11 |
+
print("YOLO models loaded successfully.")
|
| 12 |
+
except Exception as e:
|
| 13 |
+
print(f"Error loading YOLO models: {e}")
|
| 14 |
+
|
| 15 |
+
def calculate_area(mask):
|
| 16 |
+
area = np.sum(mask > 0.5)
|
| 17 |
+
print(f"Calculated area: {area}")
|
| 18 |
+
return area
|
| 19 |
+
|
| 20 |
+
def classify_ddls(rim_to_disc_ratio):
|
| 21 |
+
if rim_to_disc_ratio >= 0.5:
|
| 22 |
+
stage = 0 # Non Glaucomatous
|
| 23 |
+
elif 0.4 <= rim_to_disc_ratio < 0.5:
|
| 24 |
+
stage = 1
|
| 25 |
+
elif 0.3 <= rim_to_disc_ratio < 0.4:
|
| 26 |
+
stage = 2
|
| 27 |
+
elif 0.2 <= rim_to_disc_ratio < 0.3:
|
| 28 |
+
stage = 3
|
| 29 |
+
elif 0.1 <= rim_to_disc_ratio < 0.2:
|
| 30 |
+
stage = 4
|
| 31 |
+
elif 0.0 < rim_to_disc_ratio < 0.1:
|
| 32 |
+
stage = 5
|
| 33 |
+
else:
|
| 34 |
+
stage = 6
|
| 35 |
+
print(f"Classified DDLS stage: {stage}")
|
| 36 |
+
return stage
|
| 37 |
+
|
| 38 |
+
def add_watermark(image):
|
| 39 |
+
try:
|
| 40 |
+
logo = Image.open('image-logo.png').convert("RGBA")
|
| 41 |
+
image = image.convert("RGBA")
|
| 42 |
+
|
| 43 |
+
# Resize logo
|
| 44 |
+
basewidth = 100
|
| 45 |
+
wpercent = (basewidth / float(logo.size[0]))
|
| 46 |
+
hsize = int((float(wpercent) * logo.size[1]))
|
| 47 |
+
logo = logo.resize((basewidth, hsize), Image.LANCZOS)
|
| 48 |
+
|
| 49 |
+
# Position logo
|
| 50 |
+
position = (image.width - logo.width - 10, image.height - logo.height - 10)
|
| 51 |
+
|
| 52 |
+
# Composite image
|
| 53 |
+
transparent = Image.new('RGBA', (image.width, image.height), (0, 0, 0, 0))
|
| 54 |
+
transparent.paste(image, (0, 0))
|
| 55 |
+
transparent.paste(logo, position, mask=logo)
|
| 56 |
+
|
| 57 |
+
return transparent.convert("RGB")
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f"Error adding watermark: {e}")
|
| 60 |
+
return image
|
| 61 |
+
|
| 62 |
+
def predict_and_visualize_glaucoma(image, mask_threshold=0.5):
|
| 63 |
+
try:
|
| 64 |
+
pil_image = Image.fromarray(image)
|
| 65 |
+
orig_size = pil_image.size
|
| 66 |
+
results = yolo_model_glaucoma(pil_image)
|
| 67 |
+
|
| 68 |
+
raw_response = str(results)
|
| 69 |
+
print(f"YOLO results: {raw_response}")
|
| 70 |
+
masked_image = np.array(pil_image)
|
| 71 |
+
mask_image = np.zeros_like(masked_image)
|
| 72 |
+
|
| 73 |
+
cup_mask, disk_mask = None, None
|
| 74 |
+
|
| 75 |
+
if len(results) > 0:
|
| 76 |
+
result = results[0]
|
| 77 |
+
if hasattr(result, 'masks') and result.masks is not None and len(result.masks) > 0:
|
| 78 |
+
for mask_data in result.masks.data:
|
| 79 |
+
mask = np.array(mask_data.cpu().squeeze().numpy())
|
| 80 |
+
mask_resized = cv2.resize(mask, orig_size, interpolation=cv2.INTER_NEAREST)
|
| 81 |
+
|
| 82 |
+
if np.sum(mask_resized) > np.sum(disk_mask if disk_mask is not None else 0):
|
| 83 |
+
cup_mask = disk_mask
|
| 84 |
+
disk_mask = mask_resized
|
| 85 |
+
else:
|
| 86 |
+
cup_mask = mask_resized
|
| 87 |
+
|
| 88 |
+
if cup_mask is not None and disk_mask is not None:
|
| 89 |
+
area_cup = calculate_area(cup_mask)
|
| 90 |
+
area_disk = calculate_area(disk_mask)
|
| 91 |
+
rim_area = area_disk - area_cup
|
| 92 |
+
print(f"Area cup: {area_cup}, Area disk: {area_disk}, Rim area: {rim_area}")
|
| 93 |
+
|
| 94 |
+
rim_to_disc_ratio = rim_area / area_disk if area_disk > 0 else 0
|
| 95 |
+
print(f"Rim to disc ratio: {rim_to_disc_ratio}")
|
| 96 |
+
ddls_stage = classify_ddls(rim_to_disc_ratio)
|
| 97 |
+
|
| 98 |
+
combined_image = np.array(pil_image)
|
| 99 |
+
|
| 100 |
+
# Create RGBA version of the original image
|
| 101 |
+
combined_image_rgba = cv2.cvtColor(combined_image, cv2.COLOR_RGB2RGBA)
|
| 102 |
+
|
| 103 |
+
# Create transparent masks
|
| 104 |
+
cup_mask_rgba = np.zeros_like(combined_image_rgba)
|
| 105 |
+
cup_mask_rgba[:, :, 0] = 0 # Red channel
|
| 106 |
+
cup_mask_rgba[:, :, 1] = 0 # Green channel
|
| 107 |
+
cup_mask_rgba[:, :, 2] = 255 # Blue channel
|
| 108 |
+
cup_mask_rgba[:, :, 3] = 128 # Alpha channel (50% transparency)
|
| 109 |
+
|
| 110 |
+
disk_mask_rgba = np.zeros_like(combined_image_rgba)
|
| 111 |
+
disk_mask_rgba[:, :, 0] = 255 # Red channel
|
| 112 |
+
disk_mask_rgba[:, :, 1] = 0 # Green channel
|
| 113 |
+
disk_mask_rgba[:, :, 2] = 0 # Blue channel
|
| 114 |
+
disk_mask_rgba[:, :, 3] = 128 # Alpha channel (50% transparency)
|
| 115 |
+
|
| 116 |
+
# Apply masks to the original image with transparency
|
| 117 |
+
cup_mask_indices = cup_mask > mask_threshold
|
| 118 |
+
disk_mask_indices = disk_mask > mask_threshold
|
| 119 |
+
|
| 120 |
+
combined_image_rgba[cup_mask_indices] = (0.5 * combined_image_rgba[cup_mask_indices] + 0.5 * cup_mask_rgba[cup_mask_indices]).astype(np.uint8)
|
| 121 |
+
combined_image_rgba[disk_mask_indices] = (0.5 * combined_image_rgba[disk_mask_indices] + 0.5 * disk_mask_rgba[disk_mask_indices]).astype(np.uint8)
|
| 122 |
+
|
| 123 |
+
# Convert to PIL image for drawing
|
| 124 |
+
combined_pil_image = Image.fromarray(combined_image_rgba)
|
| 125 |
+
|
| 126 |
+
# Add text to the image
|
| 127 |
+
draw = ImageDraw.Draw(combined_pil_image)
|
| 128 |
+
|
| 129 |
+
# Load a larger font (adjust the size as needed)
|
| 130 |
+
font_size = 48 # Example font size
|
| 131 |
+
try:
|
| 132 |
+
font = ImageFont.truetype("font.ttf", size=font_size)
|
| 133 |
+
except IOError:
|
| 134 |
+
font = ImageFont.load_default()
|
| 135 |
+
print("Error: cannot open resource, using default font.")
|
| 136 |
+
|
| 137 |
+
text = f"Area cup: {area_cup}\nArea disk: {area_disk}\nRim area: {rim_area}\nRim to disc ratio: {rim_to_disc_ratio:.2f}\nDDLS stage: {ddls_stage}"
|
| 138 |
+
text_x = 20
|
| 139 |
+
text_y = 40
|
| 140 |
+
|
| 141 |
+
draw.text((text_x, text_y), text, fill=(255, 255, 255, 255), font=font)
|
| 142 |
+
|
| 143 |
+
# Add watermark
|
| 144 |
+
combined_pil_image = add_watermark(combined_pil_image)
|
| 145 |
+
|
| 146 |
+
return np.array(combined_pil_image), area_cup, area_disk, rim_area, rim_to_disc_ratio, ddls_stage
|
| 147 |
+
|
| 148 |
+
print("No detected regions")
|
| 149 |
+
return np.zeros_like(image), 0, 0, 0, 0, "No detected regions"
|
| 150 |
+
except Exception as e:
|
| 151 |
+
print("Error:", e)
|
| 152 |
+
return np.zeros_like(image), 0, 0, 0, 0, str(e)
|
| 153 |
+
|
| 154 |
+
def combined_prediction_glaucoma(image, mask_threshold):
|
| 155 |
+
segmented_image, cup_area, disk_area, rim_area, rim_to_disc_ratio, ddls_stage = predict_and_visualize_glaucoma(image, mask_threshold)
|
| 156 |
+
print(f"Segmented image: {segmented_image.shape}")
|
| 157 |
+
print(f"Cup area: {cup_area}, Disk area: {disk_area}, Rim area: {rim_area}")
|
| 158 |
+
print(f"Rim to disc ratio: {rim_to_disc_ratio}, DDLS stage: {ddls_stage}")
|
| 159 |
+
|
| 160 |
+
return segmented_image, cup_area, disk_area, rim_area, rim_to_disc_ratio, ddls_stage
|
| 161 |
+
|
| 162 |
+
def submit_to_db(image, cup_area, disk_area, rim_area, rim_to_disc_ratio, ddls_stage):
|
| 163 |
+
try:
|
| 164 |
+
# Convert the image from numpy array to PIL image
|
| 165 |
+
pil_image = Image.fromarray(np.uint8(image))
|
| 166 |
+
save_prediction_to_db(pil_image, cup_area, disk_area, rim_area, rim_to_disc_ratio, ddls_stage)
|
| 167 |
+
return "Values successfully saved to database.", ""
|
| 168 |
+
except Exception as e:
|
| 169 |
+
print(f"Error saving to database: {e}")
|
| 170 |
+
return f"Error saving to database: {e}", ""
|
| 171 |
+
|
| 172 |
+
def predict_image(input_image):
|
| 173 |
+
# Convert Gradio input image (PIL Image) to numpy array
|
| 174 |
+
image_np = np.array(input_image)
|
| 175 |
+
|
| 176 |
+
# Ensure the image is in the correct format
|
| 177 |
+
if len(image_np.shape) == 2: # grayscale to RGB
|
| 178 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
|
| 179 |
+
elif image_np.shape[2] == 4: # RGBA to RGB
|
| 180 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
|
| 181 |
+
|
| 182 |
+
# Perform prediction
|
| 183 |
+
results = yolo_model_od(image_np)
|
| 184 |
+
|
| 185 |
+
# Draw bounding boxes on the image
|
| 186 |
+
image_with_boxes = image_np.copy()
|
| 187 |
+
raw_predictions = []
|
| 188 |
+
for result in results[0].boxes:
|
| 189 |
+
confidence = result.conf.item() # Convert tensor to standard Python type
|
| 190 |
+
label = "Glaucoma" if confidence > 0.5 else "Normal" # Set label based on confidence
|
| 191 |
+
|
| 192 |
+
xmin, ymin, xmax, ymax = map(int, result.xyxy[0])
|
| 193 |
+
|
| 194 |
+
# Draw black rectangle as background for text
|
| 195 |
+
text = f'{label} {confidence:.2f}'
|
| 196 |
+
font_scale = 1.0 # Increased font scale
|
| 197 |
+
font_thickness = 2 # Increased font thickness
|
| 198 |
+
(w, h), baseline = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness)
|
| 199 |
+
cv2.rectangle(image_with_boxes, (xmin, ymin - h - baseline), (xmin + w, ymin), (0, 0, 0), -1)
|
| 200 |
+
|
| 201 |
+
cv2.putText(image_with_boxes, text, (xmin, ymin - baseline), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), font_thickness)
|
| 202 |
+
|
| 203 |
+
# Draw thicker bounding box
|
| 204 |
+
box_thickness = 3 # Increased box thickness
|
| 205 |
+
cv2.rectangle(image_with_boxes, (xmin, ymin), (xmax, ymax), (0, 255, 0), box_thickness)
|
| 206 |
+
|
| 207 |
+
raw_predictions.append(f"Label: {label}, Confidence: {confidence:.2f}, Box: [{xmin}, {ymin}, {xmax}, {ymax}]")
|
| 208 |
+
|
| 209 |
+
raw_predictions_str = "\n".join(raw_predictions)
|
| 210 |
+
|
| 211 |
+
# Add watermark to the final image with boxes
|
| 212 |
+
pil_image_with_boxes = Image.fromarray(image_with_boxes)
|
| 213 |
+
pil_image_with_boxes = add_watermark(pil_image_with_boxes)
|
| 214 |
+
image_with_boxes = np.array(pil_image_with_boxes)
|
| 215 |
+
|
| 216 |
+
return image_with_boxes, raw_predictions_str
|