从 Python 中的两条分割线创建二进制掩码

Create binary mask from two segmentation lines in Python

我有两条分割线作为一维 numpy 数组存储在变量 seg1(图像中的底线)和 seg2(图像中的上线)中。我正在尝试创建一个图像,其中除了那两条线内的区域 -> 白色外,其他地方都是黑色的。我正在做的是以下不起作用:

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

有什么想法吗?这些行内的所有内容都应为一,而外部的所有内容均应为零。

使用 np.arange 屏蔽行并使用 cmap='gray' 绘制白色和黑色:

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

要在像素级别上工作,请从 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')

我能想到的最简单的答案如下: 给定图像,曲线 1,曲线 2 曲线:

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