[Solved] Using opencv to find the shortest path for a set of 6 points on an image


cv::norm can be used to find distance between two points. I have taken 6 random points on a board of 200 x 200.

points

Now i have just looped over the rest of the points to find the smallest distance using cv::norm and then exchanged its index with the next point. My result is:

result

Sorry but the code is in python:

import cv2
import numpy as np

def find_nn(point, neighborhood):
"""
Finds the nearest neighborhood of a vector.

Args:
    point (float array): The initial point.
    neighborhood (numpy float matrix): The points that are around the initial point.

Returns:
    float array: The point that is the nearest neighbor of the initial point.
    integer: Index of the nearest neighbor inside the neighborhood list
"""
min_dist = float('inf')
nn = neighborhood[0]
nn_idx = 0
for i in range(len(neighborhood)):
    neighbor = neighborhood[i]
    dist = cv2.norm(point, neighbor, cv2.NORM_L2)
    if dist < min_dist:
        min_dist = dist
        nn = neighbor
        nn_idx = i
nn_idx = nn_idx + j + 1
return nn, nn_idx 

#taking 6 random points on a board of 200 x 200
points = [(10, 10), (115, 42), (36, 98), (78, 154), (167, 141), (189, 4)]
board = np.ones((200, 200, 3), dtype = np.uint8) * 255
for i in range(6):
    cv2.circle(board, points[i], 5, (0, 255, 255), -1)

for j in range(5):
    nn, nn_idx = find_nn(points[j], points[j+1:])
    points[j+1], points[nn_idx] = points[nn_idx], points[j+1]

for i in range(5):
    cv2.arrowedLine(board, points[i], points[i+1], (255, 0, 0), 1, tipLength = 0.07)
cv2.imshow('image', board)
cv2.waitKey(0)
cv2.destroyAllWindows()

1

solved Using opencv to find the shortest path for a set of 6 points on an image