Search code examples
python-3.xmaskscikit-imageopencvpython

Create mask or boundary from each other in Python3


I would like to get the mask from images with boundaries or boundaries from images of masks.

Here are two images:

Mask Image Boundary Image

I went through the followings, I did not understand the logic there: link1, link2, link3, link4

thanks, ilyas


Solution

  • I still do not understand the logic, however, one can create boundary from mask and mask from boundary.

    import os
    import numpy as np
    import cv2
    from matplotlib import pyplot as plt
    
    out = "mask_boundary.png"
    inp = "mask.png"
    im = cv2.imread(inp)
    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(imgray,127,255,0)
    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    tmp = np.zeros_like(im)
    boundary = cv2.drawContours(tmp, contours, -1, (255,255,255), 1)
    plt.imsave(out, boundary, cmap = "gray")
    
    
    out = "boundary_mask.png"
    inp = "mask_boundary.png"
    im = cv2.imread(inp)
    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(imgray,0,255,0)
    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    tmp = np.zeros_like(im)
    boundary = cv2.drawContours(tmp, contours, 0,(255,255,255), -1)
    for i in range(1,len(contours)):
        boundary = cv2.drawContours(boundary, contours, i,(255,255,255), -1)
    
    plt.imsave(out, boundary, cmap = "gray")
    
    
    
    out = "boun_mask.png"
    inp = "boundary.png"
    im = cv2.imread(inp)
    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(imgray,0,255,0)
    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    tmp = np.zeros_like(im)
    boundary = cv2.drawContours(tmp, contours, 0,(255,255,255), -1)
    for i in range(1,len(contours)):
        boundary = cv2.drawContours(boundary, contours, i,(255,255,255), -1)
    
    plt.imsave(out, boundary, cmap = "gray")
    

    Note: using the mask image above, I first created boundary and then from this boundary I created mask. However, I could not convert all boundary above to mask, especially the one at the image edges/border. It looks like there must be boundary at the border as well! Any help on that will be appreciated!

    convert the above mask to boundary:

    mask2boundary

    now convert the new boundary to mask:

    newboundary2mask

    now convert the above boundary to mask:

    enter image description here