如何获得带孔的二进制掩码的边界坐标?

How to obtain boundary coordinates of binary mask with holes?

我有以下图片:

我想获得一个列表,其中包含每个 blob 的外轮廓和​​内轮廓的 (x, y) 坐标(我们称它们为 blob A 和 B)。

import cv2
from skimage import measure

blob = cv2.imread('blob.png', 0)
contours, hier = cv2.findContours(blob, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
labels = measure.label(blob)
props = measure.regionprops(labels)

for ii in range(0,len(props))
xy = props[ii].coords

plt.figure(figsize=(18, 16))
plt.imshow(blob, cmap='gray')
plt.plot(xy[:, 0], xy[:,1])
plt.show()

所需的输出图像,其中蓝色和红色取自 (x, y) 坐标列表 A 和 B:

您直接从 cv2.findContours 获得 (x, y) 坐标。要识别单个 blob,请查看层次结构 hier。第四个索引告诉您,可能的内部(或子)轮廓与哪个外部(或父)轮廓相关。大多数外部轮廓的索引为 -1,所有其他轮廓都具有非负值。因此,对于 plotting/drawing,一个天真的方法是,在迭代轮廓时,每次看到 -1 时增加一个 blob 计数器,并用相同的颜色绘制所有轮廓,直到下一个 [=14] =] 显示。

import cv2
from skimage import io         # Only needed for web grabbing images, use cv2.imread for local images

# Read image; find contours with hierarchy
blob = io.imread('https://i.stack.imgur.com/Ga5Pe.png')
contours, hier = cv2.findContours(blob, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Define sufficient enough colors for blobs
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]

# Draw all contours, and their children, with different colors
out = cv2.cvtColor(blob, cv2.COLOR_GRAY2BGR)
k = -1
for i, cnt in enumerate(contours):
    if (hier[0, i, 3] == -1):
        k += 1
    cv2.drawContours(out, [cnt], -1, colors[k], 2)

cv2.imshow('out', out)
cv2.waitKey(0)
cv2.destroyAllWindows()

当然,可以使用 NumPy 优化获取属于同一 blob 的所有轮廓,但循环在这里感觉最直观。我省略了所有其他内容(skimage、Matplotlib),因为它们在这里似乎不相关。正如我所说,(x, y) 坐标已经存储在 contours.

希望对您有所帮助!


编辑: 我还没有验证,如果 OpenCV 总是连续获取属于一个最外层轮廓的所有轮廓,或者如果 - 例如 - 给定层次结构级别的所有轮廓随后被存储。因此,对于更复杂的层次结构,应该事先进行测试,或者应该从一开始就使用提到的使用 NumPy 查找索引。