qqwjq1981 commited on
Commit
e63ba27
·
verified ·
1 Parent(s): 9b8e87c

Update utils/polygon_utils.py

Browse files
Files changed (1) hide show
  1. utils/polygon_utils.py +27 -6
utils/polygon_utils.py CHANGED
@@ -34,13 +34,33 @@ def calculate_iou(poly1, poly2):
34
  print(f"⚠️ calculate_iou failed: {e}")
35
  return 0.0
36
 
37
-
38
- def calculate_polygon_overlap(ocr_poly, bubble_poly):
39
  """
40
- Calculate what percentage of OCR polygon is inside bubble polygon.
41
- overlap = area(ocr ∩ bubble) / area(ocr)
42
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  try:
 
 
 
 
 
44
  ocr_shape = Polygon(ocr_poly)
45
  bubble_shape = Polygon(bubble_poly)
46
 
@@ -49,10 +69,11 @@ def calculate_polygon_overlap(ocr_poly, bubble_poly):
49
  if not bubble_shape.is_valid:
50
  bubble_shape = bubble_shape.buffer(0)
51
 
52
- intersection = ocr_shape.intersection(bubble_shape).area
53
  ocr_area = ocr_shape.area
54
 
55
- return intersection / ocr_area if ocr_area > 0 else 0.0
 
56
  except Exception as e:
57
  print(f"⚠️ calculate_polygon_overlap failed: {e}")
58
  return 0.0
 
34
  print(f"⚠️ calculate_iou failed: {e}")
35
  return 0.0
36
 
37
+ def sanitize_polygon(poly):
 
38
  """
39
+ Ensures polygon has at least 4 distinct points.
40
+ Returns None if invalid.
41
  """
42
+ if not poly:
43
+ return None
44
+
45
+ # Flatten & cast to int
46
+ pts = [(int(x), int(y)) for x, y in poly if isinstance(x, (int,float)) and isinstance(y, (int,float))]
47
+
48
+ # Remove duplicates
49
+ pts = list(dict.fromkeys(pts))
50
+
51
+ # Must have ≥ 4 points
52
+ if len(pts) < 4:
53
+ return None
54
+
55
+ return pts
56
+
57
+ def calculate_polygon_overlap(ocr_poly, bubble_poly):
58
  try:
59
+ if not ocr_poly or not bubble_poly:
60
+ return 0.0
61
+ if len(ocr_poly) < 4 or len(bubble_poly) < 4:
62
+ return 0.0
63
+
64
  ocr_shape = Polygon(ocr_poly)
65
  bubble_shape = Polygon(bubble_poly)
66
 
 
69
  if not bubble_shape.is_valid:
70
  bubble_shape = bubble_shape.buffer(0)
71
 
72
+ inter = ocr_shape.intersection(bubble_shape).area
73
  ocr_area = ocr_shape.area
74
 
75
+ return inter / ocr_area if ocr_area > 0 else 0.0
76
+
77
  except Exception as e:
78
  print(f"⚠️ calculate_polygon_overlap failed: {e}")
79
  return 0.0