【发布时间】:2020-03-17 03:35:00
【问题描述】:
这是来自How to obtain boundary coordinates of binary mask with holes?的后续问题
给定相同的图像:
我想为(x, y)-外轮廓及其内轮廓的坐标的每个对象获取一个单独的列表。理想情况下,我想使用此列表在单独的空白画布上绘制对象(外轮廓和内轮廓)。
import matplotlib.pyplot as plt # For plotting
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)
# Check if it's the outer contour
k = -1
# Preallocate list
obj_list = []
for i, cnt in enumerate(contours):
if (hier[0, i, 3] == -1):
k += 1
# cv2.drawContours(out, [cnt], -1, colors[k], 2)
# Add contour list to object list if it is an inner contour
obj_list.extend([cnt])
# Concatenate array in list
obj_list = np.vstack(obj_list)
obj_list = np.squeeze(obj_list)
x = obj_list[:,0].tolist()
y = obj_list[:,1].tolist()
cv2.imshow('out', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
编辑: 接受的答案仅适用于具有内部轮廓的对象,但不适用于没有内部轮廓的对象。我尝试通过添加以下代码来修复它:
# Add inner contours of blob to list
cnt_idx = np.squeeze(np.where(hier[0, :, 3] == b_idx))
c_cnt_idx = np.array(cnt_idx)
if c_cnt_idx.size > 0:
cnt_idx = b_idx
但我收到以下错误消息:
ValueError:未启用零大小操作数的迭代
【问题讨论】:
-
我不清楚与您之前提出的问题相比有什么不同?
-
你当前的输出是什么,预期的输出是什么?