OpenCV: Is a given point within a contour?

edited August 2014 in Library Questions

I am using this OpenCV library: https://github.com/atduskgreg/opencv-processing

Is there a piece of code in this library, or a method I could use, that could allow me to find out if a given point, say a boid, was within a contour?

Since the contours found in the library's example sketch ("FindContours") are simply an array of points with lines drawn in between, I was figuring there would be a way to determine this.

I could imagine a bounding box but an irregular shape has proven to be more difficult.

Tagged:

Answers

  • Found out this little nugget today from this discussion on StackOverflow. Apparently you cast a ray from the object and detect how many times it crosses a contour. If it is odd it is inside, if it is even it is outside.

    "Easiest way to do it is cast a ray from that point and count how many times it crosses the boundary. If it is odd, the point is inside, even the point is outside. Note that this only works for manifold shapes."

    http://stackoverflow.com/questions/6486499/determine-if-a-point-sits-inside-an-arbitrary-shape

    http://en.wikipedia.org/wiki/Point_in_polygon

  • I found out two methods that work great!

    1) Check the image, pg, at every pixel to see what color it is. It reads the color of the pixel at each point and checks if it is equal to a desired value, then does something. Something like

    if (pg.get(int(location.x), int(location.y)) == color(255)) { // do something }

    This is great if you are using a binary image like after most threshold operations.

    2) Use the official OpenCV method "pointPolygonTest()" listed here: https://gist.github.com/atduskgreg/d0b5b3f10f027062d80e

    This also works great. It casts a ray and checks how many times this forward facing ray crosses a path. An odd number and it is inside, and even number if it is outside, pretty great process. This method proved to be a little slow however. I suggest testing both.

Sign In or Register to comment.