OpenCV Python ŌĆō How to find the shortest distance between a point in the image and a contour?
When working with images, it is common to need to identify the distance between a point in the image and a contour. In OpenCV Python, this can be accomplished using several methods.
The first step is to load the image and the contour data. For this example, we will be using the following code:
import cv2
import numpy as np
# Load image
img = cv2.imread('image.jpg')
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find edges
edges = cv2.Canny(gray, 50, 150)
# Find contours
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
This code loads the image and converts it to grayscale. It then finds the edges of the image using Canny edge detection and identifies the contours using the cv2.findContours()
method.
Once we have the contour data for the image, we can identify the shortest distance between a point and the contour. The following code demonstrates one method of accomplishing this:
# Pick a point in the image
point = (100, 100)
# Find distance to closest point on contour
dist = cv2.pointPolygonTest(contours[0], point, True)
# Print distance
print(dist)
In this code, we have chosen a point at (100, 100) in the image. We then use the cv2.pointPolygonTest()
method to find the distance between this point and the closest point on the contour. The True
argument in this method indicates that we want the signed distance, meaning the distance will be negative if the point is inside the contour.
Another method for finding the shortest distance between a point and a contour is to use the Euclidean distance formula. The following code demonstrates this method:
# Find shortest distance using Euclidean distance formula
min_distance = None
# Loop over points on contour
for c in contours[0]:
dist = np.linalg.norm(np.array(c) - np.array(point))
if min_distance is None or dist < min_distance:
min_distance = dist
# Print shortest distance
print(min_distance)
In this code, we loop over each point on the contour and calculate the distance to the chosen point using the Euclidean distance formula. We then keep track of the minimum distance found and print this value.
It is important to note that these methods will only give accurate results if the chosen point is near the contour. If the point is far away from the contour, the distance calculated may not be meaningful.
Conclusion
In summary, finding the shortest distance between a point in an image and a contour can be accomplished using several methods in OpenCV Python. The cv2.pointPolygonTest()
method can be used to find the distance to the closest point on the contour, while the Euclidean distance formula can be used to find the shortest distance overall. Care should be taken to ensure that the chosen point is near the contour for accurate results.