首页 > 解决方案 > 来自两条分割曲线的二进制掩码

问题描述

两条分割曲线作为一维 numpy 数组存储在 r2(图像中的底线)和 r1(图像中的上行线)中。我正在尝试创建一个二进制掩码;除了那两条曲线内的区域外,到处都是黑色:白色。到目前为止,我已经尝试了以下代码,它适用于线条,但不适用于基于另一个 stackoverflow 答案的曲线:

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

段 2 和段 1

标签: python

解决方案


从两条曲线的点创建一个多边形,然后用它来填充一个白色区域。如果我们将曲线视为一组 X 值,然后是两组不同的 Y 值,我们应该执行以下操作:

from matplotlib.patches import Polygon

X = ...
Y1, Y2 = ...
points = list(zip(X, Y1)) + list(reversed(zip(X, Y2)))
polygon = Polygon(points)

# Now fill the polygon with one color, and everything else with a different color

在此处查看有关 matplotlib 中排水多边形的更多信息


推荐阅读