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

<p>Modifying the example in the documentation: </p>

<pre><code>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()
</code></pre>

<p>Here is the contour in red:</p>

<p><a href="http://i.stack.imgur.com/O2Ldt.png" rel="nofollow"><img src="http://i.stack.imgur.com/O2Ldt.png" alt="enter image description here"></a></p>

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

<p><a href="http://i.stack.imgur.com/o1IYn.png" rel="nofollow"><img src="http://i.stack.imgur.com/o1IYn.png" alt="enter image description here"></a></p>

<p>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.</p>

<pre><code>from numpy import ma
masked_image = ma.array(r.copy(), mask=False)
masked_image.mask[pixels_outside_contour] = True
</code></pre>

<p>Thanks!</p>

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

<pre><code># 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)
</code></pre>

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

python contour skimage masked-array