Ani14 commited on
Commit
0e2bcdc
·
verified ·
1 Parent(s): 97562fa

Update predict.py

Browse files
Files changed (1) hide show
  1. predict.py +188 -99
predict.py CHANGED
@@ -1,132 +1,221 @@
1
- from fastapi import FastAPI, File, UploadFile, Response, HTTPException
2
  import cv2
3
  import numpy as np
4
  from ultralytics import YOLO
5
  import tensorflow as tf
6
- import os
7
  from typing import Union
8
 
9
- app = FastAPI()
10
-
11
  PIXELS_PER_CM = 50.0
12
 
13
- # --- Model loading ---
14
- segmentation_model, yolo_model = None, None
15
- try:
16
- segmentation_model = tf.keras.models.load_model("segmentation_model.h5")
17
- except Exception as e:
18
- print(f"Segmentation model not loaded: {e}")
19
 
20
- try:
21
- yolo_model = YOLO("best.pt")
22
- except Exception as e:
23
- print(f"YOLO model not loaded: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- # --- Helpers ---
26
  def preprocess_image(image: np.ndarray) -> np.ndarray:
27
- lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
28
- l, a, b = cv2.split(lab)
 
 
29
  clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
30
- cl = clahe.apply(l)
31
- limg = cv2.merge((cl, a, b))
32
- return cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
 
 
 
 
33
 
34
- def detect_with_yolo(image: np.ndarray) -> Union[tuple, None]:
 
 
35
  try:
36
  results = yolo_model.predict(image, verbose=False)
37
- if results and results[0].boxes:
 
38
  best_box = sorted(results[0].boxes, key=lambda b: b.conf[0], reverse=True)[0]
39
  coords = best_box.xyxy[0].cpu().numpy()
40
  return tuple(map(int, coords))
41
  except Exception as e:
42
- print(f"YOLO error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  return None
44
 
45
- def fallback_segmentation(image: np.ndarray) -> np.ndarray:
46
- Z = image.reshape((-1, 3)).astype(np.float32)
 
47
  criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
48
- _, label, center = cv2.kmeans(Z, 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
49
- label = label.reshape(image.shape[:2])
50
- unique_vals = np.unique(label)
51
- if len(unique_vals) > 1:
52
- wound_label = np.argmax([np.sum(label == val) for val in unique_vals])
53
- else:
54
- wound_label = unique_vals[0]
55
- return (label == wound_label).astype(np.uint8) * 255
56
-
57
- def segment(image: np.ndarray) -> np.ndarray:
58
- if segmentation_model is not None:
59
- try:
60
- input_shape = segmentation_model.input.shape[1:3]
61
- resized = cv2.resize(image, (input_shape[1], input_shape[0]))
62
- norm = np.expand_dims(resized / 255.0, axis=0)
63
- prediction = segmentation_model.predict(norm)
64
- if isinstance(prediction, list):
65
- prediction = prediction[0]
66
- mask = (prediction[0].squeeze() >= 0.5).astype(np.uint8) * 255
67
- return cv2.resize(mask, (image.shape[1], image.shape[0]))
68
- except Exception as e:
69
- print(f"Segmentation model failed: {e}")
70
- return fallback_segmentation(image)
71
-
72
- def calculate_metrics(mask: np.ndarray, image: np.ndarray) -> dict:
73
- area_px = cv2.countNonZero(mask)
74
- area_cm2 = area_px / (PIXELS_PER_CM ** 2)
75
  contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
76
  if not contours:
77
- return {"length": 0, "breadth": 0, "area": 0, "depth": 0, "moisture": 0}
78
- c = max(contours, key=cv2.contourArea)
79
- rect = cv2.minAreaRect(c)
80
- length, breadth = max(rect[1]) / PIXELS_PER_CM, min(rect[1]) / PIXELS_PER_CM
81
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
82
- texture_std = np.std(gray[mask.astype(bool)])
83
- lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
84
- mean_a = np.mean(lab[:, :, 1][mask.astype(bool)])
85
- depth = mean_a - 128
86
- moisture = max(0, 100 * (1.0 - texture_std / 127.0))
87
- return {
88
- "area": area_cm2,
89
- "length": length,
90
- "breadth": breadth,
91
- "depth": depth,
92
- "moisture": moisture,
93
- "contour": c
94
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- def annotate(image: np.ndarray, mask: np.ndarray, contour) -> np.ndarray:
97
- poly_image = image.copy()
98
- if contour is not None:
99
- cv2.drawContours(poly_image, [contour], -1, (0, 255, 0), 2)
100
- return poly_image
101
 
102
- # --- API ---
103
  @app.post("/analyze_wound")
104
  async def analyze_wound(file: UploadFile = File(...)):
 
 
 
 
105
  contents = await file.read()
106
- arr = np.frombuffer(contents, np.uint8)
107
- image = cv2.imdecode(arr, cv2.IMREAD_COLOR)
108
- if image is None:
109
- raise HTTPException(status_code=400, detail="Invalid image")
110
-
111
- image = preprocess_image(image)
112
- bbox = detect_with_yolo(image)
113
- cropped = image[bbox[1]:bbox[3], bbox[0]:bbox[2]] if bbox else image
114
- mask = segment(cropped)
115
-
116
- metrics = calculate_metrics(mask, cropped)
117
- full_mask = np.zeros(image.shape[:2], dtype=np.uint8)
118
  if bbox:
119
- full_mask[bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask
 
 
120
  else:
121
- full_mask = mask
 
 
 
 
 
 
 
 
 
122
 
123
- final_image = annotate(image, full_mask, metrics['contour'])
124
- _, buf = cv2.imencode(".png", final_image)
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- response = Response(content=buf.tobytes(), media_type="image/png")
127
- response.headers['X-Length-Cm'] = str(metrics['length'])
128
- response.headers['X-Breadth-Cm'] = str(metrics['breadth'])
129
- response.headers['X-Depth-Cm'] = str(metrics['depth'])
130
- response.headers['X-Area-Cm2'] = str(metrics['area'])
131
- response.headers['X-Moisture'] = str(metrics['moisture'])
132
- return response
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException, Response
2
  import cv2
3
  import numpy as np
4
  from ultralytics import YOLO
5
  import tensorflow as tf
6
+ import io
7
  from typing import Union
8
 
9
+ # --- Configuration ---
 
10
  PIXELS_PER_CM = 50.0
11
 
12
+ # --- App Initialization ---
13
+ app = FastAPI(
14
+ title="Wound Analysis API",
15
+ description="An API to analyze wound images, zoom to the wound, and return an annotated image with data in headers.",
16
+ version="3.5.0" # Version updated for polygon and zoom features
17
+ )
18
 
19
+ # --- Model Loading ---
20
+ def load_models():
21
+ """Loads the segmentation and YOLO models, handling potential errors."""
22
+ segmentation_model, yolo_model = None, None
23
+ try:
24
+ # Load your trained segmentation model
25
+ segmentation_model = tf.keras.models.load_model("segmentation_model.h5")
26
+ print("Segmentation model 'segmentation_model.h5' loaded successfully.")
27
+ except Exception as e:
28
+ print(f"Warning: Could not load segmentation model. Using fallback. Error: {e}")
29
+
30
+ try:
31
+ # Load your trained YOLO model for wound detection
32
+ yolo_model = YOLO("best.pt")
33
+ print("YOLO model 'best.pt' loaded successfully.")
34
+ except Exception as e:
35
+ print(f"Warning: Could not load YOLO model. Using fallback. Error: {e}")
36
+
37
+ return segmentation_model, yolo_model
38
+
39
+ segmentation_model, yolo_model = load_models()
40
+
41
+ # --- Helper Functions ---
42
 
 
43
  def preprocess_image(image: np.ndarray) -> np.ndarray:
44
+ """Applies a series of preprocessing steps to enhance the image for analysis."""
45
+ img_denoised = cv2.medianBlur(image, 3)
46
+ lab = cv2.cvtColor(img_denoised, cv2.COLOR_BGR2LAB)
47
+ l_channel, a_channel, b_channel = cv2.split(lab)
48
  clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
49
+ l_clahe = clahe.apply(l_channel)
50
+ lab_clahe = cv2.merge([l_clahe, a_channel, b_channel])
51
+ img_clahe = cv2.cvtColor(lab_clahe, cv2.COLOR_LAB2BGR)
52
+ gamma = 1.2
53
+ img_float = img_clahe.astype(np.float32) / 255.0
54
+ img_gamma = np.power(img_float, gamma)
55
+ return (img_gamma * 255).astype(np.uint8)
56
 
57
+ def detect_wound_region_yolo(image: np.ndarray) -> Union[tuple, None]:
58
+ """Detects the wound bounding box using the YOLO model."""
59
+ if not yolo_model: return None
60
  try:
61
  results = yolo_model.predict(image, verbose=False)
62
+ if results and results[0].boxes and len(results[0].boxes) > 0:
63
+ # Get the box with the highest confidence
64
  best_box = sorted(results[0].boxes, key=lambda b: b.conf[0], reverse=True)[0]
65
  coords = best_box.xyxy[0].cpu().numpy()
66
  return tuple(map(int, coords))
67
  except Exception as e:
68
+ print(f"YOLO prediction failed: {e}")
69
+ return None
70
+
71
+ def segment_wound_with_model(image: np.ndarray) -> Union[np.ndarray, None]:
72
+ """Segments the wound from the image using the primary segmentation model."""
73
+ if not segmentation_model:
74
+ return None
75
+ try:
76
+ input_shape = segmentation_model.input_shape[1:3]
77
+ img_resized = cv2.resize(image, (input_shape[1], input_shape[0]))
78
+ img_norm = np.expand_dims(img_resized.astype(np.float32) / 255.0, axis=0)
79
+
80
+ prediction = segmentation_model.predict(img_norm, verbose=0)
81
+
82
+ # Handle nested list or Tensor output from some model versions
83
+ while isinstance(prediction, list):
84
+ prediction = prediction[0]
85
+ if isinstance(prediction, tf.Tensor):
86
+ prediction = prediction.numpy()
87
+
88
+ pred_mask = prediction[0]
89
+ pred_mask_resized = cv2.resize(pred_mask, (image.shape[1], image.shape[0]))
90
+ return (pred_mask_resized.squeeze() >= 0.5).astype(np.uint8) * 255
91
+ except Exception as e:
92
+ print(f"Segmentation model prediction failed: {e}")
93
  return None
94
 
95
+ def segment_wound_with_fallback(image: np.ndarray) -> np.ndarray:
96
+ """A fallback segmentation method using k-means clustering if the primary model fails."""
97
+ pixels = image.reshape((-1, 3)).astype(np.float32)
98
  criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
99
+ _, labels, centers = cv2.kmeans(pixels, 2, None, criteria, 5, cv2.KMEANS_PP_CENTERS)
100
+ centers_lab = cv2.cvtColor(centers.reshape(1, -1, 3).astype(np.uint8), cv2.COLOR_BGR2LAB)[0]
101
+ wound_cluster_idx = np.argmax(centers_lab[:, 1]) # 'a' channel in LAB is good for redness
102
+ mask = (labels.reshape(image.shape[:2]) == wound_cluster_idx).astype(np.uint8) * 255
103
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
104
+ if contours:
105
+ largest_contour = max(contours, key=cv2.contourArea)
106
+ refined_mask = np.zeros_like(mask)
107
+ cv2.drawContours(refined_mask, [largest_contour], -1, 255, cv2.FILLED)
108
+ return refined_mask
109
+ return mask
110
+
111
+ def calculate_metrics(mask: np.ndarray) -> dict:
112
+ """Calculates dimensional and analytical metrics from the wound mask."""
113
+ wound_pixels = cv2.countNonZero(mask)
114
+ if wound_pixels == 0:
115
+ return {"area_cm2": 0.0, "length_cm": 0.0, "breadth_cm": 0.0, "depth_cm": 0.0, "moisture": 0.0}
116
+
117
+ area_cm2 = wound_pixels / (PIXELS_PER_CM ** 2)
118
+
 
 
 
 
 
 
 
119
  contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
120
  if not contours:
121
+ return {"area_cm2": area_cm2, "length_cm": 0.0, "breadth_cm": 0.0, "depth_cm": 0.0, "moisture": 0.0}
122
+
123
+ largest_contour = max(contours, key=cv2.contourArea)
124
+ (_, (width, height), _) = cv2.minAreaRect(largest_contour)
125
+
126
+ length_cm = max(width, height) / PIXELS_PER_CM
127
+ breadth_cm = min(width, height) / PIXELS_PER_CM
128
+
129
+ # Placeholder for depth and moisture calculation.
130
+ # These would typically require more advanced sensors or algorithms.
131
+ depth_cm = 0.1 # Placeholder value
132
+ moisture = 75.0 # Placeholder value
133
+
134
+ return {"area_cm2": area_cm2, "length_cm": length_cm, "breadth_cm": breadth_cm, "depth_cm": depth_cm, "moisture": moisture}
135
+
136
+ def create_visual_overlay_and_zoom(image: np.ndarray, mask: np.ndarray, bbox: tuple = None) -> np.ndarray:
137
+ """Draws a polygon around the wound, applies a color overlay, and zooms to the region."""
138
+ annotated_img = image.copy()
139
+
140
+ # Find contours to draw the polygon
141
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
142
+ if contours:
143
+ # Draw a distinct polygon outline around the wound
144
+ cv2.drawContours(annotated_img, contours, -1, (0, 255, 255), 2) # Yellow, 2px thick
145
+
146
+ # Zoom to the wound area if a bounding box is available
147
+ if bbox:
148
+ xmin, ymin, xmax, ymax = bbox
149
+ # Add a 10% padding around the bounding box for better context
150
+ padding_x = int((xmax - xmin) * 0.10)
151
+ padding_y = int((ymax - ymin) * 0.10)
152
+
153
+ # Ensure coordinates are within image bounds
154
+ zoom_xmin = max(0, xmin - padding_x)
155
+ zoom_ymin = max(0, ymin - padding_y)
156
+ zoom_xmax = min(image.shape[1], xmax + padding_x)
157
+ zoom_ymax = min(image.shape[0], ymax + padding_y)
158
+
159
+ return annotated_img[zoom_ymin:zoom_ymax, zoom_xmin:zoom_xmax]
160
+
161
+ return annotated_img
162
 
 
 
 
 
 
163
 
164
+ # --- Main API Endpoint ---
165
  @app.post("/analyze_wound")
166
  async def analyze_wound(file: UploadFile = File(...)):
167
+ """
168
+ Receives an image, analyzes the wound, and returns a zoomed,
169
+ annotated image with metrics in the response headers.
170
+ """
171
  contents = await file.read()
172
+ image_array = np.frombuffer(contents, np.uint8)
173
+ original_image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
174
+ if original_image is None:
175
+ raise HTTPException(status_code=400, detail="Invalid or corrupt image file")
176
+
177
+ processed_image = preprocess_image(original_image)
178
+
179
+ # Use YOLO to find the general wound region
180
+ bbox = detect_wound_region_yolo(processed_image)
181
+
 
 
182
  if bbox:
183
+ xmin, ymin, xmax, ymax = bbox
184
+ # Crop to the detected region for more accurate segmentation
185
+ cropped_for_segmentation = processed_image[ymin:ymax, xmin:xmax]
186
  else:
187
+ # If no wound is detected, analyze the whole image as a fallback
188
+ cropped_for_segmentation = processed_image
189
+
190
+ # Segment the wound within the cropped region
191
+ mask = segment_wound_with_model(cropped_for_segmentation)
192
+ if mask is None:
193
+ mask = segment_wound_with_fallback(cropped_for_segmentation)
194
+
195
+ # Calculate metrics based on the precise mask
196
+ metrics = calculate_metrics(mask)
197
 
198
+ # Create a full-sized mask to pass to the visualization function
199
+ full_mask = np.zeros(original_image.shape[:2], dtype=np.uint8)
200
+ if bbox:
201
+ full_mask[ymin:ymax, xmin:xmax] = mask
202
+ else:
203
+ full_mask = mask
204
+
205
+ # Generate the final visual output: draw polygon and zoom
206
+ final_image = create_visual_overlay_and_zoom(original_image, full_mask, bbox)
207
+
208
+ success, png_data = cv2.imencode(".png", final_image)
209
+ if not success:
210
+ raise HTTPException(status_code=500, detail="Failed to encode output image")
211
 
212
+ # Set the custom headers as requested
213
+ headers = {
214
+ 'X-Length-Cm': f"{metrics['length_cm']:.2f}",
215
+ 'X-Breadth-Cm': f"{metrics['breadth_cm']:.2f}",
216
+ 'X-Depth-Cm': f"{metrics['depth_cm']:.2f}",
217
+ 'X-Area-Cm2': f"{metrics['area_cm2']:.2f}",
218
+ 'X-Moisture': f"{metrics['moisture']:.1f}"
219
+ }
220
+
221
+ return Response(content=png_data.tobytes(), media_type="image/png", headers=headers)