在二进制边缘图像中找到闭合循环的数量 [英] Find number of close loops in Binary Edge Image
本文介绍了在二进制边缘图像中找到闭合循环的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有闭环和自由曲线数量的二进制图像,如图所示.
I have a binary image with the number of close loops and free curves like shown in image..
到目前为止,我的方法-(python代码):
My approach so far- (python code):
- 骨骼化图像以获得1个像素的边缘
- 使用标签/bwlabel获取单个曲线/边缘
- 应用DFS获取未闭合的边缘
- 应用DFS以获得接近的边缘..但无法正常工作..
预期输出-
闭合循环数= 6,沿循环的像素总和或闭合曲线边缘上的所有(x,y)点,如 RED
Number of close loops =6, the sum of the pixels along the loop or all (x,y) points along the edge of the close curve as highlighted in RED
预期输出-
推荐答案
这是在Python/OpenCV中实现此目的的一种方法.
Here is one way to do that in Python/OpenCV.
- 将输入读取为灰度
- 二进制阈值
- 获取轮廓和层次
- 遍历轮廓和相应的层次结构,并丢弃没有父级的轮廓(外部的),并保存和计数没有子级的轮廓(最内部的)
- 在输入上绘制轮廓
- 保存结果
输入:
import cv2
import numpy as np
# read image as grayscale
img = cv2.imread('loops.png', cv2.IMREAD_GRAYSCALE)
hh, ww = img.shape
# blacken right columns that are white
img[0:hh, ww-3:ww] = 0
# threshold
thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)[1]
# get contours
contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = contours[1] if len(contours) == 2 else contours[2]
contours = contours[0] if len(contours) == 2 else contours[1]
# get the actual inner list of hierarchy descriptions
hierarchy = hierarchy[0]
# count inner contours
count = 0
result = img.copy()
result = cv2.merge([result,result,result])
for component in zip(contours, hierarchy):
cntr = component[0]
hier = component[1]
# discard outermost no parent contours and keep innermost no child contours
# hier = indices for next, previous, child, parent
# no parent or no child indicated by negative values
if (hier[3] > -1) & (hier[2] < 0):
count = count + 1
cv2.drawContours(result, [cntr], 0, (0,0,255), 2)
# print count
print("count:",count)
# save result
cv2.imwrite("loops_result.png",result)
# show result
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
产生的轮廓:
Resulting contours:
计数:
count: 6
这篇关于在二进制边缘图像中找到闭合循环的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文