什么是凸包(Convex Hull)
任意两点的连线都包含在多边形边界内,还有一个约束条件,就是这个多边形最小。
凸包的应用
物体的凸包检测常应用在物体识别、手势识别及边界检测等领域。
凸包检测常常用在轮廓分析之后。对二值图像进行轮廓分析之后,可以构建每个轮廓的凸包,构建完成之后会返回该凸包包含的点集。根据返回的凸包点集可以绘制该轮廓对应的凸包。一般来说,凸性曲线总是凸出来的,至少是平的。如果有地方凹进去了就被叫做凸性缺陷。
convexHull函数解释
convexHull函数的调用形式
void convexHull(InputArray points,OutputArray hull,bool clockwise = false,
bool returnPoints = true)
参数详解:
-
InputArray points: 得到的点集,一般是用图像轮廓函数求得的轮廓点
-
OutputArray hull: 输出的是凸包的二维xy点的坐标值,针对每一个轮廓形成的
-
bool clockwise = false: 表示凸包的方向,顺时针或者逆时针
-
bool returnPoint = true: 表示返回点还是点地址的索引
实例代码
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
static void help(char** argv)
{
cout << "\nThis sample program demonstrates the use of the convexHull() function\n"
<< "Call:\n"
<< argv[0] << endl;
}
int main( int argc, char** argv )
{
CommandLineParser parser(argc, argv, "{help h||}");
if (parser.has("help"))
{
help(argv);
return 0;
}
Mat img(500, 500, CV_8UC3);
RNG& rng = theRNG();
for(;;)
{
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<Point> hull;
convexHull(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);
polylines(img, hull, true, Scalar(0, 255, 0), 1, LINE_AA);
imshow("hull", img);
char key = (char)waitKey();
if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
break;
}
return 0;
}
代码解释:
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);
}
随机生成count个点,随机生成的点范围 x(img.cols/4, img.cols3/4),y(img.rows/4, img.rows3/4)这样保正随机生成的点在img的特定区域。
convexHull(points, hull, true);
将随机生成的点集points作为输入,hull作为输出,调用convexHull。
for( i = 0; i < count; i++ )
circle(img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA);
polylines(img, hull, true, Scalar(0, 255, 0), 1, LINE_AA);
imshow("hull", img);
将随机生成的所有点画在img上。通过polylines()
将凸点合集全部画在img上。最终结果展示: