繁体   English   中英

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

[英]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()

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

期望的输出

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

输出

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

希望有帮助!


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

暂无
暂无

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

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