How to find contours of white object having little bit of black object?
I have white background with a black filled rectangle in the center. I need to have contours of white regions. cv2.findContours gives one full contour of the whole image. How to use this cv2.findContours function?
import numpy as np
import cv2
white_img = np.ones((190, 640, 3), np.uint8) * 255
(rows, cols, channels) = white_img.shape
gray = cv2.cvtColor(white_img, cv2.COLOR_BGR2GRAY)
cv2.rectangle(gray, (320, 100), (380, 190), (0, 0, 0), cv2.FILLED)
contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
print(len(contours))
for c in contours:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(white_img, (x, y), (x + w, y + h), (0, 0, 255), 3)
cv2.imshow('white_img', white_img)
cv2.waitKey(0)
Input Image
Output should be like this
Other input could be like
Its output should be
For each column, check height of black section. If height changes, then start a new box. Or something close to that.
it is not necessary that the black object is a rectangle only. It could be of any shape.