这个系列的目的是通过对OpenCV示例,进一步了解OpenCV函数的使用,不涉及具体原理。
本文记录了对OpenCV示例convexhull.cpp的分析。
Example源码:
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <fstream>
#include <iostream>
using namespace cv;
using namespace std;
static void help()
{
cout << "\nThis sample program demonstrates the use of the convexHull() function\n"
<< "Call:\n"
<< "./convexhull\n" << endl;
}
int main( int /*argc*/, char** /*argv*/ )
{
Mat img(500, 500, CV_8UC3);
RNG& rng = theRNG();
help();
for(;;)
{
char key;
int i, count = (unsigned)rng%100 + 1;
vector<Point> points;
for( i = 0; i < count; i++ )
{
Point pt;
pt.x = rng.uniform(img.cols/4, img.cols*3/4);
pt.y = rng.uniform(img.rows/4, img.rows*3/4);
points.push_back(pt);
}
vector<int> hull;
convexHull(Mat(points), hull, true);
img = Scalar::all(0);
for( i = 0; i < count; i++ )
circle(img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA);
int hullcount = (int)hull.size();
Point pt0 = points[hull[hullcount-1]];
for( i = 0; i < hullcount; i++ )
{
Point pt = points[hull[i]];
line(img, pt0, pt, Scalar(0, 255, 0), 1,LINE_AA);
pt0 = pt;
}
imshow("hull", img);
key = (char)waitKey();
if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
break;
}
return 0;
}
Example运行截图
1
|
|
2
|
|
3
|
|
Example分析
这个例子说明函数 convexHull的使用。
convexHull用于计算凸包,凸包在很多地方有着重要的作用,如手势识别,需要识别出手的轮廓的凸包,二维或者三维区域的边界等等。
convexHull
函数原型: void convexHull(InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true); 参数说明: InputArray points: 要求凸包的点集;OutputArray hull: 输出的凸包点; bool clockwise: bool变量,表示求得的凸包是顺时针方向还是逆时针方向,true是顺时针方向,false为逆时针方向 PS:对于OutputArray hull参数可以为std::vector<int>,这是返回的是凸包点在原轮廓点集中的索引,当为std::vector<cv::Point>时,表示的是凸包点的位置 |
参考资料:
1.《
opencv中convexHull函数说明
》