Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
OpenCV Python – How to find the shortest distance between a point in the image and a contour?
In OpenCV, we can compute the shortest distance between a point and a contour using cv2.pointPolygonTest(). This function takes contour coordinates and a point coordinate as arguments and returns the shortest Euclidean distance between them.
Syntax
distance = cv2.pointPolygonTest(contour, point, measureDist)
Parameters
contour ? The input contour
point ? The point coordinates as a tuple (x, y)
measureDist ? If True, returns actual distance. If False, returns +1, 0, or -1
Return Value
Positive ? Point is inside the contour
Negative ? Point is outside the contour
Zero ? Point lies on the contour boundary
StepbyStep Process
Read the input image using cv2.imread()
Convert the image to grayscale using cv2.cvtColor()
Apply thresholding to create a binary image
Find contours using cv2.findContours()
Use cv2.pointPolygonTest() to calculate the distance
Example 1: Single Contour with Two Points
In this example, we test two points against a single contour to see their relative positions ?
import cv2
import numpy as np
# Create a sample image with a shape
img = np.zeros((400, 500, 3), dtype=np.uint8)
cv2.rectangle(img, (150, 100), (350, 300), (255, 255, 255), -1)
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find contours
contours, hierarchy = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
# Test two points
point1 = (250, 200) # Inside the rectangle
point2 = (400, 200) # Outside the rectangle
# Calculate distances
dist1 = cv2.pointPolygonTest(cnt, point1, True)
dist2 = cv2.pointPolygonTest(cnt, point2, True)
print(f'Distance from point {point1}: {dist1:.2f}')
print(f'Distance from point {point2}: {dist2:.2f}')
# Visualize
cv2.drawContours(img, [cnt], -1, (0, 255, 255), 2)
cv2.circle(img, point1, 5, (0, 255, 0), -1)
cv2.circle(img, point2, 5, (0, 0, 255), -1)
cv2.putText(img, 'Inside', (point1[0]+10, point1[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
cv2.putText(img, 'Outside', (point2[0]+10, point2[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
cv2.imshow('Point-Contour Distance', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Distance from point (250, 200): 50.00 Distance from point (400, 200): -50.00
Example 2: Multiple Contours Distance Comparison
This example demonstrates finding the closest contour to a given point ?
import cv2
import numpy as np
# Create image with multiple shapes
img = np.zeros((400, 600, 3), dtype=np.uint8)
# Draw three different shapes
cv2.circle(img, (150, 200), 50, (255, 255, 255), -1)
cv2.rectangle(img, (250, 150), (350, 250), (255, 255, 255), -1)
cv2.circle(img, (450, 200), 60, (255, 255, 255), -1)
# Convert to grayscale and find contours
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Test point
test_point = (300, 300)
print(f"Number of contours detected: {len(contours)}")
print(f"Testing point: {test_point}")
# Find distances to all contours
distances = []
for i, cnt in enumerate(contours):
dist = cv2.pointPolygonTest(cnt, test_point, True)
distances.append(abs(dist))
print(f'Distance to contour {i+1}: {dist:.2f}')
# Find closest contour
closest_idx = distances.index(min(distances))
print(f'Closest contour: {closest_idx + 1}')
# Visualize results
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
for i, cnt in enumerate(contours):
cv2.drawContours(img, [cnt], -1, colors[i], 2)
# Highlight closest contour
cv2.drawContours(img, [contours[closest_idx]], -1, (255, 255, 255), 3)
cv2.circle(img, test_point, 5, (255, 255, 0), -1)
cv2.putText(img, 'Test Point', (test_point[0]+10, test_point[1]),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
cv2.imshow('Multiple Contours Distance', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Number of contours detected: 3 Testing point: (300, 300) Distance to contour 1: -111.80 Distance to contour 2: -70.71 Distance to contour 3: -141.42 Closest contour: 2
Distance Interpretation
| Distance Value | Point Location | Meaning |
|---|---|---|
| Positive (+) | Inside contour | Distance from center to boundary |
| Negative () | Outside contour | Distance from point to nearest boundary |
| Zero (0) | On boundary | Point lies exactly on contour edge |
Common Use Cases
Object proximity detection ? Check if points are near specific objects
Collision detection ? Determine if moving objects intersect boundaries
Region analysis ? Find the closest contour to a given location
Quality control ? Measure distances from defects to object boundaries
Conclusion
The cv2.pointPolygonTest() function is essential for measuring distances between points and contours in computer vision applications. Positive values indicate points inside contours, negative values indicate points outside, and zero means the point lies on the boundary.
