Search code examples
pythonnumpymask

Create binary mask from two segmentation lines in Python


I have two segmentation lines stored in variables seg1 (bottom line in image) and seg2 (upper line in image) as 1-d numpy arrays. I'm trying to create an image where is black everywhere except the region inside those two lines -> white. What I am doing is the following which does not work:

binaryim = np.zeros_like(im)
for col in range(0, im.shape[1]):
    for row in range(0, im.shape[0]):
        if row < seg1[col] or row > seg2[col]: 
            binaryim[row][col] = 0
        else:
            binaryim[row][col] = 255

Any ideas? Everything inside those lines should be one and everything outside should be zero.

Seg2 and seg1


Solution

  • The simplest answer I could think of and it works was the following: Given im the image, curve1, curve2 the curves:

    rows, cols = np.indices(im.shape)
    mask0=(rows < curve1) & (rows > curve2)
    plt.gca().invert_yaxis()
    plt.imshow(mask0,origin='lower',cmap='gray')
    ax = plt.gca()
    ax.set_ylim(ax.get_ylim()[::-1])
    plt.show()