基础知识的理论,主要看这个博客:https://blog.csdn.net/github_38140310/article/details/68959931
然后代码展示:
1 #include "opencv2/imgproc/imgproc.hpp" 2 #include "opencv2/highgui/highgui.hpp" 3 #include4 #include 5 6 using namespace cv; 7 8 /** @function main */ 9 int main() //int argc, char** argv10 {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("C:\\Users\\32829\\Desktop\\aa.jpg");23 24 if (!src.data)25 {26 return -1;27 }28 29 GaussianBlur(src, src, Size(3, 3), 0, 0, BORDER_DEFAULT);30 31 /// 转换为灰度图32 cvtColor(src, src_gray, CV_RGB2GRAY);33 34 /// 创建显示窗口35 namedWindow("原图", CV_WINDOW_AUTOSIZE);36 37 /// 创建 grad_x 和 grad_y 矩阵38 Mat grad_x, grad_y;39 Mat abs_grad_x, abs_grad_y;40 41 /// 求 X方向梯度42 //Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT );43 Sobel(src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);44 convertScaleAbs(grad_x, abs_grad_x);45 46 /// 求Y方向梯度47 //Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );48 Sobel(src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);49 convertScaleAbs(grad_y, abs_grad_y);50 51 /// 合并梯度(近似)52 addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);53 imshow("原图", grad);54 //imwrite("testout.jpg", grad);55 waitKey(0);56 57 return 0;58 }
=========================================
结果展示:
============================================