Create mask from skimage contour

有些话、适合烂在心里 提交于 2021-02-18 14:54:48

问题


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?

Modifying the example in the documentation:

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

Here is the contour in red:

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

Thanks!


回答1:


A bit late but you know the saying. Here is how I would accomplish this.

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




回答2:


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)

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




回答3:


If you're still looking for a faster way to achieve that, I would recommend using skimage.draw.polygon, I'm kind of new to this but it seems to be built in to do exactly what you are trying to accomplish:

import numpy as np
from skimage.draw import polygon

# fill polygon
poly = np.array((
    (300, 300),
    (480, 320),
    (380, 430),
    (220, 590),
    (300, 300),
))
rr, cc = polygon(poly[:, 0], poly[:, 1], img.shape)
img[rr, cc, 1] = 1

So in your case, a 'closed contour' is a 'poly', we are creating a blank image with the shape of your contours filled with the value 1:

mask = np.zeros(r.shape)
rr, cc = polygon(contour[:, 0], contour[:, 1], mask.shape)
mask[rr, cc] = 1

And now you can apply your mask to the original image to mask out everything outside the contours:

masked = ma.array(r.copy(), mask=mask)

Documented in scikit image - Shapes



来源:https://stackoverflow.com/questions/39642680/create-mask-from-skimage-contour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!