从skimage轮廓创建蒙版 [英] Create mask from skimage contour

查看:68
本文介绍了从skimage轮廓创建蒙版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一幅图像,该图像是通过 skimage.measure.find_contours()在其上找到轮廓的,但是现在我想为完全在最大闭合轮廓之外的像素创建一个遮罩.任何想法如何做到这一点?

I have an image that I found contours on with skimage.measure.find_contours() but now I want to create a mask for the pixels fully outside the largest closed contour. Any idea how to do this?

修改文档中的示例:

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

这是红色的轮廓:

但是,如果放大,请注意轮廓不在像素的分辨率上.

But if you zoom in, notice the contour is not at the resolution of the pixels.

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

How can I create an image of the same dimensions as the original with the pixels fully outside (i.e. not crossed by the contour line) masked? E.g.

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

谢谢!

推荐答案

好,我可以通过将轮廓转换为路径然后选择其中的像素来完成这项工作:

Ok, I was able to make this work by converting the contour to a path and then selecting the pixels inside:

# Convert the contour into a closed path
from matplotlib import path
closed_path = path.Path(contour.T)

# Get the points that lie within the closed path
idx = np.array([[(i,j) for i in range(r.shape[0])] for j in range(r.shape[1])]).reshape(np.prod(r.shape),2)
mask = closed_path.contains_points(idx).reshape(r.shape)

# Invert the mask and apply to the image
mask = np.invert(mask)
masked_data = ma.array(r.copy(), mask=mask)

但是,这是一种缓慢的测试,需要对 N = r.shape [0] * r.shape [1] 个像素进行遏制.有人有更快的算法吗?谢谢!

However, this is kind of slow testing N = r.shape[0]*r.shape[1] pixels for containment. Anyone have a faster algorithm? Thanks!

这篇关于从skimage轮廓创建蒙版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆