如何使用Matplotlib从轮廓转到图像蒙版

时间:2013-06-07 02:46:16

标签: python matplotlib plot mask contour

如果我绘制一个2D数组并对其进行轮廓绘制,我可以通过cs = plt.contour(...); cs.allsegs访问分割图,但它被参数化为一条线。我想要一个行内部内容的segmap布尔掩码,所以我可以快速地对该轮廓内的所有内容求和。

非常感谢!

2 个答案:

答案 0 :(得分:6)

我不认为有一种非常简单的方法,主要是因为你想混合光栅和矢量数据。幸运的是,Matplotlib路径有一种方法可以检查一个点是否在路径中,对所有像素执行此操作都会生成一个掩码,但我认为这种方法对于大型数据集来说可能会非常慢。

import matplotlib.patches as patches
from matplotlib.nxutils import points_inside_poly
import matplotlib.pyplot as plt
import numpy as np

# generate some data
X, Y = np.meshgrid(np.arange(-3.0, 3.0, 0.025), np.arange(-3.0, 3.0, 0.025))
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

fig, axs = plt.subplots(1,2, figsize=(12,6), subplot_kw={'xticks': [], 'yticks': [], 'frameon': False})

# create a normal contour plot
axs[0].set_title('Standard contour plot')
im = axs[0].imshow(Z, cmap=plt.cm.Greys_r)
cs = axs[0].contour(Z, np.arange(-3, 4, .5), linewidths=2, colors='red', linestyles='solid')

# get the path from 1 of the contour lines
verts = cs.collections[7].get_paths()[0]

# highlight the selected contour with yellow
axs[0].add_patch(patches.PathPatch(verts, facecolor='none', ec='yellow', lw=2, zorder=50))

# make a mask from it with the dimensions of Z
mask = verts.contains_points(list(np.ndindex(Z.shape)))
mask = mask.reshape(Z.shape).T

axs[1].set_title('Mask of everything within one contour line')
axs[1].imshow(mask, cmap=plt.cm.Greys_r, interpolation='none')

# get the sum of everything within the contour
# the mask is inverted because everything within the contour should not be masked
print np.ma.MaskedArray(Z, mask=~mask).sum()

请注意,默认情况下,在不同边缘“留下”绘图的轮廓线不会形成跟随这些边缘的路径。这些行需要一些额外的处理。

enter image description here

答案 1 :(得分:2)

另一种方式,也许更直观,是来自scipy.ndimage的{​​{3}}函数。

import numpy as np
import scipy


image = np.zeros((512, 512))
image[contour1[:, 0], contour1[:, 1]] = 1
masked_image = scipy.ndimage.morphology.binary_fill_holes(image)
```