How to check if point is placed inside contour?

Question:

I have drawn a contour around extreme points. Inside polygon figure I have others points.
How to check if they are inside contour?

Asked By: OPV

||

Answers:

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

  1. 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
  2. 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

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:

enter image description here

I assumed the following points to be used as illustration:

(50, 70), (170, 152), (152, 48)

enter image description here

dist1 = cv2.pointPolygonTest(contours[0], (50, 70), True) #green 
dist2 = cv2.pointPolygonTest(contours[0], (170, 152), True) #blue
dist3 = cv2.pointPolygonTest(contours[0], (152, 48), True) #red

print('dist1 : ', dist1)
print('dist2 : ', dist2)
print('dist3 : ', dist3)

Output:

('dist1 : ', -45.17742799230607)
('dist2 : ', 49.9799959983992)
('dist3 : ', -0.0)
Answered By: Jeru Luke
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.