尋找物體的凸包 opencv


 

凸包的含義:

  在二維平面上給定點集,凸包就是將最外層的點連接起來構成的凸多邊形。並且這個凸多邊形能包含點集中所有的點。
OPENCV中:

convexHull函數用於尋找圖像點集中的凸包。它有六個輸入參數。

第一個參數:輸入的二維點集
第二個參數:輸出的凸包。為數組類型的hull
第三個參數:bool類型的clockwise。當此標志符為真時,輸出的凸包為順時針方向,否則,為逆時針方向。
第四個參數:bool類型的returnPoints,操作標識符,默認值為true。

 1 #include<opencv2/opencv.hpp>
 2 #include<iostream>
 3 
 4 using namespace std;
 5 using namespace cv;
 6  
 7 int main()
 8 {
 9     Mat image(600, 600, CV_8UC3);  //創建一個600*600 8位無符號字符型的3通道圖像
10     RNG& rng = theRNG();     ////用其引用來接收theRNG函數返回的隨機數生成器
11 
12     while (1)
13     {
14         char key; // 鍵值
15         int count = rng.uniform(3,103);//隨機生成點的數量
16         vector<Point>points;  //二維點集存在這個向量里面
17 
18         for (int i = 0; i < count; i++)   //點的坐標
19         {
20             Point point;
21             point.x = rng.uniform(image.cols /4, image.cols * 3 / 4);
22             point.y = rng.uniform(image.rows / 4, image.cols * 3 / 4);
23             points.push_back(point);  //生成的點放進points這個向量里面
24         }
25         //檢測凸包
26         vector<int> hull;  //第二個參數聲明
27         convexHull(Mat(points), hull, true);
28 
29         image = Scalar::all(0);//初始化圖像為全黑色
30         //隨機化點的顏色 並畫出
31         for (int i = 0; i < count; i++)
32         {
33             circle(image, points[i], 3, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), FILLED, LINE_AA);
34         }
35         //准備參數
36         int hullcount = (int)hull.size();//凸包的邊數
37         Point point0 = points[hull[hullcount - 1]]; //連接凸包邊的坐標點
38         //繪制凸包的邊
39         for (int i = 0; i < hullcount; i++)
40         {
41             Point point = points[hull[i]];
42             line(image, point0, point, Scalar(255, 255, 255), 2, LINE_AA);
43             point0 = point;
44         }
45         //顯示效果圖
46         imshow("凸包檢測示例", image);
47         //按下ESC退出程序
48         key = (char)waitKey();
49         if (key == 27)
50             break;
51     }
52 
53     return 0;
54 }

檢測效果:


免責聲明!

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



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