0

I have this image:

test_image.png

I am trying to detect and draw bounding rectangles based on contours.

Everything works correctly except the area at the bottom right which gets detected as multiple contours.

I would like to find out how to merge those nearby contours in that area so that I can draw it as a single bigger rectangle that encloses them.

This is the code that I use:

import cv2 

img_path = "test_image.png"
img = cv2.imread(img_path)

gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY_INV)[1]

contours = cv2.findContours(thresh_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]

for i in contours:
    x, y, w, h = cv2.boundingRect(i)
    cv2.rectangle(img, (x, y), (x + w, y + h), (255,0,0), 4)

cv2.imshow(img_path, img)
cv2.waitKey(0) 
mangotango
  • 326
  • 4
  • 15
  • Possibly similar question: https://stackoverflow.com/q/44501723/7613480 – UdonN00dle Nov 04 '22 at 00:46
  • A quick&dirty approach: Run a cv.dilate() on the raw image before extracting contrours so that the small objects merge into one. Then subtract the dilation value from the bounding box, if thats all you need. This depends heavily on the variance between the drawings symbols and how widely spaced they are. – nick Nov 04 '22 at 12:24
  • Btw. how do you handle the contours found for letters inside the objects on the top right ('in') and the big circles ('+') ? – nick Nov 04 '22 at 12:26
  • Thank you, I had thought about cv.dilate() but not about subtracting the value afterwards. As it is, it won't draw smaller contours for "in" and "+". – mangotango Nov 05 '22 at 02:10

0 Answers0