Search code examples
pythonopencvnestedhierarchymask

Building nested mask from contours with openCV


I'd like to build a nested mask (mask with holes) from contours that I've drawn.

The input contour image is attached to this message - called contours.png -, and here is the code I used to build my nested mask.

import cv2
import numpy as np
import matplotlib.pyplot as plt

test_im = cv2.imread("contours.png")
im_gray = cv2.cvtColor(test_im, cv2.COLOR_RGB2GRAY)

# find contours and hierarchy with OpenCV 
cnts, hierachy = cv2.findContours(im_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = np.array(cnts)

mask = np.zeros_like(test_im)

# draw nested mask from contours using cv2.fillPoly
for i, cnt in enumerate(cnts):

    # look for external contours
    if hierachy[0][i][3] == -1:
        cnt = cnt.reshape((cnt.shape[0], 2))
        # fill the external contour entirely
        cv2.fillPoly(mask, [cnt], 255)

        # look for grandchild contours to fill them with zeros (and have a nested mask as output)
        child_ix = hierachy[0][i][2]
        same_level_ix = hierachy[0][child_ix][0]

        # for an akward reason, the extrenal contour has two child contours
        # (should get only one in my understanding)
        if same_level_ix == -1:
            grandchild_ix = hierachy[0][child_ix][2]
        else:
            child_ix = hierachy[0][child_ix][2]
            grandchild_ix = hierachy[0][same_level_ix][2]

        if grandchild_ix != -1:
            cnt = cnts[grandchild_ix]
            cnt = cnt.reshape((cnt.shape[0], 2))
            cv2.fillPoly(mask, [cnt], 0)
            same_level_ix = hierachy[0][grandchild_ix][0]

            while same_level_ix != -1:
                cnt = cnts[same_level_ix]
                cnt = cnt.reshape((cnt.shape[0], 2))
                cv2.fillPoly(mask, [cnt], 0)
                same_level_ix = hierachy[0][same_level_ix][0]

Even if it works on this example, my code doesn't seem really robust. Additionaly, I found that the external contour has two child contours which is weird to me: should get only one in my understanding.

Do you have any better solution ?

Thanks for your help, have a nice day !

contours.png

desired_output


Solution

  • Based on the hierarchy settings, you can get the result by making 2 mask, and subtracting them. First mask is done by filling the outermost contour, and the second mask is done by filling the innermost contours:

    enter image description here

    Here is the necessary setting for extracting contours and filling them (the code in c++ but the settings are equivalent with python):

    Mat img__1, img__2,img__ = imread("E:/img.jpg", 0);
    
    threshold(img__, img__1, 0, 255, THRESH_BINARY);
    
    vector<vector<Point>> contours;
    vector< Vec4i > hierarchy;
    
    findContours(img__1, contours, hierarchy, RETR_TREE, CHAIN_APPROX_NONE);
    
    Mat tmp = Mat::zeros(img__1.size(), CV_8U);
    Mat tmp2 = Mat::zeros(img__1.size(), CV_8U);
    
    for (size_t i = 0; i < contours.size(); i++)
        if (hierarchy[i][3]<0)
            drawContours(tmp, contours, i, Scalar(255, 255, 255), -1); # first mask
    
    for (size_t i = 0; i < contours.size(); i++)
        if (hierarchy[i][2]<0 && hierarchy[i][3]>-1)
            drawContours(tmp2, contours, i, Scalar(255, 255, 255), -1); # second mask
    
    imshow("img", img__1);
    imshow("first_mask", tmp);
    imshow("second_mask", tmp2);
    
    tmp = tmp - tmp2;  # subtracting the two masks to remove the holes
    
    imshow("final image", tmp);
    waitKey(0);