【问题标题】:Point in polygon algorithm explanationPoint in polygon 算法解释
【发布时间】:2015-06-11 15:53:55
【问题描述】:

您好,我从Mathhelpforum 发现了这个算法,它确定一个点是在多边形内部还是外部。到目前为止,代码运行良好,但我不完全理解逻辑。如果您这样做,请提供解释,特别是方法...是否射线投射,或缠绕数等。谢谢。

function [ inside ] = inpoly(polygon,xt,yt)

rows = size(polygon);
npoints = rows(1);
disp (npoints);
inside = 0;

xold = polygon(npoints,1);
yold = polygon(npoints,2);

for i = 1:1:npoints

   xnew = polygon(i,1);
   ynew = polygon(i,2);

      if (xnew > xold) 
         x1=xold;
         x2=xnew;
         y1=yold;
         y2=ynew;
      else 
         x1=xnew;
         x2=xold;
         y1=ynew;
         y2=yold;
      end

      if ((xnew < xt) == (xt <= xold) & (yt-y1)*(x2-x1) < (y2-y1)*(xt-x1) ) 
               inside=~inside;
      end

      xold=xnew;
      yold=ynew;

end

endfunction

测试功能,例如:

inpoly([p,q],x,y)

其中 p 和 q 是多边形的顶点和点的 x、y 坐标。

【问题讨论】:

    标签: algorithm matlab polygon point


    【解决方案1】:

    对我来说似乎是射线投射。变量x1y1x2y2 是相对于 X 排序的多边形边的端点。条件 (xnew &lt; xt) == (xt &lt;= xold) 测试从点 xt,yt 开始的 Y 平行线是否与边相交。条件的另一部分测试xt,yt 是否在多边形一侧的正确一侧。

    条件

    (yt-y1)*(x2-x1) < (y2-y1)*(xt-x1)
    

    等价于

    (yt-y1)*(x2-x1) - (y2-y1)*(xt-x1) < 0
    

    这是一个矩阵行列式

    | yt-y1  xt-x1 |
    |              | < 0
    | y2-y1  x2-x1 |
    

    矩阵是向量叉积

    (pointT - point1) times (point2 - point1)
    

    【讨论】:

    • 谢谢@CiaPan,我现在清楚多了。这种光线投射的实现看起来相当简单。它在点位于多边形内时有效,但在点位于边或顶点时无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多