Skip to content
Advertisement

How to improve rectangles from image using opencv?

I’ve an input image like below :

enter image description here]

I did some processing and got lines from my input image as below Lined Image :

enter image description here

I want to have output with cell detected like this: Output Image

enter image description here

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:

contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

for contour in contours[2:]:
    (x,y,w,h) = cv2.boundingRect(contour)
    cv2.rectangle(img, (x,y), (x+w,y+h),(0, 255, 0),2)

For connectedComponentsWithStats:

_, labels, stats,_ = cv2.connectedComponentsWithStats(img, connectivity=4, ltype=cv2.CV_32S)
for x,y,w,h,area in stats[2:]:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

Any Help is appreciated.

Advertisement

Answer

# https://stackoverflow.com/questions/59979760/how-to-detect-all-rectangular-boxes-python-opencv-without-missing-anything
import cv2

image = cv2.imread('JoWnj.jpg')
result = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 51, 9)

# Fill rectangular contours
# CHECK OTHER CONTOUR SETTINGS ? TO EXLCUDE OUTER ?
# https://docs.opencv.org/master/d9/d8b/tutorial_py_contours_hierarchy.html
# https://medium.com/analytics-vidhya/opencv-findcontours-detailed-guide-692ee19eeb18
# cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(thresh, [c], -1, (255, 255, 255), -1)
    cv2.drawContours(thresh, [c], -1, (0, 0, 0), 1)

# Morph open
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 4))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=4)
# opening = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=4)

# Draw rectangles
# cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x, y, w, h = cv2.boundingRect(c)
    cv2.rectangle(image, (x, y-3), (x + w, y + h-3), (36, 255, 12), 1)
    # filled
    # cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), -1)

cv2.imwrite('sunday.jpg', image)

result image that You want: Reference:

  1. How to detect all rectangular boxes python opencv without missing anything
  2. Unboxing opencv rectangles
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement