在图像python中查找给定点和轮廓边缘之间的距离

问题描述

我正在尝试找到图像中给定点的最近轮廓边缘。使用Canny边缘检测确定边缘。

enter image description here

上图是显示边缘的图像,红点是用户指定的点(右上角)。

我遍历所有可能的轮廓边缘,以找到边缘与坐标为(t1,x1)的给定点之间的最短距离。然后找到该点到所有边缘的距离,然后找到距离该点最短的边缘。

for i in range(0,num_contours):
    cnt=contours[i]
    # find the distance of the chosen point from all the contours
    dist= cv2.pointpolygonTest(cnt,(t1,x1),True)
    dist_abs[i]=abs(dist)

# find the minimum value and its index from a list of values 
val,idx = min((val,idx) for (idx,val) in enumerate(dist_abs))

现在我们知道与给定点最近的边缘相对应的索引,然后我使用 以下代码确定最接近轮廓边缘的索引以对其进行绘制。我将最近的轮廓边的坐标保存在“ jj”和“ ii”向量中。

contour = contours[idx]
contour_lens = []
contour_len = contour.shape[0]
contour_lens.append(contour_len)

jj = [0] * contour_len
ii = [0] * contour_len 

for ilen in list(range(0,contour_len)):
    jj[ilen]=contour[ilen,1]
    ii[ilen]=contour[ilen,0]

使用上述逻辑,代码找到一条错误的边缘,即位于右下角的红线,而不是下图中给定点位于右上角的红线。

![edge_image2

解决方法

使用pointInPolygonTest似乎有些矫kill过正,并且有人想知道开放轮廓的有符号距离的含义是什么。也不需要存储所有距离值。

我将首先在边缘上然后在各个像素上使用双循环解决此问题,并通过计算欧几里德距离(避免使用无用的平方根求平方)来保持最接近的像素。