Spaces:
Sleeping
Sleeping
Upload app.py
Browse files88 unmodified lines89909192939447 unmodified lines1421431441451461471481491501511521531 unmodified line155156157158159160161162163164165166216 unmodified lines3833843853863873883893903913923933943953963973983995 unmodified lines405406407408409410163 unmodified lines574575576577578579101 unmodified lines68168268368468568668713 unmodified lines70170270370470570670770870971088 unmodified linesreturn maskdef detect_reference(img_bgr: np.ndarray,mode: str,47 unmodified linescandidates.append((score, i, (x, y, ww, hh), area, (int(cx), int(cy))))if not candidates:# 如果没有找到参考物,使用安全的默认值px_per_mm = 4.0center = Noneref_type = Nonebbox = Nonereturn px_per_mm, center, ref_type, bbox# 选择最左上角的候选物candidates.sort(key=lambda c: c[0])1 unmodified linex, y, ww, hh = bbox# 计算像素/毫米比例ref_size = ref_size_mm if ref_size_mm and ref_size_mm > 0 else 25.0ref_bbox_size_px = max(ww, hh)px_per_mm = ref_bbox_size_px / ref_sizereturn px_per_mm, center, "square", (x, y, ww, hh)# -----------------------------216 unmodified lines"""Compute all morphological + color metrics for each component."""rows: List[Dict[str, Any]] = []for i, comp in enumerate(components, start=1):# 使用新的length_px和width_px字段length_mm = comp["length_px"] / px_per_mmwidth_mm = comp["width_px"] / px_per_mmarea_mm2 = comp["area_px"] / (px_per_mm * px_per_mm)perimeter_mm = comp["peri_px"] / px_per_mmaspect_ratio = length_mm / (width_mm + 1e-6)# 计算圆形度 (4π*面积/周长²)circularity = (4.0 * np.pi * area_mm2) / (perimeter_mm * perimeter_mm + 1e-6)# 计算颜色指标mask_single = np.zeros(img_bgr.shape[:2], dtype=np.uint8)5 unmodified lines"label": f"s{i}","centerX_px": int(comp["center"][0]),"centerY_px": int(comp["center"][1]),"length_mm": round(length_mm, 2),"width_mm": round(width_mm, 2),"area_mm2": round(area_mm2, 2),163 unmodified lines# 检测参考物(左上角第一个物体)px_per_mm, ref_center, ref_type, ref_bbox = detect_reference(img_bgr, ref_mode, ref_size_mm)# 分割所有样品comps = segment(101 unmodified linesif nearest_idx < 0:return state_dict, None, pd.DataFrame(), None, []px_per_mm = state_dict.get("px_per_mm", 4.0)ref_center = state_dict.get("ref_center")ref_type = state_dict.get("ref_type", "square")ref_bbox = state_dict.get("ref_bbox")13 unmodified linesref_bbox = (x0, y0, w0, h0)ref_center = (int(comp["center"][0]), int(comp["center"][1]))# Update px_per_mm using the largest side as diameter/side lengthside_px = float(max(w0, h0))px_per_mm = max(side_px / (ref_size_mm if ref_size_mm > 0 else 20.0), 1e-6)ref_type = "square"# Remove this component from active samples (reference is not a sample)new_components = []88 unmodified lines899091929394959697989910010110210310410510610710810911011147 unmodified lines1591601611621631641651661 unmodified line168169170171172173174175176177178179180181182183216 unmodified lines4004014024034044054064074084094104114124134144154164174185 unmodified lines424425426427428429430431432163 unmodified lines596597598599600601602603604605606101 unmodified lines70870971071171271371413 unmodified lines72872973073173273373473573688 unmodified linesreturn maskdef reference_size_px(contour: np.ndarray) -> Tuple[float, str]:"""Size of a reference object in pixels, independent of its rotation.A round object (circularity > 0.85) is a coin: its size is the diameterof the circle with the same area. Otherwise it is a square: its size isthe mean side of the minimum-area rotated rectangle. The axis-alignedbounding box would overestimate a rotated square by up to 41% (45°)."""area = float(cv2.contourArea(contour))peri = float(cv2.arcLength(contour, True))circularity = 4.0 * np.pi * area / (peri * peri + 1e-9)if circularity > 0.85:return float(np.sqrt(4.0 * area / np.pi)), "coin"(_, _), (w, h), _ = cv2.minAreaRect(contour)return float((w + h) / 2.0), "square"def detect_reference(img_bgr: np.ndarray,mode: str,47 unmodified linescandidates.append((score, i, (x, y, ww, hh), area, (int(cx), int(cy))))if not candidates:# No reference: report pixels only instead of inventing a scale.return None, None, None, None# 选择最左上角的候选物candidates.sort(key=lambda c: c[0])1 unmodified linex, y, ww, hh = bbox# 计算像素/毫米比例(与参考物旋转无关)ref_size = ref_size_mm if ref_size_mm and ref_size_mm > 0 else 25.0ref_mask = np.uint8(labels == label_idx) * 255contours, _ = cv2.findContours(ref_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)size_px, kind = reference_size_px(max(contours, key=cv2.contourArea))if mode in ("coin", "square"):kind = modepx_per_mm = size_px / ref_sizereturn px_per_mm, center, kind, (x, y, ww, hh)# -----------------------------216 unmodified lines"""Compute all morphological + color metrics for each component."""rows: List[Dict[str, Any]] = []scaled = px_per_mm is not None and px_per_mm > 0for i, comp in enumerate(components, start=1):# Millimetre values only when a reference set the scale; pixel values# are always reported.length_mm = comp["length_px"] / px_per_mm if scaled else float("nan")width_mm = comp["width_px"] / px_per_mm if scaled else float("nan")area_mm2 = comp["area_px"] / (px_per_mm * px_per_mm) if scaled else float("nan")perimeter_mm = comp["peri_px"] / px_per_mm if scaled else float("nan")aspect_ratio = comp["length_px"] / (comp["width_px"] + 1e-6)# 圆形度 (4π*面积/周长²),与尺度无关circularity = (4.0 * np.pi * comp["area_px"]) / (comp["peri_px"] ** 2 + 1e-6)# 计算颜色指标mask_single = np.zeros(img_bgr.shape[:2], dtype=np.uint8)5 unmodified lines"label": f"s{i}","centerX_px": int(comp["center"][0]),"centerY_px": int(comp["center"][1]),"length_px": round(float(comp["length_px"]), 1),"width_px": round(float(comp["width_px"]), 1),"area_px": int(comp["area_px"]),"length_mm": round(length_mm, 2),"width_mm": round(width_mm, 2),"area_mm2": round(area_mm2, 2),163 unmodified lines# 检测参考物(左上角第一个物体)px_per_mm, ref_center, ref_type, ref_bbox = detect_reference(img_bgr, ref_mode, ref_size_mm)if px_per_mm is None:gr.Warning("No reference object found in the top-left of the image: sizes are reported in pixels only. ""Place the reference there, or click an object in 'set-ref' mode.")# 分割所有样品comps = segment(101 unmodified linesif nearest_idx < 0:return state_dict, None, pd.DataFrame(), None, []px_per_mm = state_dict.get("px_per_mm")ref_center = state_dict.get("ref_center")ref_type = state_dict.get("ref_type", "square")ref_bbox = state_dict.get("ref_bbox")13 unmodified linesref_bbox = (x0, y0, w0, h0)ref_center = (int(comp["center"][0]), int(comp["center"][1]))# Update px_per_mm from the object's rotation-independent sizeside_px, ref_type = reference_size_px(comp["contour"])px_per_mm = max(side_px / (ref_size_mm if ref_size_mm > 0 else 20.0), 1e-6)# Remove this component from active samples (reference is not a sample)new_components = []
app.py+49-23