如何获取带孔二值掩模的边界坐标?

Chr*_*neP 3 python opencv contour

我有以下图像:

测试图像

我想获得一个列表,其中包含(x, y)每个斑点的外部和内部轮廓的坐标(我们称它们为斑点 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()
Run Code Online (Sandbox Code Playgroud)

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

所需输出

Han*_*rse 5

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

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()
Run Code Online (Sandbox Code Playgroud)

输出

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

希望有帮助!


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