【OpenCV】凸包-Convex Hull
概念介绍
什么是凸包(Convex Hull),在一个多变形边缘或者内部任 意两个点的连线都包含在多边形边界或者内部。
检测算法
- Graham扫描法
概念介绍-Graham扫描算法 - 首先选择Y方向最低的点作为起始点p0
- 从p0开始极坐标扫描,依次添加p1….pn(排序顺序是根据极坐标的角度大小,逆时针方向)
- 对每个点pi来说,如果添加pi点到凸包中导致一个左转向(逆时针方法)则添加该点到凸包,
反之如果导致一个右转向(顺时针方向)删除该点从凸包中
相关APIcv::convexHull
convexHull(
InputArray points,// 输入候选点,来自findContours
OutputArray hull,// 凸包
bool clockwise,// default true, 顺时针方向
bool returnPoints)// true 表示返回点个数,如果第二个参数是 vector<Point>则自动忽略
步骤
- 首先把图像从RGB转为灰度
- 然后再转为二值图像
- 在通过发现轮廓得到候选点
- 凸包API调用
- 绘制显示
代码实现
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
int threshold_value = 100;
int threshold_max = 255;
Mat src, src_gray, dst;
const char* output_title = "convexhull_demo";
const char* input_title = "input";
RNG rng(12345);
void convexhull_demo(int, void*);
int main(int argc, char**argv)
{
src = imread("2.jpg");
if (!src.data) {
printf("cannot load the image...\n");
return -1;
}
namedWindow(input_title, CV_WINDOW_AUTOSIZE);
cvtColor(src, src_gray, CV_BGR2GRAY);
blur(src_gray, src_gray, Size(3, 3), Point(-1, -1));
imshow(input_title, src);
namedWindow(output_title, CV_WINDOW_AUTOSIZE);
createTrackbar("threshhold_value", output_title, &threshold_value, threshold_max, convexhull_demo);
convexhull_demo(0, 0);
waitKey(0);
return 0;
}
void convexhull_demo(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);//寻找凸包
}
dst = Mat::zeros(src.size(), CV_8UC3);
for (size_t k = 0; k < contours.size(); k++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));//随机颜色
drawContours(dst, contours, k, color, 2, 8, hierachy, 0, Point(0, 0));//绘制轮廓
drawContours(dst, convexs, k, color, 2, 8, hierachy, 0, Point(0, 0));//绘制凸包
}
imshow(output_title, dst);
}
实验效果·