【計算幾何】多邊形點集排序

來源:互聯網
上載者:User

標籤:

問題描述:已知多邊形點集C={P1,P2,...,PN},其排列順序是雜亂,依次串連這N個點,無法形成確定的多邊形,需要對點集C進行排序後,再繪製多邊形。

點集排序過程中,關鍵在於如何定義點的大小關係。

以按逆時針排序為例,演算法步驟如下:

定義:點A在點B的逆時針方向,則點A大於點B

1.計算點集的重心O,以重心作為逆時針旋轉的中心點。

2.計算點之間的大小關係。

大小關係的計算,可由兩種方法進行計算。

方法1:

以重心O作一條平行於X軸的單位向量OX,然後依次計算OPi和OX的夾角,根據夾角的大小,確定點之間的大小關係。

OPi和OX夾角越大,說明點Pi越小,。

方法2:

根據向量叉積的定義,向量OPi和OPj的叉積大於0,則向量OPj在向量OPi的逆時針方向,即點Pj小於點Pi。

依據方法2,多邊形點集排序的代碼如下:

 1 typedef struct Point 2 { 3     int x; 4     int y; 5 }Point; 6 //若點a大於點b,即點a在點b順時針方向,返回true,否則返回false 7 bool PointCmp(const Point &a,const Point &b,const Point &center) 8 { 9     if (a.x >= 0 && b.x < 0)10         return true;11     if (a.x == 0 && b.x == 0)12         return a.y > b.y;13     //向量OA和向量OB的叉積14     int det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);15     if (det < 0)16         return true;17     if (det > 0)18         return false;19     //向量OA和向量OB共線,以距離判斷大小20     int d1 = (a.x - center.x) * (a.x - center.x) + (a.y - center.y) * (a.y - center.y);21     int d2 = (b.x - center.x) * (b.x - center.y) + (b.y - center.y) * (b.y - center.y);22     return d1 > d2;23 }24 void ClockwiseSortPoints(std::vector<Point> &vPoints)25 {26     //計算重心27     cv::Point center;28     double x = 0,y = 0;29     for (int i = 0;i < vPoints.size();i++)30     {31         x += vPoints[i].x;32         y += vPoints[i].y;33     }34     center.x = (int)x/vPoints.size();35     center.y = (int)y/vPoints.size();36 37     //冒泡排序38     for(int i = 0;i < vPoints.size() - 1;i++)39     {40         for (int j = 0;j < vPoints.size() - i - 1;j++)41         {42             if (PointCmp(vPoints[j],vPoints[j+1],center))43             {44                 cv::Point tmp = vPoints[j];45                 vPoints[j] = vPoints[j + 1];46                 vPoints[j + 1] = tmp;47             }48         }49     }50 }

參考資料:

http://blog.csdn.net/beyond071/article/details/5855171

http://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order

【計算幾何】多邊形點集排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.