二十八、凸包(Convex Hull
)
1、概念介绍
- 什么是凸包:在一个多边形边缘或者内部任意两个点的连线都包含在多边形边界或者内部。
- 正式定义:包含点集合S中所有点的最小凸多边形称为凸包。
- 检测算法
Graham扫描法
- 首先选择Y方向最低的点作为起始点p0
- 从p0开始极坐标扫描,依次添加p1…pn(排序顺序是根据极坐标的角度大小,逆时针方向)
- 对每个点pi来说,如果添加pi点到凸包中导致一个左转向(逆时针方向)则添加该点到凸包,反之如果导致一个右转向(顺时针方向)则从凸包中删除该点。
- OpenCV中已经实现了凸包发现算法和API提供我们使用。
2、API说明cv::convexHull
convexHull(
InputArray points,//输入候选点,来自findContours
OutputArray hull,//凸包,构成凸包的点
bool clockwise,//default true,顺时针方向
bool returnPoints//true表示返回点个数,如果第二个参数是vector<Point>则自动忽略
)
3、步骤
- 首先把图像转换为灰度图像
cvtColor
- 将图像转为二值图像
threshold
- 通过发现轮廓得到候选点
findContours
- 凸包API调用
convexHull
- 绘制显示
drawContours
,凸包也是一种特殊的轮廓
示例代码:(凸包)
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
Mat src, src_gray, dst;
int threshold_value = 100;
int threshold_max = 255;
void Threshold_Callback(int, void*);
char output_win[] = "convexHull demo";
RNG rng(12345);
int main(int argc, char** argv) {
src = imread("添加图片路径");
if (!src.data) {
cout << "could not load image..." << endl;
return -1;
}
namedWindow("output_win", WINDOW_AUTOSIZE);
imshow("input image", src);
cvtColor(src, src_gray, COLOR_BGR2GRAY);//转灰度
blur(src_gray, src_gray, Size(3, 3), Point(-1, -1), BORDER_DEFAULT);//模糊
createTrackbar("Threshold value:", output_win, &threshold_value, threshold_max, Threshold_Callback);//控制阈值
Threshold_Callback(0,0);
waitKey(0);
return 0;
}
void Threshold_Callback(int, void*) {
Mat bin_output;
vector<vector<Point>> contours;//存储轮廓点
vector<Vec4i> hierachy;
threshold(src_gray, bin_output, threshold_value, threshold_max, THRESH_BINARY);//二值化
findContours(bin_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));//发现轮廓点
vector<vector<Point>> convexs(contours.size());//存储凸包点,容量初始化为轮廓点的数量
for (size_t i = 0; i < contours.size(); i++) {//计算凸包轮廓点
convexHull(contours[i], convexs[i], false, true);
}//对每一组轮廓的全部轮廓点计算其凸包,留下符合凸包的点存入convexs中,其余的舍弃
//绘制
src.copyTo(dst);
for (size_t i = 0; i < contours.size(); i++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(dst, convexs, i, color, 2, LINE_8, Mat(), 0, Point(0,0));
}
imshow(output_win, dst);
}
输出结果显示:(threshold_value: 238
)