SmartHeal commited on
Commit
c0d5504
·
verified ·
1 Parent(s): 8ba3ba0

Update src/ai_processor.py

Browse files
Files changed (1) hide show
  1. src/ai_processor.py +15 -6
src/ai_processor.py CHANGED
@@ -232,7 +232,6 @@ initialize_cpu_models()
232
  setup_knowledge_base()
233
 
234
  # ---------- Calibration helpers ----------
235
- # ---- Adaptive thresholding for model prob map ----
236
  def _adaptive_prob_threshold(p: np.ndarray) -> float:
237
  """
238
  Pick a threshold that avoids tiny blobs while not swallowing skin.
@@ -244,20 +243,30 @@ def _adaptive_prob_threshold(p: np.ndarray) -> float:
244
  p01 = np.clip(p.astype(np.float32), 0, 1)
245
  p255 = (p01 * 255).astype(np.uint8)
246
 
247
- # Otsu
248
- _, thr_otsu = cv2.threshold(p255, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
249
- thr_otsu = np.clip(thr_otsu / 255.0, 0.25, 0.65)
250
 
251
  # Percentile (90th)
252
  thr_pctl = float(np.clip(np.percentile(p01, 90), 0.25, 0.65))
253
 
254
- # Prefer the threshold that yields an area fraction in [0.005..0.20]
255
- def area_frac(thr):
256
  return float((p01 >= thr).sum()) / float(p01.size)
257
 
258
  af_otsu = area_frac(thr_otsu)
259
  af_pctl = area_frac(thr_pctl)
260
 
 
 
 
 
 
 
 
 
 
 
261
  # Score: closeness to a target area fraction (aim ~3–10%)
262
  def score(af):
263
  target_low, target_high = 0.03, 0.10
 
232
  setup_knowledge_base()
233
 
234
  # ---------- Calibration helpers ----------
 
235
  def _adaptive_prob_threshold(p: np.ndarray) -> float:
236
  """
237
  Pick a threshold that avoids tiny blobs while not swallowing skin.
 
243
  p01 = np.clip(p.astype(np.float32), 0, 1)
244
  p255 = (p01 * 255).astype(np.uint8)
245
 
246
+ # Otsu → use the returned scalar threshold (ret), NOT the image
247
+ ret_otsu, _dst = cv2.threshold(p255, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
248
+ thr_otsu = float(np.clip(ret_otsu / 255.0, 0.25, 0.65))
249
 
250
  # Percentile (90th)
251
  thr_pctl = float(np.clip(np.percentile(p01, 90), 0.25, 0.65))
252
 
253
+ # Area fraction helper
254
+ def area_frac(thr: float) -> float:
255
  return float((p01 >= thr).sum()) / float(p01.size)
256
 
257
  af_otsu = area_frac(thr_otsu)
258
  af_pctl = area_frac(thr_pctl)
259
 
260
+ # Score: prefer ~3–10% coverage
261
+ def score(af: float) -> float:
262
+ target_low, target_high = 0.03, 0.10
263
+ if af < target_low: return abs(af - target_low) * 3.0
264
+ if af > target_high: return abs(af - target_high) * 1.5
265
+ return 0.0
266
+
267
+ return thr_otsu if score(af_otsu) <= score(af_pctl) else thr_pctl
268
+
269
+
270
  # Score: closeness to a target area fraction (aim ~3–10%)
271
  def score(af):
272
  target_low, target_high = 0.03, 0.10