1. 程式人生 > >Point in polygon(判斷一個點是否落在多邊形內)

Point in polygon(判斷一個點是否落在多邊形內)

 

專案中遇到一個問題,判斷一個點是否位於一個多邊形內,查看了google,知道維基百科,發現這已經是一個很古老的問題了,被稱為PNP問題。這一篇記錄一下原理。

An early description of the problem in computer graphics shows two common approaches (ray casting and angle summation) in use as early as 1974.[1]

Ray casting algorithm[edit]

The number of intersections for a ray passing from the exterior of the polygon to any point; if odd, it shows that the point lies inside the polygon. If it is even, the point lies outside the polygon; this test also works in three dimensions.

One simple way of finding whether the point is inside or outside a simple polygon is to test how many times a ray, starting from the point and going in any fixed direction, intersects the edges of the polygon. If the point is on the outside of the polygon the ray will intersect its edge an 

even number of times. If the point is on the inside of the polygon then it will intersect the edge an odd number of times. This method won't work if the point is on the edge of the polygon.

對要判斷的點向任意方向做射線,如果這條射線與多邊形的交點是奇數,則表明這個點位於多邊形內,是偶數,則表明這個點位於多邊形外。這個方法並不適用於點位於多邊形邊上的情況。

This algorithm is sometimes also known as the crossing number algorithm or the even–odd rule algorithm, and is known as early as 1962.[3] The algorithm is based on a simple observation that if a point moves along a ray from infinity to the probe point and if it crosses the boundary of a polygon, possibly several times, then it alternately goes from the outside to inside, then from the inside to the outside, etc. As a result, after every two "border crossings" the moving point goes outside. This observation may be mathematically proved using the Jordan curve theorem.

這個演算法1962年便被提出來了,數學證明被稱為Jordan curve theorem,喬丹曲線定理,這篇帖子看了好幾遍,還是沒有看懂,過於專業了,百度這裡也有一些講解,還是沒有看懂,所以還是暫時先放一放。

If implemented on a computer with finite precision arithmetics, the results may be incorrect if the point lies very close to that boundary, because of rounding errors. This is not normally a concern, as speed is much more important than complete accuracy in most applications of computer graphics. However, for a formally correct computer program, one would have to introduce a numerical tolerance ε and test in line whether P (the point) lies within ε of L (the Line), in which case the algorithm should stop and report "P lies very close to the boundary."

這段說的是,如果計算機是有限精度(基本上大多數計算機都是這樣),如果這個點非常靠近邊緣的話,那麼結果可能並不準確,因為會有四捨五入的情況。這一點其實並不是非常重要,因為完全的精確可能並不比計算速度來的重要。當然,也有一些對此的處理辦法(暫時先不解釋)。

參考

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