Saturday, July 5, 2014

Point in Polygon Algorithm


In computational geometry, the point-in-polygon (PIP) problem asks whether a given point in the plane lies inside, outside, or on the boundary of a polygon.

Thinking..





in this case, how to prove that (2,5) is inside the polygon and (7,5) is outside?

1st Approach
if we get minX , maxX , minY , maxY of the polygon. then we check if this point within this area or not.

minX = 1 , maxX = 5 
minY = 1 , maxY = 6 

(2,5)         1 < 2 <5 ?  and  1< 5 <6 ?  Inside 
(7,5)         1 < 7 <5 ?   and  1< 5 <6 ?  Outside 

 but if we have more than 4 vertices like the following shape, this check will fail. as some points will seem to be inside but  it is actually outside.


minX = 1 , maxX = 4 
minY = 0 , maxY = 5 

(2.9 , 1.2 )         1 < 2.9 <4 ?  and  0< 1.2 <5 ?  Inside 
(3.7 , 4 )            1 < 3.7 <4 ?   and  0< 4 <5 ?  Inside   X

so, this approach needs improvements with shapes with more than 4 vertices.

2nd approach called Ray Casting 
The easiest way to determine if the point is inside the complex polygon is  to test how many times a ray, starting from the point and going any fixed direction, intersects the polygon sides. The number of intersections is an even number if the point is outside, and it is odd if inside.

Here, we have a complex polygon with the point located in one of the holes inside (the red dot is the selected point :)


check this link for the source code point-in-polygon-and-ray-casting  
also, if you have any problems in the link check this link RayCasting C#Project .

Thanks to Alex :)

No comments:

Post a Comment