引用
原帖收藏于IT老兵驿站。
前言
项目中遇到一个问题,判断一个点是否位于一个多边形内,查看了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
本文地址:https://blog.csdn.net/chaiyu2002/article/details/85914630