问题
I have drawn a contour around extreme points. Inside polygon figure I have others points. How to check if they are inside contour?
回答1:
You can use the cv2.pointPolygonTest() function available in OpenCV.
For example:
dist = cv2.pointPolygonTest(cnt,(50,50),True)
In this example we are checking whether the coordinate (50, 50)
is present withing the contour cnt
dist
returns one of the following three:- Positive value if the point is inside the contour
- Negative value if the point is outside the contour
- Zero if the point is on the contour
Within the function
cv2.pointPolygonTest()
the third parameter decides whether you want one of the following two :- If it is True,
dist
returns either the positive or negative distance of the point, if it is either inside or outside the contour respectively. - On the other hand, if it is set to False, it returns +1, -1 or 0 depending on the point lying inside, outside or on the contour respectively
- If it is True,
See THE DOCS for more details
Illustration:
I added an example to show how it works. I considered the following image for which a contour was obtained:
I assumed the following points to be used as illustration:
(50, 70), (170, 152), (152, 48)
dist1 = cv2.pointPolygonTest(contours[0], (50, 70), True)
dist2 = cv2.pointPolygonTest(contours[0], (170, 152), True)
dist3 = cv2.pointPolygonTest(contours[0], (152, 48), True)
print('dist1 : ', dist1)
print('dist2 : ', dist2)
print('dist3 : ', dist3)
Output:
('dist1 : ', -45.17742799230607)
('dist2 : ', 49.9799959983992)
('dist3 : ', -0.0)
来源:https://stackoverflow.com/questions/50670326/how-to-check-if-point-is-placed-inside-contour