python - Create mask from skimage contour -
i have image found contours on skimage.measure.find_contours()
want create mask pixels outside largest closed contour. idea how this?
modifying example in documentation:
import numpy np import matplotlib.pyplot plt skimage import measure # construct 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 @ constant value of 0.8 contours = measure.find_contours(r, 0.8) # select largest contiguous contour contour = sorted(contours, key=lambda x: len(x))[-1] # display image , plot 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 contour in red:
but if zoom in, notice contour not @ resolution of pixels.
how can create image of same dimensions original pixels outside (i.e. not crossed 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!
ok, able make work converting contour path , selecting pixels inside:
# convert contour closed path matplotlib import path closed_path = path.path(contour.t) # points lie within closed path idx = np.array([[(i,j) in range(r.shape[0])] j in range(r.shape[1])]).reshape(np.prod(r.shape),2) mask = closed_path.contains_points(idx).reshape(r.shape) # invert mask , apply image mask = np.invert(mask) masked_data = ma.array(r.copy(), mask=mask)
however, kind of slow testing n = r.shape[0]*r.shape[1]
pixels containment. have faster algorithm? thanks!
Comments
Post a Comment