How to check if point is placed inside contour? [closed]

≡放荡痞女 提交于 2019-12-02 21:25:14

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:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!