只用来记录学习笔记
凸包:任意两个点的连线都在多边形内
Graham扫描算法:
如果新加入点后两条线的逆时针角度小于180度了就舍弃旧的点,如:bc和cd的逆时针角度小于180度了,就舍弃掉c点。
代码:
cvtColor(src, gray_src, CV_BGR2GRAY); //转灰度图像
blur(gray_src, gray_src, Size(3, 3), Point(-1, -1), BORDER_DEFAULT); //模糊
createTrackbar(trackbar_title, output_title, &threshold_value, threshold_max, Threshold_CallBack);//滑块改变threshold_value
Threshold_CallBack(0, 0);
模糊笔记:opencv学习笔记6-模糊图像-均值模糊&高斯模糊
void Threshold_CallBack(int, void*) {
Mat bin_output;
vector<vector<Point>> contours;
vector<Vec4i> hierachy;
threshold(gray_src, bin_output, threshold_value, threshold_max, THRESH_BINARY); //阈值操作(阈值二值化)
findContours(bin_output, contours, 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);//凸包
// contours[i]:输入候选点,来自findContours
// convexs[i]: 凸包
//default true, 顺时针方向
//true: true 表示返回点个数,如果第二个参数是vector<Point>则自动忽略
}
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, LINE_8, hierachy, 0, Point(0, 0));//画轮廓
drawContours(dst, convexs, k, color, 2, LINE_8, Mat(), 0, Point(0, 0));//画凸包
}
imshow(output_title, dst);
}
阈值操作笔记:opencv学习笔记12-阈值操作threshold
轮廓发现笔记:opencv学习笔记26-轮廓发现findContours和绘制轮廓drawContours
效果图:(轮廓+凸包):
效果图:(凸包):