python - 从 skimage 轮廓创建蒙版

标签 python contour scikit-image masked-array

我有一张图像,我使用 skimage.measure.find_contours() 找到了轮廓,但现在我想为完全位于最大闭合轮廓之外的像素创建一个蒙版。知道怎么做吗?

修改文档中的例子:

import numpy as np
import matplotlib.pyplot as plt
from skimage import measure

# Construct some test data
x, y = np.ogrid[-np.pi:np.pi:100j, -np.pi:np.pi:100j]
r = np.sin(np.exp((np.sin(x)**2 + np.cos(y)**2)))

# Find contours at a constant value of 0.8
contours = measure.find_contours(r, 0.8)

# Select the largest contiguous contour
contour = sorted(contours, key=lambda x: len(x))[-1]

# Display the image and plot the contour
fig, ax = plt.subplots()
ax.imshow(r, interpolation='nearest', cmap=plt.cm.gray)
X, Y = ax.get_xlim(), ax.get_ylim()
ax.step(contour.T[1], contour.T[0], linewidth=2, c='r')
ax.set_xlim(X), ax.set_ylim(Y)
plt.show()

这是红色的轮廓:

enter image description here

但如果放大,请注意轮廓不是像素分辨率。

enter image description here

如何创建与原始图像尺寸相同且像素完全位于外部(即未与轮廓线交叉)被 mask 的图像?例如

from numpy import ma
masked_image = ma.array(r.copy(), mask=False)
masked_image.mask[pixels_outside_contour] = True

谢谢!

最佳答案

有点晚了,但你知道这句话。以下是我将如何实现这一目标。

import scipy.ndimage as ndimage    

# Create an empty image to store the masked array
r_mask = np.zeros_like(r, dtype='bool')

# Create a contour image by using the contour coordinates rounded to their nearest integer value
r_mask[np.round(contour[:, 0]).astype('int'), np.round(contour[:, 1]).astype('int')] = 1

# Fill in the hole created by the contour boundary
r_mask = ndimage.binary_fill_holes(r_mask)

# Invert the mask since you want pixels outside of the region
r_mask = ~r_mask

enter image description here

关于python - 从 skimage 轮廓创建蒙版,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39642680/

相关文章:

python - 使用 gfortran 支持为 Lion Python 2.6 构建 numpy

python - 如何使用分段仿射变换拉直弯曲的文本线/轮廓?

python - 在 qt 应用程序中显示 skimage 输出

plot - 在 Julia 中使用带有插值函数的 gr() 绘制等高线图

python-3.x - 为 Scikit-image 构建自定义 AWS Lambda 层

Python 3.6.0 隐式命名空间包

python - 在虚拟环境中运行 Spyder 最简单的方法是什么?

python - Pytorch 嵌入 RuntimeError : Expected object of type torch. LongTensor 但发现参数类型 torch.cuda.LongTensor #3 'index'

python - 将轮廓转换为 BLOB OpenCV

python - python 等高线图中缺少级别