I have two binary images and I am trying to detect the contours of the white patches in them (the pink outline in the right of the collage is the contour result).
cv2.contourFind()
is working fine for Contour1:
But for Contour2 it's acting weird:
Here is the function call for it
#Convert Image to grayscale
img = cv2.imread(file_name)
img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
dilated = cv2.dilate(mask, kernel, iterations=2)
image, contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in contours:
[x, y, w, h] = cv2.boundingRect(contour)
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)
Using this contours
variable I draw rectangles around the points found.
I don't understand why it works for Contour1, but fails for Contour2 when they look pretty similar.
Mistake: The binary image had a thin white border box in Contour2 but not in Contour1 (my bad!). Since I asked for only external contours, cv2.RETR_EXTERNAL
in
image, contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for Contour2 had only the outermost box detected and hence none of its children got drawn. But in Contour1 there is no white border box around the binary image hence the internal white blobs got detected.
Solution: Use cv2.RETR_LIST
or cv2.RETR_CCOMP