什么是凸包?
解释:给定二维平面上的点集,凸包就是将最外层的点连接起来构成的凸边形,它是包含点集中所有的点。
如下:用人手图来举例说明凸缺陷概念。手周围深色的线描画出凸包,A到H被标出的区域是凸包的各个“缺陷”,这些凸度缺陷提供了手以及手状态的特征表现的方法。

说明:convexHull()函数用于寻找图像点集中的凸包。
void convexHull(InputArray points,OutputArray hull,bool clockwise=false,bool returnPoints=true)
函数说明:返回默认的随机数生成器。如果需要使用生成器获得一个随机数或者初始化一个数组,可以使用 randu 或者 randn
代替。但想要在一个循环中产生很多随机数,那么使用此函数检索生成器,会很快。
RNG &rng = theRNG(); //用其引用来接收theRNG函数返回的随机数生成器(RNG就是随机数生成器的类)
void circle(CV_IN_OUT Mat& image, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8);
说明:随机生成3~103个坐标值随机的彩色点,然后将这些点连接起来
#include
#include
#include
#include
using namespace std;
using namespace cv;
int main()
{
//初始化变量和随机值
Mat image(500, 500, CV_8UC3);
RNG & rng = theRNG();
while (1)
{
char key;
int count = (unsigned)rng % 100 + 3;//随机生成点的数量
cout << count << endl;
vector<Point> points;//点值
//随机生成点坐标
for (int i = 0; i < count; i++)
{
Point point;
point.x = rng.uniform(image.cols / 4, image.cols * 3 / 4);//uniform() 方法将随机生成下一个实数,它在[x,y]范围内。
point.y = rng.uniform(image.rows / 4, image.rows * 3 / 4);
if(i<10)
cout << "(" << point.x << "," << point.y << ")" << endl;
points.push_back(point);//C++ vector::push_back 会先创建临时对象,然后将临时对象拷贝到容器中
}
//检测凸包
vector<int> hull;
convexHull(Mat(points), hull, true);
//绘制出随机颜色的点
image = Scalar::all(0);
for (int i = 0; i < count; i++)
{
circle(image, points[i], 3, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), FILLED,LINE_AA);
}
//准备参数
int hullcount = (int)hull.size();//凸包边数
Point point0 = points[hull[hullcount - 1]];//连接凸包边的坐标点
// cout << hull[0] <<":"<< hull.size()<
//绘制凸包的边
for (int i = 0; i < hullcount; i++)
{
Point point = points[hull[i]];
line(image, point0, point, Scalar(255, 255, 255), 2, LINE_AA);
point0 = point;
}
imshow("凸包检测", image);
key = (char)waitKey();
if (key == 27 || key == 'q' || key == 'Q')
break;
}
return 0;
}
