qqwjq1981 commited on
Commit
af10e17
·
verified ·
1 Parent(s): 7e9867d

Upload bubble_detect.py

Browse files
Files changed (1) hide show
  1. utils/bubble_detect.py +39 -0
utils/bubble_detect.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from shapely.geometry import Polygon
4
+
5
+ def detect_speech_bubbles(img_pil):
6
+ img = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)
7
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
8
+
9
+ # Adaptive threshold handles dark scenes + uneven lighting
10
+ th = cv2.adaptiveThreshold(
11
+ gray, 255,
12
+ cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
13
+ cv2.THRESH_BINARY,
14
+ 35, 10
15
+ )
16
+
17
+ inv = 255 - th # bubbles become white
18
+
19
+ # Close small gaps in bubble borders
20
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
21
+ cleaned = cv2.morphologyEx(inv, cv2.MORPH_CLOSE, kernel, iterations=2)
22
+
23
+ contours, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
24
+
25
+ bubbles = []
26
+
27
+ for cnt in contours:
28
+ area = cv2.contourArea(cnt)
29
+ if area < 500:
30
+ continue
31
+
32
+ approx = cv2.approxPolyDP(cnt, 0.01 * cv2.arcLength(cnt, True), True)
33
+
34
+ poly = [(int(p[0][0]), int(p[0][1])) for p in approx]
35
+
36
+ # verify shape is bubble-like (optional)
37
+ bubbles.append(poly)
38
+
39
+ return bubbles