crabbly commited on
Commit
d0dc7e3
·
verified ·
1 Parent(s): c85fc32

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +147 -112
main.py CHANGED
@@ -12,18 +12,95 @@ from ultralytics import YOLO
12
  from fastapi import FastAPI, UploadFile, File
13
  from fastapi.middleware.cors import CORSMiddleware
14
  import uvicorn
 
15
 
 
16
  torch.set_num_threads(1)
17
 
 
18
  from cv_helpers import blend_mask_overlays, stem_tip_tangent_deg
19
- import color_calibration as calib
20
- import test_color_eval as eval
21
 
22
  # --- CONFIGURATION ---
23
  MODEL_PATH = "best.pt"
24
- # HF has 16GB RAM, so we can use a higher resolution to ensure the checkerboard is detected!
25
- MAX_IMAGE_SIZE = 2048
26
- CHECKER_WIDTH_CM = 6.3 # 63 mm = 6.3 cm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  @dataclass
29
  class ProcessResult:
@@ -42,18 +119,16 @@ class WatermelonProcessor:
42
  def __init__(self, model_path: str):
43
  self.model = YOLO(model_path)
44
 
 
45
  self.ref24 = None
46
  if os.path.exists("reference.png"):
47
  try:
48
  ref_img = cv2.imread("reference.png")
49
- ref_corners = calib.detect_checker_corners(ref_img)
50
- ref_warped = calib.warp_checker(ref_img, ref_corners)
51
- self.ref24 = calib.sample_24_patches(ref_warped)
52
- print("Reference ColorChecker loaded successfully.")
53
  except Exception as e:
54
- print(f"Failed to extract reference patches: {e}")
55
- else:
56
- print("WARNING: 'reference.png' not found. Color Correction will be skipped.")
57
 
58
  @staticmethod
59
  def watermelon_model(theta, Rx, Ry, c_a, d_top, w_top, d_bot, w_bot, phi, c_skew, c_bend):
@@ -68,26 +143,23 @@ class WatermelonProcessor:
68
  def get_stable_perimeter_data(rind_mask, flesh_combined):
69
  cnts, _ = cv2.findContours(rind_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
70
  if not cnts: return None
71
-
72
- # Pick the rind that specifically surrounds the flesh
73
- best_cnt = None
74
- max_overlap = -1
75
  for cnt in cnts:
76
- temp_mask = np.zeros_like(rind_mask)
77
- cv2.drawContours(temp_mask, [cnt], -1, 255, -1)
78
- overlap_area = cv2.countNonZero(cv2.bitwise_and(temp_mask, flesh_combined))
79
- if overlap_area > max_overlap:
80
- max_overlap = overlap_area
81
- best_cnt = cnt
82
 
83
  if best_cnt is None: best_cnt = max(cnts, key=cv2.contourArea)
84
  M = cv2.moments(best_cnt)
85
  if M["m00"] == 0: return None
86
 
87
- cx, cy = M["m10"] / M["m00"], M["m01"] / M["m00"]
88
  pts = best_cnt.reshape(-1, 2)
89
  dx, dy = pts[:, 0] - cx, cy - pts[:, 1]
90
  r_vals, t_vals = np.sqrt(dx**2 + dy**2), np.arctan2(dy, dx)
 
91
  num_bins = 360
92
  bins = np.linspace(-np.pi, np.pi, num_bins + 1)
93
  raw_r = np.full(num_bins, np.nan)
@@ -98,28 +170,17 @@ class WatermelonProcessor:
98
  valid_idx = np.where(~np.isnan(raw_r))[0]
99
  if len(valid_idx) == 0: return None
100
  raw_r[np.isnan(raw_r)] = np.interp(np.where(np.isnan(raw_r))[0], valid_idx, raw_r[valid_idx], period=360)
101
- final_r = median_filter(raw_r, size=7, mode="wrap")
102
- final_theta = (bins[:-1] + bins[1:]) / 2.0
103
- return final_theta, final_r, (cx, cy), best_cnt
104
 
105
  @staticmethod
106
- def get_dual_mask_midline(f_left, f_right, rind_cnt, predicted_cnt, cx, cy):
107
  h, w = f_left.shape
108
- if len(rind_cnt) > 5:
109
- _, (ma, Ma), angle = cv2.fitEllipse(rind_cnt)
110
- rot_angle = angle if ma < Ma else angle + 90
111
- else: rot_angle = 0
112
 
113
  m_rot = cv2.getRotationMatrix2D((cx, cy), rot_angle, 1.0)
114
  m_inv = cv2.getRotationMatrix2D((cx, cy), -rot_angle, 1.0)
115
- l_rot = cv2.warpAffine(f_left, m_rot, (w, h))
116
- r_rot = cv2.warpAffine(f_right, m_rot, (w, h))
117
-
118
- l_idx = np.where(l_rot > 0)[1]
119
- r_idx = np.where(r_rot > 0)[1]
120
- if len(l_idx) > 0 and len(r_idx) > 0:
121
- if np.mean(l_idx) > np.mean(r_idx):
122
- l_rot, r_rot = r_rot, l_rot
123
 
124
  gap_points =[]
125
  y_l, y_r = np.where(l_rot > 0)[0], np.where(r_rot > 0)[0]
@@ -133,22 +194,18 @@ class WatermelonProcessor:
133
  if len(gap_points) > 10:
134
  y_min, y_max = np.min(gap_points[:, 0]), np.max(gap_points[:, 0])
135
  y_span, y_mean = max(y_max - y_min, 1), (y_max + y_min) / 2.0
136
- y_norm, x_data = (gap_points[:, 0] - y_mean) / y_span, gap_points[:, 1]
137
-
138
- def parabola(y_n, a, b, c): return a * (y_n**2) + b * y_n + c
139
- max_bend = w * 0.08
140
- try: popt_mid, _ = curve_fit(parabola, y_norm, x_data, bounds=([-max_bend, -np.inf, -np.inf], [max_bend, np.inf, np.inf]))
141
  except: popt_mid = [0.0, 0.0, cx]
142
-
143
- ys_extrap = np.linspace(0, h, 500)
144
- xs_extrap = parabola((ys_extrap - y_mean) / y_span, *popt_mid)
145
- pts_rot = np.vstack([xs_extrap, ys_extrap, np.ones_like(xs_extrap)])
146
  else:
147
- ys_extrap = np.linspace(0, h, 500)
148
- pts_rot = np.vstack([np.full_like(ys_extrap, cx), ys_extrap, np.ones_like(ys_extrap)])
149
 
150
  pts_orig = (m_inv @ pts_rot).T
151
- pred_cnt_cv = predicted_cnt.reshape(-1, 1, 2).astype(np.int32)
152
  return np.array([pt for pt in pts_orig if cv2.pointPolygonTest(pred_cnt_cv, (float(pt[0]), float(pt[1])), False) >= 0])
153
 
154
  def process_image(self, image: np.ndarray, source_name: str, scale_ratio: float) -> ProcessResult:
@@ -159,53 +216,40 @@ class WatermelonProcessor:
159
  dE_initial, dE_final, cm_per_px, checker_corners = None, None, None, None
160
 
161
  try:
162
- checker_corners = calib.detect_checker_corners(image)
 
163
  top_width = np.linalg.norm(checker_corners[1] - checker_corners[2])
164
  bot_width = np.linalg.norm(checker_corners[0] - checker_corners[3])
165
- px_width = (top_width + bot_width) / 2.0
166
- cm_per_px = CHECKER_WIDTH_CM / px_width
167
 
168
  if self.ref24 is not None:
169
- tgt_warped = calib.warp_checker(image, checker_corners)
170
- tgt24 = calib.sample_24_patches(tgt_warped)
171
-
172
- dE_initial = float(np.mean(eval.compute_deltaE_00(tgt24, self.ref24)))
173
 
174
- # Apply Color Correction Pipeline
175
- image = calib.apply_pipeline(image, self.ref24, tgt24)
176
 
177
- # Re-check the corrected patches for Final dE
178
- tgt_warped_corr = calib.warp_checker(image, checker_corners)
179
- tgt24_corr = calib.sample_24_patches(tgt_warped_corr)
180
- dE_final = float(np.mean(eval.compute_deltaE_00(tgt24_corr, self.ref24)))
181
  except Exception as e:
182
  print(f"Calibration skipped for {source_name}: {e}")
183
 
184
- # --- 2. YOLO INFERENCE ---
185
  results = self.model(image, conf=0.25, retina_masks=True, verbose=False)
186
- rind_mask = np.zeros((h, w), dtype=np.uint8)
187
- flesh_contours = []
188
-
189
- if results[0].masks is not None:
190
- for mask_data, cls in zip(results[0].masks.xy, results[0].boxes.cls):
191
- contour = np.array(mask_data, dtype=np.int32)
192
- if int(cls) == 0:
193
- cv2.drawContours(rind_mask, [contour], -1, 255, -1)
194
- elif int(cls) == 1:
195
- flesh_contours.append(contour)
196
-
197
- # Split Class 1 into Left and Right physically!
198
- flesh_contours.sort(key=lambda cnt: cv2.moments(cnt)['m10'] / (cv2.moments(cnt)['m00'] + 1e-5))
199
- flesh_l_m, flesh_r_m = np.zeros((h, w), dtype=np.uint8), np.zeros((h, w), dtype=np.uint8)
200
- if len(flesh_contours) >= 2:
201
- cv2.drawContours(flesh_l_m, [flesh_contours[0]], -1, 255, -1)
202
- cv2.drawContours(flesh_r_m, [flesh_contours[1]], -1, 255, -1)
203
- elif len(flesh_contours) == 1:
204
- cv2.drawContours(flesh_l_m, [flesh_contours[0]], -1, 255, -1)
205
-
206
- flesh_combined = cv2.bitwise_or(flesh_l_m, flesh_r_m)
207
-
208
- # --- 3. FIT & EXTRACTION ---
209
  perimeter_data = self.get_stable_perimeter_data(rind_mask, flesh_combined)
210
  if perimeter_data is None: return ProcessResult(success=False, message="No stable perimeter.")
211
 
@@ -213,11 +257,9 @@ class WatermelonProcessor:
213
  scale = np.mean(r_raw)
214
 
215
  try:
216
- popt, _ = curve_fit(
217
- self.watermelon_model, t_data, r_raw / scale,
218
  p0=[1.0, 1.1, 0.0, 0.05, 3.0, 0.05, 3.0, 0.0, 0.0, 0.0],
219
- bounds=([0.5, 0.5, -0.4, 0.0, 0.1, 0.0, 0.1, -1.5, -0.2, -0.2],[2.0, 2.0, 0.4, 0.5, 50.0, 0.5, 50.0, 1.5, 0.2, 0.2]),
220
- )
221
  except Exception as exc: return ProcessResult(success=False, message=f"Fit failed: {exc}")
222
 
223
  r2 = 1 - (np.sum((r_raw / scale - self.watermelon_model(t_data, *popt)) ** 2) / np.sum((r_raw / scale - 1) ** 2))
@@ -225,23 +267,18 @@ class WatermelonProcessor:
225
  r_fit = self.watermelon_model(t_fit, *popt) * scale
226
  fit_pts = np.array([[r * np.cos(t) + cx, cy - r * np.sin(t)] for t, r in zip(t_fit, r_fit)])
227
 
228
- # Re-scale back to original size for true measurements
229
  orig_scale = 1.0 / scale_ratio
230
- if cm_per_px is None: cm_per_px = 1.0 # Fallback to pixel units if checker failed
231
 
232
- width_px = float(np.max(fit_pts[:, 0]) - np.min(fit_pts[:, 0]))
233
- height_px = float(np.max(fit_pts[:, 1]) - np.min(fit_pts[:, 1]))
234
- 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]))
235
-
236
- width_val = width_px * cm_per_px * orig_scale
237
- height_val = height_px * cm_per_px * orig_scale
238
- perimeter_val = perimeter_px * cm_per_px * orig_scale
239
 
240
  # --- 4. DRAWING ---
241
- midline = self.get_dual_mask_midline(flesh_l_m, flesh_r_m, rind_cnt, fit_pts, cx, cy)
242
  output = blend_mask_overlays(image, rind_mask, flesh_combined)
243
 
244
- # Color Checker Box
245
  if checker_corners is not None:
246
  cv2.polylines(output, [np.int32(checker_corners)], True, (0, 165, 255), 4)
247
 
@@ -251,20 +288,19 @@ class WatermelonProcessor:
251
  stem = stem_tip_tangent_deg(rind_cnt, (cx, cy))
252
  if stem is not None:
253
  tx, ty, tdeg = stem
254
- L = min(w, h) * 0.08
255
  p1 = (int(round(tx)), int(round(ty)))
256
- p2 = (int(round(tx + L * np.cos(np.deg2rad(tdeg)))), int(round(ty + L * np.sin(np.deg2rad(tdeg)))))
257
  cv2.circle(output, p1, 6, (255, 0, 255), -1)
258
  cv2.line(output, p1, p2, (255, 0, 255), 2)
259
 
260
- _, buffer = cv2.imencode('.jpg', output, [cv2.IMWRITE_JPEG_QUALITY, 85])
261
- img_base64 = base64.b64encode(buffer).decode('utf-8')
262
 
263
  return ProcessResult(
264
  success=True, message="Success", r2_score=float(r2),
265
  width_val=width_val, height_val=height_val, perimeter_val=perimeter_val,
266
  delta_e_initial=dE_initial, delta_e_final=dE_final,
267
- image_base64=img_base64, filename=source_name
268
  )
269
 
270
 
@@ -282,18 +318,17 @@ def read_root(): return {"status": "Watermelon API is awake!"}
282
  @app.post("/process_single")
283
  async def process_single(file: UploadFile = File(...)):
284
  contents = await file.read()
285
- nparr = np.frombuffer(contents, np.uint8)
286
- img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
287
 
288
- h, w = img.shape[:2]
289
  scale_ratio = 1.0
 
290
  if max(h, w) > MAX_IMAGE_SIZE:
291
  scale_ratio = MAX_IMAGE_SIZE / float(max(h, w))
292
  img = cv2.resize(img, (int(w * scale_ratio), int(h * scale_ratio)), interpolation=cv2.INTER_AREA)
293
 
294
  res = processor.process_image(img, file.filename, scale_ratio)
295
 
296
- del img, nparr, contents
297
  gc.collect()
298
 
299
  return res.__dict__
 
12
  from fastapi import FastAPI, UploadFile, File
13
  from fastapi.middleware.cors import CORSMiddleware
14
  import uvicorn
15
+ from skimage import color
16
 
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 ---
24
  MODEL_PATH = "best.pt"
25
+ MAX_IMAGE_SIZE = 2048 # Large enough to ensure the color checker is clearly visible
26
+ CHECKER_WIDTH_CM = 6.3 # Physical width of the X-Rite ColorChecker Classic
27
+
28
+ # ==============================================================================
29
+ # --- COLOR CALIBRATION LOGIC (Embedded) ---
30
+ # ==============================================================================
31
+ def to_linear_srgb(u8_bgr):
32
+ rgb = cv2.cvtColor(u8_bgr, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
33
+ a = 0.055
34
+ return np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + a) / (1 + a)) ** 2.4)
35
+
36
+ def to_srgb_u8(lin_rgb):
37
+ a = 0.055
38
+ srgb = np.where(lin_rgb <= 0.0031308, 12.92 * lin_rgb, (1 + a) * np.power(np.maximum(lin_rgb, 0), 1/2.4) - a)
39
+ return cv2.cvtColor((np.clip(srgb, 0, 1) * 255.0).astype(np.uint8), cv2.COLOR_RGB2BGR)
40
+
41
+ def detect_checker_corners(img_bgr):
42
+ det = cv2.mcc.CCheckerDetector_create()
43
+ if not det.process(img_bgr, cv2.mcc.MCC24):
44
+ raise RuntimeError("ColorChecker not found")
45
+ cc = det.getListColorChecker()[0]
46
+ return np.array(cc.getBox() if hasattr(cc, "getBox") else cc.getCorners(), dtype=np.float32)
47
+
48
+ def warp_checker(img, corners, out_w=600, out_h=400):
49
+ dst = np.float32([[0, out_h-1],[0, 0], [out_w-1, 0],[out_w-1, out_h-1]])
50
+ H_mat = cv2.getPerspectiveTransform(corners, dst)
51
+ return cv2.warpPerspective(img, H_mat, (out_w, out_h), flags=cv2.INTER_CUBIC)
52
+
53
+ def sample_24_patches(warped, margin=12):
54
+ H, W = warped.shape[:2]
55
+ cell_w, cell_h = W / 6.0, H / 4.0
56
+ lin = to_linear_srgb(warped)
57
+ means =[]
58
+ for r in range(4):
59
+ for c in range(6):
60
+ x0, x1 = int(c * cell_w + margin), int((c+1) * cell_w - margin)
61
+ y0, y1 = int(r * cell_h + margin), int((r+1) * cell_h - margin)
62
+ means.append(np.median(lin[y0:y1, x0:x1].reshape(-1, 3), axis=0))
63
+ return np.stack(means, 0)
64
+
65
+ def compute_deltaE_00(lin_src, lin_ref):
66
+ srgb_src = to_srgb_u8(lin_src).astype(np.float32) / 255.0
67
+ srgb_ref = to_srgb_u8(lin_ref).astype(np.float32) / 255.0
68
+ return color.deltaE_ciede2000(color.rgb2lab(srgb_src.reshape(1, -1, 3)), color.rgb2lab(srgb_ref.reshape(1, -1, 3))).flatten()
69
+
70
+ def apply_color_pipeline(target_bgr, ref24, tgt24):
71
+ # White Balance
72
+ gains = np.median(ref24[18:24], axis=0) / np.maximum(np.median(tgt24[18:24], axis=0), 1e-6)
73
+ lin = to_linear_srgb(target_bgr)
74
+ lin_wb = lin * gains.reshape(1, 1, 3)
75
+ tgt24_wb = tgt24 * gains
76
+
77
+ # CCM
78
+ M = np.linalg.lstsq(tgt24_wb[:18], ref24[:18], rcond=None)[0].T
79
+ corrected = (lin_wb.reshape(-1, 3) @ M.T).reshape(lin_wb.shape)
80
+ tgt24_ccm = tgt24_wb @ M.T
81
+
82
+ # Luma Curve
83
+ w = np.array([0.2126, 0.7152, 0.0722], np.float32)
84
+ Ls, Lt = (tgt24_ccm[19:23] @ w), (ref24[19:23] @ w)
85
+ sort_idx = np.argsort(Ls)
86
+ Ls, Lt = np.concatenate([[0.01], Ls[sort_idx], [0.98]]), np.concatenate([[0.01], Lt[sort_idx],[0.98]])
87
+
88
+ L = np.clip(np.tensordot(corrected, w, axes=([2], [0])), 0, 1)
89
+ Lt_mapped = np.interp(L, Ls, Lt)
90
+
91
+ # Soft Rolloff
92
+ knee, strength = 0.90, 0.6
93
+ below = Lt_mapped < knee
94
+ Lt_final = np.empty_like(Lt_mapped)
95
+ Lt_final[below] = Lt_mapped[below]
96
+ Lt_final[~below] = knee + (1.0 - knee) * (1.0 - np.exp(-strength * ((Lt_mapped[~below] - knee) / (1.0 - knee))))
97
+
98
+ scale = (Lt_final + 1e-6) / (L + 1e-6)
99
+ return to_srgb_u8(np.clip(corrected * scale[..., None], 0, 1))
100
+
101
+ # ==============================================================================
102
+ # --- CORE API & PROCESSOR ---
103
+ # ==============================================================================
104
 
105
  @dataclass
106
  class ProcessResult:
 
119
  def __init__(self, model_path: str):
120
  self.model = YOLO(model_path)
121
 
122
+ # Load Golden Reference Patches
123
  self.ref24 = None
124
  if os.path.exists("reference.png"):
125
  try:
126
  ref_img = cv2.imread("reference.png")
127
+ ref_corners = detect_checker_corners(ref_img)
128
+ self.ref24 = sample_24_patches(warp_checker(ref_img, ref_corners))
129
+ print("Reference ColorChecker patches loaded.")
 
130
  except Exception as e:
131
+ print(f"Reference extraction failed: {e}")
 
 
132
 
133
  @staticmethod
134
  def watermelon_model(theta, Rx, Ry, c_a, d_top, w_top, d_bot, w_bot, phi, c_skew, c_bend):
 
143
  def get_stable_perimeter_data(rind_mask, flesh_combined):
144
  cnts, _ = cv2.findContours(rind_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
145
  if not cnts: return None
146
+ best_cnt, max_overlap = None, -1
 
 
 
147
  for cnt in cnts:
148
+ temp = np.zeros_like(rind_mask)
149
+ cv2.drawContours(temp, [cnt], -1, 255, -1)
150
+ overlap = cv2.countNonZero(cv2.bitwise_and(temp, flesh_combined))
151
+ if overlap > max_overlap:
152
+ max_overlap, best_cnt = overlap, cnt
 
153
 
154
  if best_cnt is None: best_cnt = max(cnts, key=cv2.contourArea)
155
  M = cv2.moments(best_cnt)
156
  if M["m00"] == 0: return None
157
 
158
+ cx, cy = M["m10"]/M["m00"], M["m01"]/M["m00"]
159
  pts = best_cnt.reshape(-1, 2)
160
  dx, dy = pts[:, 0] - cx, cy - pts[:, 1]
161
  r_vals, t_vals = np.sqrt(dx**2 + dy**2), np.arctan2(dy, dx)
162
+
163
  num_bins = 360
164
  bins = np.linspace(-np.pi, np.pi, num_bins + 1)
165
  raw_r = np.full(num_bins, np.nan)
 
170
  valid_idx = np.where(~np.isnan(raw_r))[0]
171
  if len(valid_idx) == 0: return None
172
  raw_r[np.isnan(raw_r)] = np.interp(np.where(np.isnan(raw_r))[0], valid_idx, raw_r[valid_idx], period=360)
173
+ return (bins[:-1] + bins[1:])/2.0, median_filter(raw_r, size=7, mode="wrap"), (cx, cy), best_cnt
 
 
174
 
175
  @staticmethod
176
+ def get_dual_mask_midline(f_left, f_right, rind_cnt, pred_cnt, cx, cy):
177
  h, w = f_left.shape
178
+ _, (ma, Ma), angle = cv2.fitEllipse(rind_cnt) if len(rind_cnt) > 5 else (None, (0,0), 0)
179
+ rot_angle = angle if ma < Ma else angle + 90
 
 
180
 
181
  m_rot = cv2.getRotationMatrix2D((cx, cy), rot_angle, 1.0)
182
  m_inv = cv2.getRotationMatrix2D((cx, cy), -rot_angle, 1.0)
183
+ l_rot, r_rot = cv2.warpAffine(f_left, m_rot, (w, h)), cv2.warpAffine(f_right, m_rot, (w, h))
 
 
 
 
 
 
 
184
 
185
  gap_points =[]
186
  y_l, y_r = np.where(l_rot > 0)[0], np.where(r_rot > 0)[0]
 
194
  if len(gap_points) > 10:
195
  y_min, y_max = np.min(gap_points[:, 0]), np.max(gap_points[:, 0])
196
  y_span, y_mean = max(y_max - y_min, 1), (y_max + y_min) / 2.0
197
+ def parabola(y_n, a, b, c): return a*(y_n**2) + b*y_n + c
198
+ try:
199
+ 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]))
 
 
200
  except: popt_mid = [0.0, 0.0, cx]
201
+ ys_ex = np.linspace(0, h, 500)
202
+ pts_rot = np.vstack([parabola((ys_ex - y_mean)/y_span, *popt_mid), ys_extrap, np.ones_like(ys_ex)])
 
 
203
  else:
204
+ ys_ex = np.linspace(0, h, 500)
205
+ pts_rot = np.vstack([np.full_like(ys_ex, cx), ys_ex, np.ones_like(ys_ex)])
206
 
207
  pts_orig = (m_inv @ pts_rot).T
208
+ pred_cnt_cv = pred_cnt.reshape(-1, 1, 2).astype(np.int32)
209
  return np.array([pt for pt in pts_orig if cv2.pointPolygonTest(pred_cnt_cv, (float(pt[0]), float(pt[1])), False) >= 0])
210
 
211
  def process_image(self, image: np.ndarray, source_name: str, scale_ratio: float) -> ProcessResult:
 
216
  dE_initial, dE_final, cm_per_px, checker_corners = None, None, None, None
217
 
218
  try:
219
+ checker_corners = detect_checker_corners(image)
220
+ # Physical width logic
221
  top_width = np.linalg.norm(checker_corners[1] - checker_corners[2])
222
  bot_width = np.linalg.norm(checker_corners[0] - checker_corners[3])
223
+ cm_per_px = CHECKER_WIDTH_CM / ((top_width + bot_width) / 2.0)
 
224
 
225
  if self.ref24 is not None:
226
+ tgt24 = sample_24_patches(warp_checker(image, checker_corners))
227
+ dE_initial = float(np.mean(compute_deltaE_00(tgt24, self.ref24)))
 
 
228
 
229
+ # Apply pipeline to full image BEFORE YOLO inference
230
+ image = apply_color_pipeline(image, self.ref24, tgt24)
231
 
232
+ # Re-check the fully corrected image
233
+ tgt24_corr = sample_24_patches(warp_checker(image, checker_corners))
234
+ dE_final = float(np.mean(compute_deltaE_00(tgt24_corr, self.ref24)))
 
235
  except Exception as e:
236
  print(f"Calibration skipped for {source_name}: {e}")
237
 
238
+ # --- 2. YOLO INFERENCE (3 CLASSES) ---
239
  results = self.model(image, conf=0.25, retina_masks=True, verbose=False)
240
+ 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)
241
+
242
+ if results[0].masks is None:
243
+ return ProcessResult(success=False, message="No masks detected.")
244
+
245
+ for mask_data, cls in zip(results[0].masks.xy, results[0].boxes.cls):
246
+ contour = np.array(mask_data, dtype=np.int32)
247
+ c_id = int(cls)
248
+ if c_id == 0: cv2.drawContours(rind_mask, [contour], -1, 255, -1)
249
+ elif c_id == 1: cv2.drawContours(flesh_l, [contour], -1, 255, -1)
250
+ elif c_id == 2: cv2.drawContours(flesh_r, [contour], -1, 255, -1)
251
+
252
+ flesh_combined = cv2.bitwise_or(flesh_l, flesh_r)
 
 
 
 
 
 
 
 
 
 
253
  perimeter_data = self.get_stable_perimeter_data(rind_mask, flesh_combined)
254
  if perimeter_data is None: return ProcessResult(success=False, message="No stable perimeter.")
255
 
 
257
  scale = np.mean(r_raw)
258
 
259
  try:
260
+ popt, _ = curve_fit(self.watermelon_model, t_data, r_raw / scale,
 
261
  p0=[1.0, 1.1, 0.0, 0.05, 3.0, 0.05, 3.0, 0.0, 0.0, 0.0],
262
+ bounds=([0.5, 0.5, -0.4, 0.0, 0.1, 0.0, 0.1, -1.5, -0.2, -0.2],[2.0, 2.0, 0.4, 0.5, 50.0, 0.5, 50.0, 1.5, 0.2, 0.2]))
 
263
  except Exception as exc: return ProcessResult(success=False, message=f"Fit failed: {exc}")
264
 
265
  r2 = 1 - (np.sum((r_raw / scale - self.watermelon_model(t_data, *popt)) ** 2) / np.sum((r_raw / scale - 1) ** 2))
 
267
  r_fit = self.watermelon_model(t_fit, *popt) * scale
268
  fit_pts = np.array([[r * np.cos(t) + cx, cy - r * np.sin(t)] for t, r in zip(t_fit, r_fit)])
269
 
270
+ # --- 3. DIMENSIONAL MATH (IN CM) ---
271
  orig_scale = 1.0 / scale_ratio
272
+ if cm_per_px is None: cm_per_px = 1.0
273
 
274
+ width_val = float(np.max(fit_pts[:, 0]) - np.min(fit_pts[:, 0])) * cm_per_px * orig_scale
275
+ height_val = float(np.max(fit_pts[:, 1]) - np.min(fit_pts[:, 1])) * cm_per_px * orig_scale
276
+ perimeter_val = float(np.sum(np.linalg.norm(np.diff(fit_pts, axis=0), axis=1)) + np.linalg.norm(fit_pts[-1] - fit_pts[0])) * cm_per_px * orig_scale
 
 
 
 
277
 
278
  # --- 4. DRAWING ---
279
+ midline = self.get_dual_mask_midline(flesh_l, flesh_r, rind_cnt, fit_pts, cx, cy)
280
  output = blend_mask_overlays(image, rind_mask, flesh_combined)
281
 
 
282
  if checker_corners is not None:
283
  cv2.polylines(output, [np.int32(checker_corners)], True, (0, 165, 255), 4)
284
 
 
288
  stem = stem_tip_tangent_deg(rind_cnt, (cx, cy))
289
  if stem is not None:
290
  tx, ty, tdeg = stem
291
+ rad = np.deg2rad(tdeg)
292
  p1 = (int(round(tx)), int(round(ty)))
293
+ p2 = (int(round(tx + min(w, h)*0.08 * np.cos(rad))), int(round(ty + min(w, h)*0.08 * np.sin(rad))))
294
  cv2.circle(output, p1, 6, (255, 0, 255), -1)
295
  cv2.line(output, p1, p2, (255, 0, 255), 2)
296
 
297
+ _, buffer = cv2.imencode('.jpg', output,[cv2.IMWRITE_JPEG_QUALITY, 85])
 
298
 
299
  return ProcessResult(
300
  success=True, message="Success", r2_score=float(r2),
301
  width_val=width_val, height_val=height_val, perimeter_val=perimeter_val,
302
  delta_e_initial=dE_initial, delta_e_final=dE_final,
303
+ image_base64=base64.b64encode(buffer).decode('utf-8'), filename=source_name
304
  )
305
 
306
 
 
318
  @app.post("/process_single")
319
  async def process_single(file: UploadFile = File(...)):
320
  contents = await file.read()
321
+ img = cv2.imdecode(np.frombuffer(contents, np.uint8), cv2.IMREAD_COLOR)
 
322
 
 
323
  scale_ratio = 1.0
324
+ h, w = img.shape[:2]
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, contents
332
  gc.collect()
333
 
334
  return res.__dict__