I’ve an input image like below :
]
I did some processing and got lines from my input image as below Lined Image :
I want to have output with cell detected like this: Output Image
I tried to found cells Bounding box using findContours
and connectedComponentsWithStats
method but they’re not giving me a satisfying results.
My Code:
For Contours:
JavaScript
x
6
1
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
2
3
for contour in contours[2:]:
4
(x,y,w,h) = cv2.boundingRect(contour)
5
cv2.rectangle(img, (x,y), (x+w,y+h),(0, 255, 0),2)
6
For connectedComponentsWithStats:
JavaScript
1
4
1
_, labels, stats,_ = cv2.connectedComponentsWithStats(img, connectivity=4, ltype=cv2.CV_32S)
2
for x,y,w,h,area in stats[2:]:
3
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
4
Any Help is appreciated.
Advertisement
Answer
JavaScript
1
36
36
1
# https://stackoverflow.com/questions/59979760/how-to-detect-all-rectangular-boxes-python-opencv-without-missing-anything
2
import cv2
3
4
image = cv2.imread('JoWnj.jpg')
5
result = image.copy()
6
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
7
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 51, 9)
8
9
# Fill rectangular contours
10
# CHECK OTHER CONTOUR SETTINGS ? TO EXLCUDE OUTER ?
11
# https://docs.opencv.org/master/d9/d8b/tutorial_py_contours_hierarchy.html
12
# https://medium.com/analytics-vidhya/opencv-findcontours-detailed-guide-692ee19eeb18
13
# cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
14
cnts = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
15
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
16
for c in cnts:
17
cv2.drawContours(thresh, [c], -1, (255, 255, 255), -1)
18
cv2.drawContours(thresh, [c], -1, (0, 0, 0), 1)
19
20
# Morph open
21
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 4))
22
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=4)
23
# opening = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=4)
24
25
# Draw rectangles
26
# cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
27
cnts = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
28
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
29
for c in cnts:
30
x, y, w, h = cv2.boundingRect(c)
31
cv2.rectangle(image, (x, y-3), (x + w, y + h-3), (36, 255, 12), 1)
32
# filled
33
# cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), -1)
34
35
cv2.imwrite('sunday.jpg', image)
36
result image that You want: Reference: