How to ignore inner black contours in OpenCV python?

Viewed 1326

In the above image, I only need the following contours: 8, 7, 0, 2, 4.

Every other contour black empty boxes inside them. Is there a way to automatically extract only such contours using cv2.RETR_TREE?

cv2.RETR_EXTERNAL will ignore 2 and 4 which I actually need

       >>heirarchy

       >>array([[[ 7, -1,  1, -1],

        [-1, -1,  2,  0],

        [-1, -1,  3,  1],

        [-1, -1,  4,  2],

        [-1, -1,  5,  3],

        [ 6, -1, -1,  4],

        [-1,  5, -1,  4],

        [ 8,  0, -1, -1],

        [-1,  7, -1, -1]]])

How can I extract from the above heirarchy only the external contours but not exlcuding 2 and 4 and ignoring 1, 3, 5, 6 since those four contours contain just empty regions inside?

2 Answers

You can use cv2.contourArea(contour) to get the area of the contour and then set a minimum area condition to get rid of too small contours.

If you are free to use any other method than cv2.RETR_TREE , then you can use cv2.RETR_CCOMP which divides contours in only two level hierarchy i.e outer and inner. You can only pick those contours whose parent index (value at index 3) is -1. '-1' denotes that the contours do not have any parent. You will only get the following contours: 8, 7, 0, 2, 4.

Reference : https://docs.opencv.org/3.4/d9/d8b/tutorial_py_contours_hierarchy.html

Related