步骤:
Canny算法介绍-五步in CV::Canny
1.高斯模糊- GaussianBlur
2.灰度转换- cvtColor
3.计算梯度- Sobel/Scharr
4.非最大信号抑制
5.高低阈值输出二值图像
Canny算法介绍-高低阈值输出二值图像
●T1, T2为阈值,凡是高于T2的都保留,凡是小于T1都丢弃,从高于T2的像素出发,凡是大于T1而且相互连接的,都保留。最终得到一一个输出二值图像。
●推荐的高低阈值比值为T2: T1 = 3:1/2:1其中T2为高阈值,T1为低阈值
API:Cv::Canny
Canny (
InputArray src, // 8-bit的输入图像
OutputArray edges,//输出边缘图像,-般都是二值图像,背景是黑色
double threshold1,//低阈值,常取高阈值的1/2或者1/3
double threshold2,//高阈值
int aptertureSize,// Soble算子的size ,通常3x3 ,取值3
bool L2gradient //选择true表示是L2来归一化,否则用L1归一化
)
代码:
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
Mat src, gray_src, dst;
int t1_val = 50;
int t1_max = 255;
const char* outputtitle = "result image";
void Canny_Demo(int, void*);
int main(int argc, char** argv) {
src = imread("C:/Users/ThinkPad/Desktop/1.PNG");
if (!src.data) {
printf("could not find");
return -1;
}
namedWindow("demo", cv::WINDOW_AUTOSIZE);
namedWindow(outputtitle, cv::WINDOW_AUTOSIZE);
imshow("demo", src);
cvtColor(src, gray_src, COLOR_BGR2GRAY);
//转换为灰度图
createTrackbar("Threshold Value", outputtitle, &t1_val, t1_max, Canny_Demo);
Canny_Demo(0, 0);
waitKey(0);
return 0;
}
void Canny_Demo(int, void*) {
Mat edge_output;
blur(gray_src, gray_src, Size(3, 3), Point(-1, -1), BORDER_DEFAULT);
Canny(gray_src, edge_output, t1_val, t1_val*2, 3, false);
//dst.create(src.size(), src.type());
//将图像的边缘显示,是彩色的边缘。像素为1的时候,将原像素的值copy到上。
//src.copyTo(dst, edge_output);
imshow(outputtitle, edge_output);
}
结果: