凸包(在轮廓发现的基础上)
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
Mat src, dst;
int threshold_value = 50;
int threshold_max = 255;
const char* output = "output_image";
void convexHull_demo(int, void*);
RNG rng;
int main() {
src = imread("D:/b.jpeg");
if (src.empty()) {
printf("could not load image");
return -1;
}
namedWindow(output, WINDOW_AUTOSIZE);
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input",src);
cvtColor(src,src,COLOR_BGR2GRAY);
blur(src,src,Size(3,3),Point(-1,-1),BORDER_DEFAULT);
const char* threshold_bar = "threshold_bar";
createTrackbar(threshold_bar,output,&threshold_value,threshold_max,convexHull_demo);
convexHull_demo(0,0);
waitKey();
return 0;
}
void convexHull_demo(int ,void*) {
Mat bin_output;
vector<vector<Point>> contours;
vector<Vec4i>hierachy;
threshold(src, 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, Mat(), 0, Point(0, 0));
imshow(output, dst);
}
}