【 imgproc 模块. 图像处理】Sobel导数
主要步骤为:
(1)高斯滤波降噪
GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT );
(2)转换为灰度图
cvtColor(src, src_gray, CV_RGB2GRAY);
(3)求x方向上的梯度,并转化为 CV_8U
//Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT ); Sobel(src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
(4)求y方向上的梯度,并转化为 CV_8U
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT ); Sobel(src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT); convertScaleAbs(grad_y, abs_grad_y);
(5)合并梯度
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
openCV例程源代码:
#include"stdafx.h" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <stdlib.h> #include <stdio.h> using namespace cv; /** @function main */ int main(int argc, char** argv) { Mat src, src_gray; Mat grad; char* window_name = "Sobel Demo - Simple Edge Detector"; int scale = 1; int delta = 0; int ddepth = CV_16S; int c; /// 装载图像 src = imread("lena512color.tiff"); if (!src.data) { return -1; } GaussianBlur(src, src, Size(3, 3), 0, 0, BORDER_DEFAULT); /// 转换为灰度图 cvtColor(src, src_gray, CV_RGB2GRAY); /// 创建显示窗口 namedWindow(window_name, CV_WINDOW_AUTOSIZE); /// 创建 grad_x 和 grad_y 矩阵 Mat grad_x, grad_y; Mat abs_grad_x, abs_grad_y; /// 求 X方向梯度 //Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT ); Sobel(src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT); convertScaleAbs(grad_x, abs_grad_x); /// 求Y方向梯度 //Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT ); Sobel(src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT); convertScaleAbs(grad_y, abs_grad_y); /// 合并梯度(近似) addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad); imshow(window_name, grad); waitKey(0); return 0; }
One day,I will say
"I did it"