pnpoly 判斷點是否在多邊形內部(c++)


遇到了一個問題,如何判斷一個點是否在一個多邊形內部。

主要有以下幾種方法:

(1)面積和判別法:判斷目標點與多邊形的每條邊組成的三角形面積和是否等於該多邊形,相等則在多邊形內部。

(2)夾角和判別法:判斷目標點與所有邊的夾角和是否為360度,為360度則在多邊形內部。

(3)引射線法:從目標點出發引一條射線,看這條射線和多邊形所有邊的交點數目。如果有奇數個交點,則說明在內部,如果有偶數個交點,則說明在外部。

 

簡潔的C++代碼如下:

int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) 
  {
    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
       c = !c;
  }
  return c;
}

 

Matlab驗證代碼:

clc;
close;


%% poly points 設定的多邊形頂點
% poly_point_x = [1 1 10 14 7];
% poly_point_y = [0 12 13 2 4];
poly_point_x = [0 0 9];
poly_point_y = [1 12 1];

%% actual points 待測試頂點
test_x = 6;
test_y = 0;

c=0;
m=0;
%% return test point in poly or not 判斷測試點是否在多邊形內
hold on;
plot(poly_point_x,poly_point_y,'*')
plot(test_x,test_y,'.')
n = 4;%n=頂點數+1
for i = 1: n-1
    if i == 1
        j = n - 1;
    else
        j = i - 1;
    end
    y = ((poly_point_y(:,i) > test_y) ~= (poly_point_y(:,j) > test_y));
    x = ((poly_point_x(:,j) - poly_point_x(:,i))*(test_y - poly_point_y(:,i))/(poly_point_y(:,j) - poly_point_y(:,i)) + poly_point_x(:,i))>test_x;
    
    if y&&x
        c = ~c;
    end
end
c

 

當返回0時,代表點不在多邊形中。當返回1時,代表點在多邊形中。

 

參考資料:    

筆記A0320180207

http://blog.csdn.net/luyuncsd123/article/details/27528519

https://www.cnblogs.com/luxiaoxun/p/3722358.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM