[英]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. 我有两条分割线以1-d numpy数组形式存储在变量seg1(图像中的底线)和seg2(图像中的上线)中。 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.
这些行内的所有内容均应为一,外部行中的所有内容应为零。
Use np.arange
to mask rows and cmap='gray'
to plot white and black: 使用
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')
To work on a pixel level, get the row and column indices from np.indices
: 要在像素级别上工作,请从
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: 我能想到的最简单的答案是行之有效的:给定即时影像,curve1,curve2为曲线:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.