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.
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). 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.
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. 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.