coderuday21 commited on
Commit
ba711fa
·
1 Parent(s): 18a63c5

Fix: fallback to Image Difference when AI/Hybrid mask is too sparse

Browse files
Files changed (1) hide show
  1. app/detection_engine.py +26 -0
app/detection_engine.py CHANGED
@@ -1677,6 +1677,32 @@ def run_detection(before_pil, after_pil, method="AI-Based Deep Learning",
1677
  before_array, after_array, sensitivity=detection_sensitivity
1678
  )
1679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1680
  change_regions = analyze_change_regions(
1681
  change_mask,
1682
  after_array,
 
1677
  before_array, after_array, sensitivity=detection_sensitivity
1678
  )
1679
 
1680
+ # --- Adaptive fallback for empty/sparse masks ---
1681
+ # In some scenes, ORB/ECC registration + fused thresholding can produce an overly
1682
+ # sparse binary mask (leading to 0 detected regions). If that happens, fall back
1683
+ # to the more stable Image Difference mask.
1684
+ total_pixels = int(change_mask.shape[0] * change_mask.shape[1])
1685
+ changed_pixels_ratio = float(np.sum(change_mask > 127)) / float(total_pixels) if total_pixels else 0.0
1686
+
1687
+ used_fallback = False
1688
+ if method in ("AI-Based Deep Learning", "Hybrid Approach") and changed_pixels_ratio < 0.0025:
1689
+ diff_mask, diff_debug = image_difference_method(
1690
+ before_array, after_array, sensitivity=detection_sensitivity
1691
+ )
1692
+ diff_ratio = float(np.sum(diff_mask > 127)) / float(total_pixels) if total_pixels else 0.0
1693
+ # Only switch if the diff mask clearly contains more signal.
1694
+ if diff_ratio > max(0.005, changed_pixels_ratio * 3.0):
1695
+ change_mask = diff_mask
1696
+ used_fallback = True
1697
+ threshold_debug = {
1698
+ "method": f"{method} (fallback->Image Difference)",
1699
+ "fallback_used": True,
1700
+ "ai_hybrid_changed_ratio": changed_pixels_ratio,
1701
+ "diff_changed_ratio": diff_ratio,
1702
+ "diff_debug": diff_debug,
1703
+ "sensitivity": float(detection_sensitivity),
1704
+ }
1705
+
1706
  change_regions = analyze_change_regions(
1707
  change_mask,
1708
  after_array,