有什么办法可以找到轮廓之间的距离?

时间:2019-11-17 01:25:10

标签: python opencv distance contour

我通过python(opencv)获得了二进制图像,并尝试如下查找每个轮廓之间的距离。 对于此示例,

Binary image

我会尝试像这样测量每条线的每个轮廓距离:

red arrow loop to get distance

有什么方法可以捕捉每个轮廓点并获得我标记为红色箭头的距离,并延伸到每条线(第1,第2 ..... nth)

我试图用for循环捕捉每个点,但是我不知道如何像这样自动测量距离(第1 <-> 2nd,2nd <---> 3rd,。。。。。。nth -1 <-> nth)

1 个答案:

答案 0 :(得分:1)

如果期望的输入始终是条纹图案,则可以逐行循环遍历像素。如果一个像素与以前的像素不同,请注意相等的像素数。

我创建了一个示例,其中使用了原始图像的一小部分-为清楚起见。

输入:

enter image description here

结果:

  

[[6,10,8,10,8,8],
    [6,10,8,10,8,8],
    [6,10,8,10,8,8],
    [7,9,8,10,8,8],
    [7、9、8、10、8、8]]

代码:

import cv2
# load image as grayscale
img = cv2.imread('YDsdI.png',0)
# create small subimage
subimg = img[100:105,95:150]
# create empty list
all_distances = []
# loop all lines, then each pixel
# if the current pixel differs from the previous,
# then append the number of pixel that where equal
for line in subimg:
    start = 0
    line_distances = []

    for i in range(1,len(line)):
        if line[i] != line[i-1]:
            line_distances.append(i-start)
            start = i
    all_distances.append(line_distances)
# print result
print(all_distances)
# draw gray rectangle around the smaller subimage
cv2.rectangle(img,(95,100),(150,105),(127),2)
# show image
cv2.imshow('Img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()