6

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

非常感谢!

4

2 回答 2

7

我认为没有真正简单的方法,主要是因为您想混合栅格和矢量数据。幸运的是,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()

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

在此处输入图像描述

于 2013-06-07T10:30:31.213 回答
5

另一种可能更直观的方法是binary_fill_holes函数 from scipy.ndimage

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)
```
于 2018-01-15T10:23:41.820 回答