Good day,
I have used cv2.findContours on an image. After that, I have extracted the contour and hierarchy information. From there, how do I filter and draw only contours without child (which from my understanding has a value of -1 in the 3rd column in the hierarchy array)?
below is my code:my image
from imutils import perspective
from imutils import contours
import numpy as np
import imutils
import cv2
img = cv2.imread('TESTING.png')
imgs = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edged = imgs
cnts = cv2.findContours(edged,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = cnts[2]
ChildContour = hierarchy [0, :,2]
WithoutChildContour = (ChildContour==-1).nonzero()[0]
cntsA = cnts[0] if imutils.is_cv2() else cnts[1]
if not cntsA:
print ("no contours")
(cntsB, _) = contours.sort_contours(cntsA)
orig = cv2.imread('TESTING.png')
for c in cntsB:
if cv2.contourArea(c) < 100:
continue
box = cv2.minAreaRect(c)
box = cv2.boxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
box = np.array(box, dtype="int")
box = perspective.order_points(box)
cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)
screen_res = 972, 648
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)
cv2.namedWindow('Image', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Image', window_width, window_height)
cv2.imshow("Image", orig)
cv2.waitKey(0)
cv2.destroyAllWindows()
The hierarchy returned by findContours
has four columns : [Next, Previous, First_Child, Parent]. As you pointed out, we are interested in index 2 i.e. First_Child. To filter and draw only contours without child, you can loop on indices present in WithoutChildContour
.
cntsA=[ cntsA[i] for i in WithoutChildContour]
Here's the corresponding snippet:
Note: Since opencv 4.0, findContours returns only 2 values (cnts and hierarchy).
# ...
hierarchy = cnts[1] #changed index
ChildContour = hierarchy [0, :,2]
WithoutChildContour = (ChildContour==-1).nonzero()[0]
cntsA = cnts[0]
# get contours from indices
cntsA=[ cntsA[i] for i in WithoutChildContour]
# ...
Running on your sample image: