简体   繁体   中英

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和seg1

Use np.arange to mask rows and cmap='gray' to plot white and black:

import matplotlib.pyplot as plt
import numpy as np

im=np.zeros((100,100)) + 0
r1, r2 = 31,41

rows = np.arange(im.shape[0])
m1 = np.logical_and(rows > r1, rows < r2)
im[rows[m1], :] = 255
plt.imshow(im, cmap='gray')

在此处输入图片说明

To work on a pixel level, get the row and column indices from np.indices :

def line_func(col, s, e):
    return (s + (e - s) * col / im.shape[1]).astype(np.int)

r1, r2 = [20, 25], [30, 35]
rows, cols = np.indices(im.shape)
m1 = np.logical_and(rows > line_func(cols, *r1),
                    rows < line_func(cols, *r2))
im+= 255 * (m1)
plt.imshow(im, cmap='gray')

在此处输入图片说明

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM