Spaces:
Running
Running
Update src/ai_processor.py
Browse files- src/ai_processor.py +156 -104
src/ai_processor.py
CHANGED
|
@@ -285,7 +285,6 @@ def estimate_px_per_cm_from_exif(pil_img: Image.Image, default_px_per_cm: float
|
|
| 285 |
|
| 286 |
# ---------- Segmentation helpers ----------
|
| 287 |
def _imagenet_norm(arr: np.ndarray) -> np.ndarray:
|
| 288 |
-
# expects RGB 0..255 -> float
|
| 289 |
mean = np.array([123.675, 116.28, 103.53], dtype=np.float32)
|
| 290 |
std = np.array([58.395, 57.12, 57.375], dtype=np.float32)
|
| 291 |
return (arr.astype(np.float32) - mean) / std
|
|
@@ -309,112 +308,166 @@ def _to_prob(pred: np.ndarray) -> np.ndarray:
|
|
| 309 |
p = 1.0 / (1.0 + np.exp(-p))
|
| 310 |
return p.astype(np.float32)
|
| 311 |
|
| 312 |
-
# ----
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
def _fill_holes(mask01: np.ndarray) -> np.ndarray:
|
| 314 |
-
# Flood-fill from border, then invert
|
| 315 |
h, w = mask01.shape[:2]
|
| 316 |
ff = np.zeros((h + 2, w + 2), np.uint8)
|
| 317 |
m = (mask01 * 255).astype(np.uint8).copy()
|
| 318 |
cv2.floodFill(m, ff, (0, 0), 255)
|
| 319 |
m_inv = cv2.bitwise_not(m)
|
| 320 |
-
# Combine original with filled holes
|
| 321 |
out = ((mask01 * 255) | m_inv) // 255
|
| 322 |
return out.astype(np.uint8)
|
| 323 |
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
_last_seg_debug: Dict[str, object] = {}
|
| 326 |
|
| 327 |
def segment_wound(image_bgr: np.ndarray, ts: str, out_dir: str) -> Tuple[np.ndarray, Dict[str, object]]:
|
| 328 |
"""
|
| 329 |
-
|
|
|
|
| 330 |
Returns (mask_uint8_0_255, debug_dict)
|
| 331 |
"""
|
| 332 |
-
|
| 333 |
-
|
| 334 |
|
| 335 |
seg_model = models_cache.get("seg", None)
|
| 336 |
-
used = "fallback_kmeans"
|
| 337 |
-
reason = "no_model"
|
| 338 |
-
heatmap_path = None
|
| 339 |
-
saw_roi_path = None
|
| 340 |
|
|
|
|
| 341 |
if seg_model is not None:
|
| 342 |
try:
|
| 343 |
ishape = getattr(seg_model, "input_shape", None)
|
| 344 |
if not ishape or len(ishape) < 4:
|
| 345 |
raise ValueError(f"Bad seg input_shape: {ishape}")
|
| 346 |
th, tw = int(ishape[1]), int(ishape[2])
|
|
|
|
| 347 |
x = _preprocess_for_seg(image_bgr, (th, tw))
|
| 348 |
-
|
| 349 |
if SMARTHEAL_DEBUG:
|
| 350 |
-
|
| 351 |
-
cv2.imwrite(
|
| 352 |
|
| 353 |
-
# Inference
|
| 354 |
pred = seg_model.predict(x, verbose=0)
|
| 355 |
-
if isinstance(pred, (list, tuple)):
|
| 356 |
-
|
| 357 |
-
p =
|
| 358 |
-
p = cv2.resize(p, (image_bgr.shape[1], image_bgr.shape[0])) # back to ROI size
|
| 359 |
-
|
| 360 |
-
# Debug stats
|
| 361 |
-
pmin, pmax, pmean = float(p.min()), float(p.max()), float(p.mean())
|
| 362 |
-
_log_kv("SEG_PROB_STATS", {"min": pmin, "max": pmax, "mean": pmean})
|
| 363 |
|
|
|
|
| 364 |
if SMARTHEAL_DEBUG:
|
| 365 |
hm = (np.clip(p, 0, 1) * 255).astype(np.uint8)
|
| 366 |
heat = cv2.applyColorMap(hm, cv2.COLORMAP_JET)
|
| 367 |
heatmap_path = os.path.join(out_dir, f"seg_pred_heatmap_{ts}.png")
|
| 368 |
cv2.imwrite(heatmap_path, heat)
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
"heatmap_path": heatmap_path,
|
| 388 |
-
"roi_seen_by_model":
|
| 389 |
-
}
|
| 390 |
-
return (
|
| 391 |
|
| 392 |
except Exception as e:
|
| 393 |
-
|
| 394 |
-
|
| 395 |
|
| 396 |
-
# --- Fallback: KMeans
|
| 397 |
Z = image_bgr.reshape((-1, 3)).astype(np.float32)
|
| 398 |
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
|
| 399 |
_, labels, centers = cv2.kmeans(Z, 2, None, criteria, 5, cv2.KMEANS_PP_CENTERS)
|
| 400 |
centers_u8 = centers.astype(np.uint8).reshape(1, 2, 3)
|
| 401 |
centers_lab = cv2.cvtColor(centers_u8, cv2.COLOR_BGR2LAB)[0]
|
| 402 |
-
wound_idx = int(np.argmax(centers_lab[:, 1])) # maximize a* (
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
"
|
| 411 |
-
"
|
| 412 |
-
"
|
| 413 |
-
"
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
}
|
| 417 |
-
return (mask * 255).astype(np.uint8), _last_seg_debug
|
| 418 |
|
| 419 |
# ---------- Measurement + overlay helpers ----------
|
| 420 |
def largest_component_mask(binary01: np.ndarray, min_area_px: int = 50) -> np.ndarray:
|
|
@@ -427,17 +480,6 @@ def largest_component_mask(binary01: np.ndarray, min_area_px: int = 50) -> np.nd
|
|
| 427 |
largest_idx = 1 + int(np.argmax(areas))
|
| 428 |
return (labels == largest_idx).astype(np.uint8)
|
| 429 |
|
| 430 |
-
def _clean_mask(mask01: np.ndarray) -> np.ndarray:
|
| 431 |
-
"""Open→Close→Fill holes→Largest component."""
|
| 432 |
-
if mask01.dtype != np.uint8:
|
| 433 |
-
mask01 = mask01.astype(np.uint8)
|
| 434 |
-
k = np.ones((3, 3), np.uint8)
|
| 435 |
-
mask01 = cv2.morphologyEx(mask01, cv2.MORPH_OPEN, k, iterations=1)
|
| 436 |
-
mask01 = cv2.morphologyEx(mask01, cv2.MORPH_CLOSE, k, iterations=2)
|
| 437 |
-
mask01 = _fill_holes(mask01)
|
| 438 |
-
mask01 = largest_component_mask(mask01, min_area_px=30)
|
| 439 |
-
return (mask01 > 0).astype(np.uint8)
|
| 440 |
-
|
| 441 |
def measure_min_area_rect(mask01: np.ndarray, px_per_cm: float) -> Tuple[float, float, Tuple]:
|
| 442 |
contours, _ = cv2.findContours(mask01.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 443 |
if not contours:
|
|
@@ -451,9 +493,23 @@ def measure_min_area_rect(mask01: np.ndarray, px_per_cm: float) -> Tuple[float,
|
|
| 451 |
box = cv2.boxPoints(rect).astype(int)
|
| 452 |
return length_cm, breadth_cm, (box, rect[0])
|
| 453 |
|
| 454 |
-
def
|
| 455 |
-
|
| 456 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
|
| 458 |
def draw_measurement_overlay(
|
| 459 |
base_bgr: np.ndarray,
|
|
@@ -464,16 +520,13 @@ def draw_measurement_overlay(
|
|
| 464 |
thickness: int = 2
|
| 465 |
) -> np.ndarray:
|
| 466 |
"""
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
3) Two double-headed arrows:
|
| 471 |
-
- 'Length' along the longer side.
|
| 472 |
-
- 'Width' along the shorter side.
|
| 473 |
"""
|
| 474 |
overlay = base_bgr.copy()
|
| 475 |
|
| 476 |
-
#
|
| 477 |
mask255 = (mask01 * 255).astype(np.uint8)
|
| 478 |
mask3 = cv2.merge([mask255, mask255, mask255])
|
| 479 |
red = np.zeros_like(overlay); red[:] = (0, 0, 255)
|
|
@@ -481,7 +534,7 @@ def draw_measurement_overlay(
|
|
| 481 |
tinted = cv2.addWeighted(overlay, 1 - alpha, red, alpha, 0)
|
| 482 |
overlay = np.where(mask3 > 0, tinted, overlay)
|
| 483 |
|
| 484 |
-
#
|
| 485 |
cnts, _ = cv2.findContours(mask255, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 486 |
if cnts:
|
| 487 |
cv2.drawContours(overlay, cnts, -1, (255, 255, 255), 2)
|
|
@@ -490,19 +543,11 @@ def draw_measurement_overlay(
|
|
| 490 |
cv2.polylines(overlay, [rect_box], True, (255, 255, 255), thickness)
|
| 491 |
pts = rect_box.reshape(-1, 2)
|
| 492 |
|
| 493 |
-
def midpoint(a, b):
|
| 494 |
-
return (int((a[0] + b[0]) / 2), int((a[1] + b[1]) / 2))
|
| 495 |
-
|
| 496 |
-
# Edge lengths
|
| 497 |
e = [np.linalg.norm(pts[i] - pts[(i + 1) % 4]) for i in range(4)]
|
| 498 |
long_edge_idx = int(np.argmax(e))
|
| 499 |
-
short_edge_idx = (long_edge_idx + 1) % 2 # 0/1 map for pairs below
|
| 500 |
-
|
| 501 |
-
# Midpoints of opposite edges for arrows
|
| 502 |
mids = [midpoint(pts[i], pts[(i + 1) % 4]) for i in range(4)]
|
| 503 |
-
# Long side uses edges long_edge_idx and the opposite edge (i+2)
|
| 504 |
long_pair = (long_edge_idx, (long_edge_idx + 2) % 4)
|
| 505 |
-
# Short side uses the other pair
|
| 506 |
short_pair = ((long_edge_idx + 1) % 4, (long_edge_idx + 3) % 4)
|
| 507 |
|
| 508 |
def draw_double_arrow(img, p1, p2):
|
|
@@ -516,7 +561,6 @@ def draw_measurement_overlay(
|
|
| 516 |
cv2.putText(overlay, text, org, cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 4, cv2.LINE_AA)
|
| 517 |
cv2.putText(overlay, text, org, cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, cv2.LINE_AA)
|
| 518 |
|
| 519 |
-
# Draw arrows and labels
|
| 520 |
draw_double_arrow(overlay, mids[long_pair[0]], mids[long_pair[1]])
|
| 521 |
draw_double_arrow(overlay, mids[short_pair[0]], mids[short_pair[1]])
|
| 522 |
put_label(f"Length: {length_cm:.2f} cm", mids[long_pair[0]])
|
|
@@ -545,6 +589,11 @@ class AIProcessor:
|
|
| 545 |
"""
|
| 546 |
try:
|
| 547 |
px_per_cm, exif_meta = estimate_px_per_cm_from_exif(image_pil, DEFAULT_PX_PER_CM)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
image_cv = cv2.cvtColor(np.array(image_pil.convert("RGB")), cv2.COLOR_RGB2BGR)
|
| 549 |
|
| 550 |
# --- Detection ---
|
|
@@ -578,20 +627,23 @@ class AIProcessor:
|
|
| 578 |
mask_u8_255, seg_debug = segment_wound(roi, ts, out_dir)
|
| 579 |
mask01 = (mask_u8_255 > 127).astype(np.uint8)
|
| 580 |
|
| 581 |
-
# Robust post-processing to ensure "proper" masking
|
| 582 |
if mask01.any():
|
| 583 |
mask01 = _clean_mask(mask01)
|
| 584 |
logging.debug(f"Mask postproc: px_after={int(mask01.sum())}")
|
| 585 |
|
| 586 |
-
# --- Measurement ---
|
| 587 |
if mask01.any():
|
| 588 |
length_cm, breadth_cm, (box_pts, _) = measure_min_area_rect(mask01, px_per_cm)
|
| 589 |
-
|
| 590 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
anno_roi = draw_measurement_overlay(roi, mask01, box_pts, length_cm, breadth_cm)
|
| 592 |
segmentation_empty = False
|
| 593 |
else:
|
| 594 |
-
#
|
| 595 |
h_px = max(0, y2 - y1); w_px = max(0, x2 - x1)
|
| 596 |
length_cm = round(max(h_px, w_px) / px_per_cm, 2)
|
| 597 |
breadth_cm = round(min(h_px, w_px) / px_per_cm, 2)
|
|
@@ -615,7 +667,7 @@ class AIProcessor:
|
|
| 615 |
roi_mask_path = os.path.join(out_dir, f"roi_mask_{ts}.png")
|
| 616 |
cv2.imwrite(roi_mask_path, (mask01 * 255).astype(np.uint8))
|
| 617 |
|
| 618 |
-
# ROI overlay (
|
| 619 |
mask255 = (mask01 * 255).astype(np.uint8)
|
| 620 |
mask3 = cv2.merge([mask255, mask255, mask255])
|
| 621 |
red = np.zeros_like(roi); red[:] = (0, 0, 255)
|
|
@@ -658,7 +710,7 @@ class AIProcessor:
|
|
| 658 |
"seg_used": seg_debug.get("used"),
|
| 659 |
"seg_reason": seg_debug.get("reason"),
|
| 660 |
"positive_fraction": round(float(seg_debug.get("positive_fraction", 0.0)), 6),
|
| 661 |
-
"threshold": seg_debug.get("
|
| 662 |
"segmentation_empty": segmentation_empty,
|
| 663 |
"exif_px_per_cm": round(px_per_cm, 3),
|
| 664 |
}
|
|
@@ -674,7 +726,7 @@ class AIProcessor:
|
|
| 674 |
"detection_confidence": float(results[0].boxes.conf[0].cpu().item())
|
| 675 |
if getattr(results[0].boxes, "conf", None) is not None else 0.0,
|
| 676 |
"detection_image_path": detection_path,
|
| 677 |
-
"segmentation_image_path":
|
| 678 |
"segmentation_annotated_path": annotated_seg_path,
|
| 679 |
"segmentation_roi_path": segmentation_roi_path,
|
| 680 |
"roi_mask_path": roi_mask_path,
|
|
@@ -857,4 +909,4 @@ Automated analysis provides quantitative measurements; verify via clinical exami
|
|
| 857 |
"report": f"Analysis initialization failed: {str(e)}",
|
| 858 |
"saved_image_path": None,
|
| 859 |
"guideline_context": "",
|
| 860 |
-
}
|
|
|
|
| 285 |
|
| 286 |
# ---------- Segmentation helpers ----------
|
| 287 |
def _imagenet_norm(arr: np.ndarray) -> np.ndarray:
|
|
|
|
| 288 |
mean = np.array([123.675, 116.28, 103.53], dtype=np.float32)
|
| 289 |
std = np.array([58.395, 57.12, 57.375], dtype=np.float32)
|
| 290 |
return (arr.astype(np.float32) - mean) / std
|
|
|
|
| 308 |
p = 1.0 / (1.0 + np.exp(-p))
|
| 309 |
return p.astype(np.float32)
|
| 310 |
|
| 311 |
+
# ---- Adaptive threshold + GrabCut grow ----
|
| 312 |
+
def _adaptive_prob_threshold(p: np.ndarray) -> float:
|
| 313 |
+
"""
|
| 314 |
+
Choose a threshold that avoids tiny blobs while not swallowing skin.
|
| 315 |
+
Try Otsu and the 90th percentile, clamp to [0.25, 0.65], pick by area heuristic.
|
| 316 |
+
"""
|
| 317 |
+
p01 = np.clip(p.astype(np.float32), 0, 1)
|
| 318 |
+
p255 = (p01 * 255).astype(np.uint8)
|
| 319 |
+
|
| 320 |
+
ret_otsu, _ = cv2.threshold(p255, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 321 |
+
thr_otsu = float(np.clip(ret_otsu / 255.0, 0.25, 0.65))
|
| 322 |
+
thr_pctl = float(np.clip(np.percentile(p01, 90), 0.25, 0.65))
|
| 323 |
+
|
| 324 |
+
def area_frac(thr: float) -> float:
|
| 325 |
+
return float((p01 >= thr).sum()) / float(p01.size)
|
| 326 |
+
|
| 327 |
+
af_otsu = area_frac(thr_otsu)
|
| 328 |
+
af_pctl = area_frac(thr_pctl)
|
| 329 |
+
|
| 330 |
+
def score(af: float) -> float:
|
| 331 |
+
target_low, target_high = 0.03, 0.10
|
| 332 |
+
if af < target_low: return abs(af - target_low) * 3.0
|
| 333 |
+
if af > target_high: return abs(af - target_high) * 1.5
|
| 334 |
+
return 0.0
|
| 335 |
+
|
| 336 |
+
return thr_otsu if score(af_otsu) <= score(af_pctl) else thr_pctl
|
| 337 |
+
|
| 338 |
+
def _grabcut_refine(bgr: np.ndarray, seed01: np.ndarray, iters: int = 3) -> np.ndarray:
|
| 339 |
+
"""Grow from a confident core into low-contrast margins."""
|
| 340 |
+
h, w = bgr.shape[:2]
|
| 341 |
+
gc = np.full((h, w), cv2.GC_PR_BGD, np.uint8)
|
| 342 |
+
k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
| 343 |
+
seed_dil = cv2.dilate(seed01, k, iterations=1)
|
| 344 |
+
gc[seed01.astype(bool)] = cv2.GC_PR_FGD
|
| 345 |
+
gc[seed_dil.astype(bool)] = cv2.GC_FGD
|
| 346 |
+
gc[0, :], gc[-1, :], gc[:, 0], gc[:, -1] = cv2.GC_BGD, cv2.GC_BGD, cv2.GC_BGD, cv2.GC_BGD
|
| 347 |
+
bgdModel = np.zeros((1, 65), np.float64)
|
| 348 |
+
fgdModel = np.zeros((1, 65), np.float64)
|
| 349 |
+
cv2.grabCut(bgr, gc, None, bgdModel, fgdModel, iters, cv2.GC_INIT_WITH_MASK)
|
| 350 |
+
return np.where((gc == cv2.GC_FGD) | (gc == cv2.GC_PR_FGD), 1, 0).astype(np.uint8)
|
| 351 |
+
|
| 352 |
def _fill_holes(mask01: np.ndarray) -> np.ndarray:
|
|
|
|
| 353 |
h, w = mask01.shape[:2]
|
| 354 |
ff = np.zeros((h + 2, w + 2), np.uint8)
|
| 355 |
m = (mask01 * 255).astype(np.uint8).copy()
|
| 356 |
cv2.floodFill(m, ff, (0, 0), 255)
|
| 357 |
m_inv = cv2.bitwise_not(m)
|
|
|
|
| 358 |
out = ((mask01 * 255) | m_inv) // 255
|
| 359 |
return out.astype(np.uint8)
|
| 360 |
|
| 361 |
+
def _clean_mask(mask01: np.ndarray) -> np.ndarray:
|
| 362 |
+
"""Open → Close → Fill holes → Largest component (no dilation)."""
|
| 363 |
+
mask01 = (mask01 > 0).astype(np.uint8)
|
| 364 |
+
k3 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
|
| 365 |
+
k5 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
| 366 |
+
mask01 = cv2.morphologyEx(mask01, cv2.MORPH_OPEN, k3, iterations=1)
|
| 367 |
+
mask01 = cv2.morphologyEx(mask01, cv2.MORPH_CLOSE, k5, iterations=1)
|
| 368 |
+
mask01 = _fill_holes(mask01)
|
| 369 |
+
# Keep largest component only
|
| 370 |
+
num, labels, stats, _ = cv2.connectedComponentsWithStats(mask01, 8)
|
| 371 |
+
if num > 1:
|
| 372 |
+
areas = stats[1:, cv2.CC_STAT_AREA]
|
| 373 |
+
if areas.size:
|
| 374 |
+
largest_idx = 1 + int(np.argmax(areas))
|
| 375 |
+
mask01 = (labels == largest_idx).astype(np.uint8)
|
| 376 |
+
return (mask01 > 0).astype(np.uint8)
|
| 377 |
+
|
| 378 |
+
# Global last debug dict (per-process)
|
| 379 |
_last_seg_debug: Dict[str, object] = {}
|
| 380 |
|
| 381 |
def segment_wound(image_bgr: np.ndarray, ts: str, out_dir: str) -> Tuple[np.ndarray, Dict[str, object]]:
|
| 382 |
"""
|
| 383 |
+
TF model → adaptive threshold on prob → GrabCut grow → cleanup.
|
| 384 |
+
Fallback: KMeans-Lab.
|
| 385 |
Returns (mask_uint8_0_255, debug_dict)
|
| 386 |
"""
|
| 387 |
+
debug = {"used": None, "reason": None, "positive_fraction": 0.0,
|
| 388 |
+
"thr": None, "heatmap_path": None, "roi_seen_by_model": None}
|
| 389 |
|
| 390 |
seg_model = models_cache.get("seg", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
|
| 392 |
+
# --- Model path ---
|
| 393 |
if seg_model is not None:
|
| 394 |
try:
|
| 395 |
ishape = getattr(seg_model, "input_shape", None)
|
| 396 |
if not ishape or len(ishape) < 4:
|
| 397 |
raise ValueError(f"Bad seg input_shape: {ishape}")
|
| 398 |
th, tw = int(ishape[1]), int(ishape[2])
|
| 399 |
+
|
| 400 |
x = _preprocess_for_seg(image_bgr, (th, tw))
|
| 401 |
+
roi_seen_path = None
|
| 402 |
if SMARTHEAL_DEBUG:
|
| 403 |
+
roi_seen_path = os.path.join(out_dir, f"roi_for_seg_{ts}.png")
|
| 404 |
+
cv2.imwrite(roi_seen_path, image_bgr)
|
| 405 |
|
|
|
|
| 406 |
pred = seg_model.predict(x, verbose=0)
|
| 407 |
+
if isinstance(pred, (list, tuple)): pred = pred[0]
|
| 408 |
+
p = _to_prob(pred)
|
| 409 |
+
p = cv2.resize(p, (image_bgr.shape[1], image_bgr.shape[0]), interpolation=cv2.INTER_LINEAR)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
|
| 411 |
+
heatmap_path = None
|
| 412 |
if SMARTHEAL_DEBUG:
|
| 413 |
hm = (np.clip(p, 0, 1) * 255).astype(np.uint8)
|
| 414 |
heat = cv2.applyColorMap(hm, cv2.COLORMAP_JET)
|
| 415 |
heatmap_path = os.path.join(out_dir, f"seg_pred_heatmap_{ts}.png")
|
| 416 |
cv2.imwrite(heatmap_path, heat)
|
| 417 |
|
| 418 |
+
thr = _adaptive_prob_threshold(p)
|
| 419 |
+
core01 = (p >= thr).astype(np.uint8)
|
| 420 |
+
core_frac = float(core01.sum()) / float(core01.size)
|
| 421 |
+
|
| 422 |
+
if core_frac < 0.005:
|
| 423 |
+
thr2 = max(thr - 0.10, 0.15)
|
| 424 |
+
core01 = (p >= thr2).astype(np.uint8)
|
| 425 |
+
thr = thr2
|
| 426 |
+
core_frac = float(core01.sum()) / float(core01.size)
|
| 427 |
+
|
| 428 |
+
if core01.any():
|
| 429 |
+
gc01 = _grabcut_refine(image_bgr, core01, iters=3)
|
| 430 |
+
mask01 = _clean_mask(gc01)
|
| 431 |
+
else:
|
| 432 |
+
mask01 = np.zeros(core01.shape, np.uint8)
|
| 433 |
+
|
| 434 |
+
pos_frac = float(mask01.sum()) / float(mask01.size)
|
| 435 |
+
logging.info(f"SegModel USED | thr={float(thr):.2f} core_frac={core_frac:.4f} final_frac={pos_frac:.4f}")
|
| 436 |
+
|
| 437 |
+
debug.update({
|
| 438 |
+
"used": "tf_model",
|
| 439 |
+
"reason": "ok",
|
| 440 |
+
"positive_fraction": pos_frac,
|
| 441 |
+
"thr": float(thr),
|
| 442 |
"heatmap_path": heatmap_path,
|
| 443 |
+
"roi_seen_by_model": roi_seen_path
|
| 444 |
+
})
|
| 445 |
+
return (mask01 * 255).astype(np.uint8), debug
|
| 446 |
|
| 447 |
except Exception as e:
|
| 448 |
+
logging.warning(f"⚠️ Segmentation model failed → fallback. Reason: {e}")
|
| 449 |
+
debug.update({"used": "fallback_kmeans", "reason": f"model_failed: {e}"})
|
| 450 |
|
| 451 |
+
# --- Fallback: KMeans in Lab (reddest cluster as wound) ---
|
| 452 |
Z = image_bgr.reshape((-1, 3)).astype(np.float32)
|
| 453 |
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
|
| 454 |
_, labels, centers = cv2.kmeans(Z, 2, None, criteria, 5, cv2.KMEANS_PP_CENTERS)
|
| 455 |
centers_u8 = centers.astype(np.uint8).reshape(1, 2, 3)
|
| 456 |
centers_lab = cv2.cvtColor(centers_u8, cv2.COLOR_BGR2LAB)[0]
|
| 457 |
+
wound_idx = int(np.argmax(centers_lab[:, 1])) # maximize a* (red)
|
| 458 |
+
mask01 = (labels.reshape(image_bgr.shape[:2]) == wound_idx).astype(np.uint8)
|
| 459 |
+
mask01 = _clean_mask(mask01)
|
| 460 |
+
|
| 461 |
+
pos_frac = float(mask01.sum()) / float(mask01.size)
|
| 462 |
+
logging.info(f"KMeans USED | final_frac={pos_frac:.4f}")
|
| 463 |
+
|
| 464 |
+
debug.update({
|
| 465 |
+
"used": "fallback_kmeans",
|
| 466 |
+
"reason": debug.get("reason") or "no_model",
|
| 467 |
+
"positive_fraction": pos_frac,
|
| 468 |
+
"thr": None
|
| 469 |
+
})
|
| 470 |
+
return (mask01 * 255).astype(np.uint8), debug
|
|
|
|
|
|
|
| 471 |
|
| 472 |
# ---------- Measurement + overlay helpers ----------
|
| 473 |
def largest_component_mask(binary01: np.ndarray, min_area_px: int = 50) -> np.ndarray:
|
|
|
|
| 480 |
largest_idx = 1 + int(np.argmax(areas))
|
| 481 |
return (labels == largest_idx).astype(np.uint8)
|
| 482 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
def measure_min_area_rect(mask01: np.ndarray, px_per_cm: float) -> Tuple[float, float, Tuple]:
|
| 484 |
contours, _ = cv2.findContours(mask01.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 485 |
if not contours:
|
|
|
|
| 493 |
box = cv2.boxPoints(rect).astype(int)
|
| 494 |
return length_cm, breadth_cm, (box, rect[0])
|
| 495 |
|
| 496 |
+
def area_cm2_from_contour(mask01: np.ndarray, px_per_cm: float) -> Tuple[float, Optional[np.ndarray]]:
|
| 497 |
+
"""Area from largest polygon (sub-pixel); returns (area_cm2, contour)."""
|
| 498 |
+
m = (mask01 > 0).astype(np.uint8)
|
| 499 |
+
contours, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 500 |
+
if not contours:
|
| 501 |
+
return 0.0, None
|
| 502 |
+
cnt = max(contours, key=cv2.contourArea)
|
| 503 |
+
poly_area_px2 = float(cv2.contourArea(cnt))
|
| 504 |
+
area_cm2 = round(poly_area_px2 / (max(px_per_cm, 1e-6) ** 2), 2)
|
| 505 |
+
return area_cm2, cnt
|
| 506 |
+
|
| 507 |
+
def clamp_area_with_minrect(cnt: np.ndarray, px_per_cm: float, area_cm2_poly: float) -> float:
|
| 508 |
+
rect = cv2.minAreaRect(cnt)
|
| 509 |
+
(w_px, h_px) = rect[1]
|
| 510 |
+
rect_area_px2 = float(max(w_px, 0.0) * max(h_px, 0.0))
|
| 511 |
+
rect_area_cm2 = rect_area_px2 / (max(px_per_cm, 1e-6) ** 2)
|
| 512 |
+
return round(min(area_cm2_poly, rect_area_cm2 * 1.05), 2)
|
| 513 |
|
| 514 |
def draw_measurement_overlay(
|
| 515 |
base_bgr: np.ndarray,
|
|
|
|
| 520 |
thickness: int = 2
|
| 521 |
) -> np.ndarray:
|
| 522 |
"""
|
| 523 |
+
1) Strong red mask overlay + white contour
|
| 524 |
+
2) Min-area rectangle
|
| 525 |
+
3) Double-headed arrows labeled Length/Width
|
|
|
|
|
|
|
|
|
|
| 526 |
"""
|
| 527 |
overlay = base_bgr.copy()
|
| 528 |
|
| 529 |
+
# Mask tint
|
| 530 |
mask255 = (mask01 * 255).astype(np.uint8)
|
| 531 |
mask3 = cv2.merge([mask255, mask255, mask255])
|
| 532 |
red = np.zeros_like(overlay); red[:] = (0, 0, 255)
|
|
|
|
| 534 |
tinted = cv2.addWeighted(overlay, 1 - alpha, red, alpha, 0)
|
| 535 |
overlay = np.where(mask3 > 0, tinted, overlay)
|
| 536 |
|
| 537 |
+
# Contour
|
| 538 |
cnts, _ = cv2.findContours(mask255, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 539 |
if cnts:
|
| 540 |
cv2.drawContours(overlay, cnts, -1, (255, 255, 255), 2)
|
|
|
|
| 543 |
cv2.polylines(overlay, [rect_box], True, (255, 255, 255), thickness)
|
| 544 |
pts = rect_box.reshape(-1, 2)
|
| 545 |
|
| 546 |
+
def midpoint(a, b): return (int((a[0] + b[0]) / 2), int((a[1] + b[1]) / 2))
|
|
|
|
|
|
|
|
|
|
| 547 |
e = [np.linalg.norm(pts[i] - pts[(i + 1) % 4]) for i in range(4)]
|
| 548 |
long_edge_idx = int(np.argmax(e))
|
|
|
|
|
|
|
|
|
|
| 549 |
mids = [midpoint(pts[i], pts[(i + 1) % 4]) for i in range(4)]
|
|
|
|
| 550 |
long_pair = (long_edge_idx, (long_edge_idx + 2) % 4)
|
|
|
|
| 551 |
short_pair = ((long_edge_idx + 1) % 4, (long_edge_idx + 3) % 4)
|
| 552 |
|
| 553 |
def draw_double_arrow(img, p1, p2):
|
|
|
|
| 561 |
cv2.putText(overlay, text, org, cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 4, cv2.LINE_AA)
|
| 562 |
cv2.putText(overlay, text, org, cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, cv2.LINE_AA)
|
| 563 |
|
|
|
|
| 564 |
draw_double_arrow(overlay, mids[long_pair[0]], mids[long_pair[1]])
|
| 565 |
draw_double_arrow(overlay, mids[short_pair[0]], mids[short_pair[1]])
|
| 566 |
put_label(f"Length: {length_cm:.2f} cm", mids[long_pair[0]])
|
|
|
|
| 589 |
"""
|
| 590 |
try:
|
| 591 |
px_per_cm, exif_meta = estimate_px_per_cm_from_exif(image_pil, DEFAULT_PX_PER_CM)
|
| 592 |
+
# Guardrails for calibration to avoid huge area blow-ups
|
| 593 |
+
px_per_cm = float(np.clip(px_per_cm, 20.0, 350.0))
|
| 594 |
+
if (exif_meta or {}).get("used") != "exif":
|
| 595 |
+
logging.warning(f"Calibration fallback used: px_per_cm={px_per_cm:.2f} (default). Prefer ruler/Aruco for accuracy.")
|
| 596 |
+
|
| 597 |
image_cv = cv2.cvtColor(np.array(image_pil.convert("RGB")), cv2.COLOR_RGB2BGR)
|
| 598 |
|
| 599 |
# --- Detection ---
|
|
|
|
| 627 |
mask_u8_255, seg_debug = segment_wound(roi, ts, out_dir)
|
| 628 |
mask01 = (mask_u8_255 > 127).astype(np.uint8)
|
| 629 |
|
|
|
|
| 630 |
if mask01.any():
|
| 631 |
mask01 = _clean_mask(mask01)
|
| 632 |
logging.debug(f"Mask postproc: px_after={int(mask01.sum())}")
|
| 633 |
|
| 634 |
+
# --- Measurement (accurate & conservative) ---
|
| 635 |
if mask01.any():
|
| 636 |
length_cm, breadth_cm, (box_pts, _) = measure_min_area_rect(mask01, px_per_cm)
|
| 637 |
+
area_poly_cm2, largest_cnt = area_cm2_from_contour(mask01, px_per_cm)
|
| 638 |
+
if largest_cnt is not None:
|
| 639 |
+
surface_area_cm2 = clamp_area_with_minrect(largest_cnt, px_per_cm, area_poly_cm2)
|
| 640 |
+
else:
|
| 641 |
+
surface_area_cm2 = area_poly_cm2
|
| 642 |
+
|
| 643 |
anno_roi = draw_measurement_overlay(roi, mask01, box_pts, length_cm, breadth_cm)
|
| 644 |
segmentation_empty = False
|
| 645 |
else:
|
| 646 |
+
# Fallback if seg failed: use ROI dimensions
|
| 647 |
h_px = max(0, y2 - y1); w_px = max(0, x2 - x1)
|
| 648 |
length_cm = round(max(h_px, w_px) / px_per_cm, 2)
|
| 649 |
breadth_cm = round(min(h_px, w_px) / px_per_cm, 2)
|
|
|
|
| 667 |
roi_mask_path = os.path.join(out_dir, f"roi_mask_{ts}.png")
|
| 668 |
cv2.imwrite(roi_mask_path, (mask01 * 255).astype(np.uint8))
|
| 669 |
|
| 670 |
+
# ROI overlay (mask tint + contour, without arrows)
|
| 671 |
mask255 = (mask01 * 255).astype(np.uint8)
|
| 672 |
mask3 = cv2.merge([mask255, mask255, mask255])
|
| 673 |
red = np.zeros_like(roi); red[:] = (0, 0, 255)
|
|
|
|
| 710 |
"seg_used": seg_debug.get("used"),
|
| 711 |
"seg_reason": seg_debug.get("reason"),
|
| 712 |
"positive_fraction": round(float(seg_debug.get("positive_fraction", 0.0)), 6),
|
| 713 |
+
"threshold": seg_debug.get("thr"),
|
| 714 |
"segmentation_empty": segmentation_empty,
|
| 715 |
"exif_px_per_cm": round(px_per_cm, 3),
|
| 716 |
}
|
|
|
|
| 726 |
"detection_confidence": float(results[0].boxes.conf[0].cpu().item())
|
| 727 |
if getattr(results[0].boxes, "conf", None) is not None else 0.0,
|
| 728 |
"detection_image_path": detection_path,
|
| 729 |
+
"segmentation_image_path": annotated_seg_path,
|
| 730 |
"segmentation_annotated_path": annotated_seg_path,
|
| 731 |
"segmentation_roi_path": segmentation_roi_path,
|
| 732 |
"roi_mask_path": roi_mask_path,
|
|
|
|
| 909 |
"report": f"Analysis initialization failed: {str(e)}",
|
| 910 |
"saved_image_path": None,
|
| 911 |
"guideline_context": "",
|
| 912 |
+
}
|