I have this image:
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)