[英]finding distance between a given point and a contour edge in an image python
I am trying to find the nearest contour edge to a given point in an image.我试图找到图像中给定点的最近轮廓边缘。 The edge was determined using the canny edge detection.使用canny边缘检测确定边缘。
The above figure is the image showing the edges and the red dot is the user given point (top right corner).上图是显示边缘的图像,红点是用户给定的点(右上角)。
I go over all the possible contour edges to find the shortest distance between the edge and a given point with the coordinates (t1,x1).我遍历所有可能的轮廓边缘以找到边缘与坐标(t1,x1)的给定点之间的最短距离。 Then find the distance of the point from all the edges and then find the edge that has the shortest distance from the point.然后找到该点与所有边的距离,然后找到与该点距离最短的边。
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))
Now we know the index corresponding to the nearest edge to a given point and then I use the following code to determine the indices of the nearest contour edge to plot it.现在我们知道与给定点最近的边缘对应的索引,然后我使用以下代码来确定最近的轮廓边缘的索引来绘制它。 I save the coordinates of the nearest contour edge in "jj" and "ii" vectors.我将最近的轮廓边缘的坐标保存在“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,0,1]
ii[ilen]=contour[ilen,0,0]
Using the above logic, the code finds an incorrect edge ie the red line located in the bottom right corner instead of top right where the given point is located in the image below.使用上述逻辑,代码找到了不正确的边缘,即位于右下角的红线,而不是下图中给定点所在的右上角。
Using the pointInPolygonTest seems overkill, and one wonders what is the meaning of a signed distance for an open contour.使用 pointInPolygonTest 似乎有点矫枉过正,有人想知道开放轮廓的带符号距离的含义是什么。 There is also no need to store all distance values.也不需要存储所有距离值。
I would solve this with a double loop, on the edges first, then on the individual pixels, and keep the closest pixel by computing the Euclidean distance (squared to avoid a useless square root).我会用双循环解决这个问题,首先在边缘上,然后在单个像素上,并通过计算欧几里德距离(平方以避免无用的平方根)来保持最近的像素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.