2016-09-22 76 views
1

我有一個圖像,我發現與skimage.measure.find_contours()輪廓,但現在我想創建一個完全在最大的封閉輪廓外面的像素蒙版。任何想法如何做到這一點?從skimage輪廓創建蒙版

修改文檔中的例子:

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

如何創建相同的尺寸與原始的圖像與像素掩蔽完全外(即,不是由輪廓線交叉)?例如。

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

謝謝!

回答

1

好吧,我是能夠由輪廓轉換爲路徑,然後選擇裏面的像素,以使這項工作:

# 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]像素遏制。任何人都有更快的算法?謝謝!