crabbly commited on
Commit
6b3b153
·
verified ·
1 Parent(s): bce7c2a

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +29 -18
main.py CHANGED
@@ -17,7 +17,7 @@ from skimage import color
17
  # OOM PREVENTION
18
  torch.set_num_threads(1)
19
 
20
- # Import your helpers (assuming cv_helpers.py is in the same folder)
21
  from cv_helpers import blend_mask_overlays, stem_tip_tangent_deg
22
 
23
  # --- CONFIGURATION ---
@@ -194,7 +194,6 @@ class WatermelonProcessor:
194
  popt_mid, _ = curve_fit(parabola, (gap_points[:,0]-y_mean)/y_span, gap_points[:,1], bounds=([-w*0.08, -np.inf, -np.inf],[w*0.08, np.inf, np.inf]))
195
  except: popt_mid = [0.0, 0.0, cx]
196
 
197
- # FIXED TYPO HERE (ys_extrap)
198
  ys_extrap = np.linspace(0, h, 500)
199
  xs_extrap = parabola((ys_extrap - y_mean)/y_span, *popt_mid)
200
  pts_rot = np.vstack([xs_extrap, ys_extrap, np.ones_like(ys_extrap)])
@@ -210,6 +209,7 @@ class WatermelonProcessor:
210
  if image is None: return ProcessResult(success=False, message="Could not decode image.")
211
  h, w = image.shape[:2]
212
 
 
213
  dE_initial, dE_final, cm_per_px, checker_corners = None, None, None, None
214
 
215
  try:
@@ -229,8 +229,9 @@ class WatermelonProcessor:
229
  except Exception as e:
230
  print(f"Calibration skipped for {source_name}: {e}")
231
 
 
232
  results = self.model(image, conf=0.25, retina_masks=True, verbose=False)
233
- rind_mask, flesh_l, flesh_r = np.zeros((h, w), dtype=np.uint8), np.zeros((h, w), dtype=np.uint8), np.zeros((h, w), dtype=np.uint8)
234
 
235
  if results[0].masks is None:
236
  return ProcessResult(success=False, message="No masks detected.")
@@ -239,10 +240,18 @@ class WatermelonProcessor:
239
  contour = np.array(mask_data, dtype=np.int32)
240
  c_id = int(cls)
241
  if c_id == 0: cv2.drawContours(rind_mask, [contour], -1, 255, -1)
242
- elif c_id == 1: cv2.drawContours(flesh_l, [contour], -1, 255, -1)
243
- elif c_id == 2: cv2.drawContours(flesh_r, [contour], -1, 255, -1)
244
 
245
- flesh_combined = cv2.bitwise_or(flesh_l, flesh_r)
 
 
 
 
 
 
 
 
 
246
  perimeter_data = self.get_stable_perimeter_data(rind_mask, flesh_combined)
247
  if perimeter_data is None: return ProcessResult(success=False, message="No stable perimeter.")
248
 
@@ -263,6 +272,7 @@ class WatermelonProcessor:
263
  r_fit = self.watermelon_model(t_fit, *popt) * scale
264
  fit_pts = np.array([[r * np.cos(t) + cx, cy - r * np.sin(t)] for t, r in zip(t_fit, r_fit)])
265
 
 
266
  orig_scale = 1.0 / scale_ratio
267
  if cm_per_px is None: cm_per_px = 1.0
268
 
@@ -270,24 +280,26 @@ class WatermelonProcessor:
270
  height_px = float(np.max(fit_pts[:, 1]) - np.min(fit_pts[:, 1]))
271
  perimeter_px = float(np.sum(np.linalg.norm(np.diff(fit_pts, axis=0), axis=1)) + np.linalg.norm(fit_pts[-1] - fit_pts[0]))
272
 
273
- width_val = width_px * cm_per_px * orig_scale
274
- height_val = height_px * cm_per_px * orig_scale
275
- perimeter_val = perimeter_px * cm_per_px * orig_scale
 
276
 
277
- midline = self.get_dual_mask_midline(flesh_l, flesh_r, rind_cnt, fit_pts, cx, cy)
 
278
  output = blend_mask_overlays(image, rind_mask, flesh_combined)
279
 
280
  if checker_corners is not None:
281
- cv2.polylines(output, [np.int32(checker_corners)], True, (0, 165, 255), 4)
282
 
283
- if len(midline) > 1: cv2.polylines(output, [midline.astype(np.int32)], False, (0, 255, 255), 3)
284
- cv2.polylines(output,[fit_pts.astype(np.int32)], True, (0, 255, 0), 3)
285
 
286
  stem = stem_tip_tangent_deg(rind_cnt, (cx, cy))
287
  if stem is not None:
288
  tx, ty, tdeg = stem
289
- L = min(w, h) * 0.08
290
  rad = np.deg2rad(tdeg)
 
291
  p1 = (int(round(tx)), int(round(ty)))
292
  p2 = (int(round(tx + L * np.cos(rad))), int(round(ty + L * np.sin(rad))))
293
  cv2.circle(output, p1, 6, (255, 0, 255), -1)
@@ -317,18 +329,17 @@ def read_root(): return {"status": "Watermelon API is awake!"}
317
  @app.post("/process_single")
318
  async def process_single(file: UploadFile = File(...)):
319
  contents = await file.read()
320
- nparr = np.frombuffer(contents, np.uint8)
321
- img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
322
 
323
- h, w = img.shape[:2]
324
  scale_ratio = 1.0
 
325
  if max(h, w) > MAX_IMAGE_SIZE:
326
  scale_ratio = MAX_IMAGE_SIZE / float(max(h, w))
327
  img = cv2.resize(img, (int(w * scale_ratio), int(h * scale_ratio)), interpolation=cv2.INTER_AREA)
328
 
329
  res = processor.process_image(img, file.filename, scale_ratio)
330
 
331
- del img, nparr, contents
332
  gc.collect()
333
 
334
  return res.__dict__
 
17
  # OOM PREVENTION
18
  torch.set_num_threads(1)
19
 
20
+ # Import your helpers
21
  from cv_helpers import blend_mask_overlays, stem_tip_tangent_deg
22
 
23
  # --- CONFIGURATION ---
 
194
  popt_mid, _ = curve_fit(parabola, (gap_points[:,0]-y_mean)/y_span, gap_points[:,1], bounds=([-w*0.08, -np.inf, -np.inf],[w*0.08, np.inf, np.inf]))
195
  except: popt_mid = [0.0, 0.0, cx]
196
 
 
197
  ys_extrap = np.linspace(0, h, 500)
198
  xs_extrap = parabola((ys_extrap - y_mean)/y_span, *popt_mid)
199
  pts_rot = np.vstack([xs_extrap, ys_extrap, np.ones_like(ys_extrap)])
 
209
  if image is None: return ProcessResult(success=False, message="Could not decode image.")
210
  h, w = image.shape[:2]
211
 
212
+ # --- 1. CALIBRATION & SCALING ---
213
  dE_initial, dE_final, cm_per_px, checker_corners = None, None, None, None
214
 
215
  try:
 
229
  except Exception as e:
230
  print(f"Calibration skipped for {source_name}: {e}")
231
 
232
+ # --- 2. YOLO INFERENCE ---
233
  results = self.model(image, conf=0.25, retina_masks=True, verbose=False)
234
+ rind_mask, flesh_contours = np.zeros((h, w), dtype=np.uint8), []
235
 
236
  if results[0].masks is None:
237
  return ProcessResult(success=False, message="No masks detected.")
 
240
  contour = np.array(mask_data, dtype=np.int32)
241
  c_id = int(cls)
242
  if c_id == 0: cv2.drawContours(rind_mask, [contour], -1, 255, -1)
243
+ elif c_id == 1: flesh_contours.append(contour)
 
244
 
245
+ flesh_contours.sort(key=lambda cnt: cv2.moments(cnt)['m10'] / (cv2.moments(cnt)['m00'] + 1e-5))
246
+ flesh_l_m, flesh_r_m = np.zeros((h, w), dtype=np.uint8), np.zeros((h, w), dtype=np.uint8)
247
+
248
+ if len(flesh_contours) >= 2:
249
+ cv2.drawContours(flesh_l_m, [flesh_contours[0]], -1, 255, -1)
250
+ cv2.drawContours(flesh_r_m,[flesh_contours[1]], -1, 255, -1)
251
+ elif len(flesh_contours) == 1:
252
+ cv2.drawContours(flesh_l_m,[flesh_contours[0]], -1, 255, -1)
253
+
254
+ flesh_combined = cv2.bitwise_or(flesh_l_m, flesh_r_m)
255
  perimeter_data = self.get_stable_perimeter_data(rind_mask, flesh_combined)
256
  if perimeter_data is None: return ProcessResult(success=False, message="No stable perimeter.")
257
 
 
272
  r_fit = self.watermelon_model(t_fit, *popt) * scale
273
  fit_pts = np.array([[r * np.cos(t) + cx, cy - r * np.sin(t)] for t, r in zip(t_fit, r_fit)])
274
 
275
+ # --- 3. DIMENSIONAL MATH (IN CM) ---
276
  orig_scale = 1.0 / scale_ratio
277
  if cm_per_px is None: cm_per_px = 1.0
278
 
 
280
  height_px = float(np.max(fit_pts[:, 1]) - np.min(fit_pts[:, 1]))
281
  perimeter_px = float(np.sum(np.linalg.norm(np.diff(fit_pts, axis=0), axis=1)) + np.linalg.norm(fit_pts[-1] - fit_pts[0]))
282
 
283
+ # CRITICAL FIX: Wrapped in float() to prevent Numpy JSON serialization errors
284
+ width_val = float(width_px * cm_per_px * orig_scale)
285
+ height_val = float(height_px * cm_per_px * orig_scale)
286
+ perimeter_val = float(perimeter_px * cm_per_px * orig_scale)
287
 
288
+ # --- 4. DRAWING ---
289
+ midline = self.get_dual_mask_midline(flesh_l_m, flesh_r_m, rind_cnt, fit_pts, cx, cy)
290
  output = blend_mask_overlays(image, rind_mask, flesh_combined)
291
 
292
  if checker_corners is not None:
293
+ cv2.polylines(output,[np.int32(checker_corners)], True, (0, 165, 255), 4)
294
 
295
+ if len(midline) > 1: cv2.polylines(output,[midline.astype(np.int32)], False, (0, 255, 255), 3)
296
+ cv2.polylines(output, [fit_pts.astype(np.int32)], True, (0, 255, 0), 3)
297
 
298
  stem = stem_tip_tangent_deg(rind_cnt, (cx, cy))
299
  if stem is not None:
300
  tx, ty, tdeg = stem
 
301
  rad = np.deg2rad(tdeg)
302
+ L = min(w, h) * 0.08
303
  p1 = (int(round(tx)), int(round(ty)))
304
  p2 = (int(round(tx + L * np.cos(rad))), int(round(ty + L * np.sin(rad))))
305
  cv2.circle(output, p1, 6, (255, 0, 255), -1)
 
329
  @app.post("/process_single")
330
  async def process_single(file: UploadFile = File(...)):
331
  contents = await file.read()
332
+ img = cv2.imdecode(np.frombuffer(contents, np.uint8), cv2.IMREAD_COLOR)
 
333
 
 
334
  scale_ratio = 1.0
335
+ h, w = img.shape[:2]
336
  if max(h, w) > MAX_IMAGE_SIZE:
337
  scale_ratio = MAX_IMAGE_SIZE / float(max(h, w))
338
  img = cv2.resize(img, (int(w * scale_ratio), int(h * scale_ratio)), interpolation=cv2.INTER_AREA)
339
 
340
  res = processor.process_image(img, file.filename, scale_ratio)
341
 
342
+ del img, contents
343
  gc.collect()
344
 
345
  return res.__dict__