只用来记录学习笔记
int threshold_value = 100;
int threshold_max = 255;
void Demo_Contours(int, void*);
cvtColor(src, gray_src, CV_BGR2GRAY); //转灰度图像gray_src
const char* trackbar_title = "output";
createTrackbar(trackbar_title, output_title, &threshold_value, threshold_max, Demo_Contours);//用滑块改变
Demo_Contours(0, 0);
void Demo_Contours(int, void*) {
Mat canny_output;
vector<vector<Point>> contours;
vector<Vec4i> hierachy;
Canny(gray_src, canny_output, threshold_value, threshold_value * 2, 3, false);//提取轮廓
//gray_src:灰度图像
//canny_output
//threshold_value:低阈值
//threshold_value * 2:高阈值
//3:Soble算子的size
findContours(canny_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
// canny_output:输入图像,非0的像素被看成1,0的像素值保持不变,8-bit
// contours: 全部发现的轮廓对象
// hierachy:图该的拓扑结构,可选,该轮廓发现算法正是基于图像拓扑结构实现。
// RETR_TREE:轮廓返回的模式
// CHAIN_APPROX_SIMPLE:发现方法
// Point(0, 0): 轮廓像素的位移,默认(0, 0)没有位移
dst = Mat::zeros(src.size(), src.type());//新建一个dst
RNG rng(12345);
for (int i = 0; i < (int) contours.size(); i++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));//生成一个随机颜色
drawContours(dst, contours, i, color, 2, 8, hierachy, 0, Point(0, 0));//绘制轮廓
//dst: 输出图像
//contours: 全部发现的轮廓对象
//i: 轮廓索引号
//color: 绘制时候颜色
// 2:绘制线宽
// 8:线的类型LINE_8
//hierachy: 拓扑结构图
// 0:最大层数, 0只绘制当前的,1表示绘制绘制当前及其内嵌的轮廓
// Point(0, 0):轮廓位移,可选
}
imshow(output_title, dst);
}
效果图: