smiler488 commited on
Commit
d6b3182
·
verified ·
1 Parent(s): 200f213

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -23
app.py CHANGED
@@ -89,6 +89,23 @@ def build_foreground_mask(img_bgr: np.ndarray) -> np.ndarray:
89
  return mask
90
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  def detect_reference(
93
  img_bgr: np.ndarray,
94
  mode: str,
@@ -142,12 +159,8 @@ def detect_reference(
142
  candidates.append((score, i, (x, y, ww, hh), area, (int(cx), int(cy))))
143
 
144
  if not candidates:
145
- # 如果没有找到参考物,使用安全的默认值
146
- px_per_mm = 4.0
147
- center = None
148
- ref_type = None
149
- bbox = None
150
- return px_per_mm, center, ref_type, bbox
151
 
152
  # 选择最左上角的候选物
153
  candidates.sort(key=lambda c: c[0])
@@ -155,12 +168,16 @@ def detect_reference(
155
 
156
  x, y, ww, hh = bbox
157
 
158
- # 计算像素/毫米比例
159
  ref_size = ref_size_mm if ref_size_mm and ref_size_mm > 0 else 25.0
160
- ref_bbox_size_px = max(ww, hh)
161
- px_per_mm = ref_bbox_size_px / ref_size
 
 
 
 
162
 
163
- return px_per_mm, center, "square", (x, y, ww, hh)
164
 
165
 
166
  # -----------------------------
@@ -383,17 +400,19 @@ def compute_metrics(
383
  """Compute all morphological + color metrics for each component."""
384
  rows: List[Dict[str, Any]] = []
385
 
 
386
  for i, comp in enumerate(components, start=1):
387
- # 使用新的length_px和width_px字段
388
- length_mm = comp["length_px"] / px_per_mm
389
- width_mm = comp["width_px"] / px_per_mm
390
- area_mm2 = comp["area_px"] / (px_per_mm * px_per_mm)
391
- perimeter_mm = comp["peri_px"] / px_per_mm
 
392
 
393
- aspect_ratio = length_mm / (width_mm + 1e-6)
394
-
395
- # 计算圆形度 (4π*面积/周长²)
396
- circularity = (4.0 * np.pi * area_mm2) / (perimeter_mm * perimeter_mm + 1e-6)
397
 
398
  # 计算颜色指标
399
  mask_single = np.zeros(img_bgr.shape[:2], dtype=np.uint8)
@@ -405,6 +424,9 @@ def compute_metrics(
405
  "label": f"s{i}",
406
  "centerX_px": int(comp["center"][0]),
407
  "centerY_px": int(comp["center"][1]),
 
 
 
408
  "length_mm": round(length_mm, 2),
409
  "width_mm": round(width_mm, 2),
410
  "area_mm2": round(area_mm2, 2),
@@ -574,6 +596,11 @@ def analyze(
574
 
575
  # 检测参考物(左上角第一个物体)
576
  px_per_mm, ref_center, ref_type, ref_bbox = detect_reference(img_bgr, ref_mode, ref_size_mm)
 
 
 
 
 
577
 
578
  # 分割所有样品
579
  comps = segment(
@@ -681,7 +708,7 @@ def apply_corrections(
681
  if nearest_idx < 0:
682
  return state_dict, None, pd.DataFrame(), None, []
683
 
684
- px_per_mm = state_dict.get("px_per_mm", 4.0)
685
  ref_center = state_dict.get("ref_center")
686
  ref_type = state_dict.get("ref_type", "square")
687
  ref_bbox = state_dict.get("ref_bbox")
@@ -701,10 +728,9 @@ def apply_corrections(
701
  ref_bbox = (x0, y0, w0, h0)
702
  ref_center = (int(comp["center"][0]), int(comp["center"][1]))
703
 
704
- # Update px_per_mm using the largest side as diameter/side length
705
- side_px = float(max(w0, h0))
706
  px_per_mm = max(side_px / (ref_size_mm if ref_size_mm > 0 else 20.0), 1e-6)
707
- ref_type = "square"
708
 
709
  # Remove this component from active samples (reference is not a sample)
710
  new_components = []
 
89
  return mask
90
 
91
 
92
+ def reference_size_px(contour: np.ndarray) -> Tuple[float, str]:
93
+ """Size of a reference object in pixels, independent of its rotation.
94
+
95
+ A round object (circularity > 0.85) is a coin: its size is the diameter
96
+ of the circle with the same area. Otherwise it is a square: its size is
97
+ the mean side of the minimum-area rotated rectangle. The axis-aligned
98
+ bounding box would overestimate a rotated square by up to 41% (45°).
99
+ """
100
+ area = float(cv2.contourArea(contour))
101
+ peri = float(cv2.arcLength(contour, True))
102
+ circularity = 4.0 * np.pi * area / (peri * peri + 1e-9)
103
+ if circularity > 0.85:
104
+ return float(np.sqrt(4.0 * area / np.pi)), "coin"
105
+ (_, _), (w, h), _ = cv2.minAreaRect(contour)
106
+ return float((w + h) / 2.0), "square"
107
+
108
+
109
  def detect_reference(
110
  img_bgr: np.ndarray,
111
  mode: str,
 
159
  candidates.append((score, i, (x, y, ww, hh), area, (int(cx), int(cy))))
160
 
161
  if not candidates:
162
+ # No reference: report pixels only instead of inventing a scale.
163
+ return None, None, None, None
 
 
 
 
164
 
165
  # 选择最左上角的候选物
166
  candidates.sort(key=lambda c: c[0])
 
168
 
169
  x, y, ww, hh = bbox
170
 
171
+ # 计算像素/毫米比例(与参考物旋转无关)
172
  ref_size = ref_size_mm if ref_size_mm and ref_size_mm > 0 else 25.0
173
+ ref_mask = np.uint8(labels == label_idx) * 255
174
+ contours, _ = cv2.findContours(ref_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
175
+ size_px, kind = reference_size_px(max(contours, key=cv2.contourArea))
176
+ if mode in ("coin", "square"):
177
+ kind = mode
178
+ px_per_mm = size_px / ref_size
179
 
180
+ return px_per_mm, center, kind, (x, y, ww, hh)
181
 
182
 
183
  # -----------------------------
 
400
  """Compute all morphological + color metrics for each component."""
401
  rows: List[Dict[str, Any]] = []
402
 
403
+ scaled = px_per_mm is not None and px_per_mm > 0
404
  for i, comp in enumerate(components, start=1):
405
+ # Millimetre values only when a reference set the scale; pixel values
406
+ # are always reported.
407
+ length_mm = comp["length_px"] / px_per_mm if scaled else float("nan")
408
+ width_mm = comp["width_px"] / px_per_mm if scaled else float("nan")
409
+ area_mm2 = comp["area_px"] / (px_per_mm * px_per_mm) if scaled else float("nan")
410
+ perimeter_mm = comp["peri_px"] / px_per_mm if scaled else float("nan")
411
 
412
+ aspect_ratio = comp["length_px"] / (comp["width_px"] + 1e-6)
413
+
414
+ # 圆形度 (4π*面积/周长²),与尺度无关
415
+ circularity = (4.0 * np.pi * comp["area_px"]) / (comp["peri_px"] ** 2 + 1e-6)
416
 
417
  # 计算颜色指标
418
  mask_single = np.zeros(img_bgr.shape[:2], dtype=np.uint8)
 
424
  "label": f"s{i}",
425
  "centerX_px": int(comp["center"][0]),
426
  "centerY_px": int(comp["center"][1]),
427
+ "length_px": round(float(comp["length_px"]), 1),
428
+ "width_px": round(float(comp["width_px"]), 1),
429
+ "area_px": int(comp["area_px"]),
430
  "length_mm": round(length_mm, 2),
431
  "width_mm": round(width_mm, 2),
432
  "area_mm2": round(area_mm2, 2),
 
596
 
597
  # 检测参考物(左上角第一个物体)
598
  px_per_mm, ref_center, ref_type, ref_bbox = detect_reference(img_bgr, ref_mode, ref_size_mm)
599
+ if px_per_mm is None:
600
+ gr.Warning(
601
+ "No reference object found in the top-left of the image: sizes are reported in pixels only. "
602
+ "Place the reference there, or click an object in 'set-ref' mode."
603
+ )
604
 
605
  # 分割所有样品
606
  comps = segment(
 
708
  if nearest_idx < 0:
709
  return state_dict, None, pd.DataFrame(), None, []
710
 
711
+ px_per_mm = state_dict.get("px_per_mm")
712
  ref_center = state_dict.get("ref_center")
713
  ref_type = state_dict.get("ref_type", "square")
714
  ref_bbox = state_dict.get("ref_bbox")
 
728
  ref_bbox = (x0, y0, w0, h0)
729
  ref_center = (int(comp["center"][0]), int(comp["center"][1]))
730
 
731
+ # Update px_per_mm from the object's rotation-independent size
732
+ side_px, ref_type = reference_size_px(comp["contour"])
733
  px_per_mm = max(side_px / (ref_size_mm if ref_size_mm > 0 else 20.0), 1e-6)
 
734
 
735
  # Remove this component from active samples (reference is not a sample)
736
  new_components = []