将触摸物体的轮廓查找为两个不同的轮廓
Find contours of touching objects as two distinct contours
我想知道如何使用 Python
中的 cv2.findContours 将相互连接的对象计为两个不同的对象
例如这张图片:
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
将输出一个轮廓。
我该怎么做才能得到两个轮廓?
这可以通过将输入图像转换为边缘图像然后检测轮廓来完成。但是在这种情况下,在两个对象的交叉处边缘图像(我尝试使用 canny)出现中断,如下所示。
精明的突破:
而预期的边缘图像应使边界处的所有像素为白色。
期望的边缘图像:
为了得到这个完美的边缘图像,我创建了一个算法,如下所示(此算法仅适用于像这样的二值图像,其中对象填充为白色)。
在使用该算法之前,请确保对象不在边界上,即图像的所有边界像素都应为黑色。如果不是黑色,则在黑色图像的四周添加一个边框,长度为 1 像素。
# Creating black image of same shape and single channel
edge = np.zeros(img.shape, dtype = np.uint8)
h, w = img.shape[:2]
# Iterating over each pixel except those at the boundary
for i in range(1, h-1):
for j in range(1, w-1):
# if current pixel is white
if img[i][j] == 255:
# roi is the image of 9 pixel from around the current pixel
roi = img[i-1:i+2, j-1:j+2].copy()
# Counting number of black pixel in the neighbourhood of current pixel
blackCount = np.sum(roi == 0)
# if a neighbouring pixel is black, then current pixel is a boundary pixel.
if blackCount > 0:
edge[i][j] = 255
找到边缘图像后,得到图像中的所有轮廓:
cont, hier = cv2.findContours(edge, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
对于此图像,您将获得 3 个轮廓,2 个用于两个对象,1 个用于两个对象的组合。要消除组合的两个对象的轮廓,请使用层次结构信息。
# I am taking only those contours which do not have a child contour.
finalContours = np.asarray([cont[i] for i in range(len(cont)) if hier[0][i][2] == -1])
“finalContours”将具有两个对象的 2 个轮廓。
Refer to this link for more information about the parent-child relationship of the contours
我想知道如何使用 Python
中的 cv2.findContours 将相互连接的对象计为两个不同的对象例如这张图片:
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
将输出一个轮廓。 我该怎么做才能得到两个轮廓?
这可以通过将输入图像转换为边缘图像然后检测轮廓来完成。但是在这种情况下,在两个对象的交叉处边缘图像(我尝试使用 canny)出现中断,如下所示。
精明的突破:
而预期的边缘图像应使边界处的所有像素为白色。
期望的边缘图像:
为了得到这个完美的边缘图像,我创建了一个算法,如下所示(此算法仅适用于像这样的二值图像,其中对象填充为白色)。
在使用该算法之前,请确保对象不在边界上,即图像的所有边界像素都应为黑色。如果不是黑色,则在黑色图像的四周添加一个边框,长度为 1 像素。
# Creating black image of same shape and single channel
edge = np.zeros(img.shape, dtype = np.uint8)
h, w = img.shape[:2]
# Iterating over each pixel except those at the boundary
for i in range(1, h-1):
for j in range(1, w-1):
# if current pixel is white
if img[i][j] == 255:
# roi is the image of 9 pixel from around the current pixel
roi = img[i-1:i+2, j-1:j+2].copy()
# Counting number of black pixel in the neighbourhood of current pixel
blackCount = np.sum(roi == 0)
# if a neighbouring pixel is black, then current pixel is a boundary pixel.
if blackCount > 0:
edge[i][j] = 255
找到边缘图像后,得到图像中的所有轮廓:
cont, hier = cv2.findContours(edge, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
对于此图像,您将获得 3 个轮廓,2 个用于两个对象,1 个用于两个对象的组合。要消除组合的两个对象的轮廓,请使用层次结构信息。
# I am taking only those contours which do not have a child contour.
finalContours = np.asarray([cont[i] for i in range(len(cont)) if hier[0][i][2] == -1])
“finalContours”将具有两个对象的 2 个轮廓。
Refer to this link for more information about the parent-child relationship of the contours