1 #include "opencv2/imgproc/imgproc.hpp" 2 #include "opencv2/highgui/highgui.hpp" 3 #include <stdlib.h> 4 #include <stdio.h> 5 6 using namespace cv; 7 8 /** @function main */ 9 int main( int argc, char** argv ) 10 { 11 12 Mat src, src_gray; 13 Mat grad; 14 char* window_name = "Sobel Demo - Simple Edge Detector"; 15 int scale = 1; 16 int delta = 0; 17 int ddepth = CV_16S; 18 19 int c; 20 21 /// 装载图像 22 src = imread( argv[1] ); 23 24 if( !src.data ) 25 { return -1; } 26 27 GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT ); 28 29 /// 转换为灰度图 30 cvtColor( src, src_gray, CV_RGB2GRAY ); 31 32 /// 创建显示窗口 33 namedWindow( window_name, CV_WINDOW_AUTOSIZE ); 34 35 /// 创建 grad_x 和 grad_y 矩阵 36 Mat grad_x, grad_y; 37 Mat abs_grad_x, abs_grad_y; 38 39 /// 求 X方向梯度 40 //Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT ); 41 Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); 42 convertScaleAbs( grad_x, abs_grad_x ); 43 44 /// 求Y方向梯度 45 //Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT ); 46 Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); 47 convertScaleAbs( grad_y, abs_grad_y ); 48 49 /// 合并梯度(近似) 50 addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad ); 51 52 imshow( window_name, grad ); 53 54 waitKey(0); 55 56 return 0; 57 }