OpenCV尋找物體的凸包convexHull()
應用到的知識點:
1.尋找物體的凸包convexHull
2.定義和輸出vector容器點坐标
3.随機數發生器
==================================
凸包檢測示例程式:
//尋找物體的凸包convexHull
//定義和輸出vector容器點坐标
#include <opencv2/opencv.hpp>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <vector>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
Mat testImage(600, 600, CV_8UC3);//畫布大小600x600
RNG& rng = theRNG();
//按Enter鍵一直更新
while (1)
{
//int count = (unsigned)rng % 100 + 8;//随機生成點的數量
int count = rng.uniform(5, 20);//随機産生點的個數
cout << "凸包包含 " << count << " 個點" << endl;
cout << "各點坐标如下:" << endl;//輸出産生随機點個數
vector<Point>points;//vector容器存放點坐标
for (int i = 0; i < count; i++)
{
Point point;
//點坐标随機産生
point.x = rng.uniform(testImage.cols / 5, testImage.cols * 4 / 5); //橫坐标x在範圍(600/1,600*4/5)随機産生
point.y = rng.uniform(testImage.rows / 4, testImage.rows * 3 / 4);//縱坐标y在範圍(600/4,600*3/4)随機産生
points.push_back(point);
cout << "Point" << i + 1 << ": " << point << endl;//依次輸出随機産生每個點的坐标
}
cout << "基于Mat的vector:\n" << Mat(points) << endl;//基于Mat類的vector将以矩陣形式輸出坐标
//檢測凸包
vector<int >hull;
convexHull(Mat(points), hull, true);
testImage = Scalar::all(0);//将畫布設定為黑色
for (int i = 0; i < count; i++)
circle(testImage, points[i], 5, Scalar(255, 0, 255), -1, 4);//以随機點為圓心,畫出半徑為5的實心圓(标記作用)
//參數準備
int hullcout = (int)hull.size();//凸包的邊數
Point point0 = points[hull[hullcout - 1]];//連接配接凸包的坐标點
//依次連接配接随機點,繪制凸包
for (int i = 0; i < hullcout; i++)
{
Point point = points[hull[i]];
line(testImage, point0, point, Scalar(0, 255, 255), 1, 4);//連接配接線條顔色為黃色
point0 = point;
}
//輸出
imshow("凸包繪制檢測", testImage);
char key;
key = (char)waitKey();
if (key == 27 || key == 'q' || key == 'Q')//按下ESC 或q 或 Q 退出
break;
}
return 0;
}
==================================
運作結果:
運作結果1
注意比較兩種坐标的輸出格式,一個是std::vector格式,另一種是基于Mat的vector格式(矩陣形式)。
============================================================
運作結果2
========================================================================================