示例程序032--Canny边缘检测(2.3版)
代码及注释:
// 039 Canny边缘检测 2.3版.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
/// 全局变量
Mat src, src_gray;
Mat dst, detected_edges;
int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";
void CannyThreshold(int, void*)
{
/// 使用 3x3内核降噪
blur( src_gray, detected_edges, Size(3,3) );
/// 运行Canny算子,支持原地计算。根据Canny算法的推荐,Canny阈值输入比例1:3,核大小为3*3
Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
/// 黑色背景
dst = Scalar::all(0);
// copyTo 将 detected_edges 拷贝到 dst . 但是,仅仅拷贝掩码不为0的像素。
//Canny边缘检测的输出是镶嵌在黑色背景中的边缘像素,因此其结果 dst 图像除了被检测的边缘像素,其余部分都为黑色。
src.copyTo( dst, detected_edges);
imshow( window_name, dst );
//imshow( window_name, detected_edges );
}
int main( int argc, char** argv )
{
src = imread( "Lena.jpg" );
if( !src.data )
{ return -1; }
/// 创建与src同类型和大小的矩阵(dst)
dst.create( src.size(), src.type() );
/// 原图像转换为灰度图像
cvtColor( src, src_gray, CV_BGR2GRAY );
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
/// 创建trackbar
createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
/// 显示图像,用于第一次没有移动滑块的时候
CannyThreshold(0, 0);
waitKey(0);
return 0;
}
运行结果: