gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:01 25 4
gpt4 key购买 nike

我有以下图片:

test image

我想获得一个列表,其中包含 (x, y) - 每个 blob 的外部和内部轮廓的坐标(我们称它们为 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 中绘制的:

Desired output

最佳答案

您可以直接从 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('/image/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()

Output

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

希望对您有所帮助!


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

关于python - 如何获得带孔的二进制掩码的边界坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58885816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com