繁体   English   中英

如何使用 go 从轮廓到图像掩码 Matplotlib

[英]How to go from a contour to an image mask in with Matplotlib

如果我 plot 是一个 2D 数组并勾勒出它的轮廓,我可以通过cs = plt.contour(...); cs.allsegs cs = plt.contour(...); cs.allsegs但它被参数化为一条线。 我想要一个线段内部的 segmap boolean 掩码,这样我就可以快速总结该轮廓内的所有内容。

非常感谢!

我不认为有一种非常简单的方法,主要是因为你想混合光栅和矢量数据。 幸运的是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()

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

在此输入图像描述

另一种方式,也许更直观,是来自scipy.ndimagebinary_fill_holes函数。

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

以下是如何从轮廓创建填充多边形并使用 OpenCV 创建二进制掩码

import cv2
import numpy as np
import matplotlib.pyplot as plt

mask = np.zeros((10,10,3), dtype=np.uint8)
# polygon's coordinates
coords = np.array([[3,3],[3,6],[6,6],[6,3]])

cv2.drawContours(mask, [coords], contourIdx=-1, color=(1,1,1), thickness=-1)
bin_mask = mask[:,:,0].astype(np.float32)
plt.imshow(bin_mask, cmap='gray')
  • contourIdx=-1 - 绘制所有轮廓

  • color=(1,1,1) - 每个通道的 0 到 255 之间的数字; 因为我们生成了一个二进制掩码,所以它被设置为 1

  • thickness=-1 - 填充多边形

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM