首页 > 代码库 > OpenCV Tutorials —— Sobel Derivatives
OpenCV Tutorials —— Sobel Derivatives
图像边缘 —— 像素灰度值变换剧烈的点
You can easily notice that in an edge, the pixel intensity changes in a notorious way. A good way to expresschanges is by using derivatives. A high change in gradient indicates a major change in the image.
To be more graphical, let’s assume we have a 1D-image. An edge is shown by the “jump” in intensity in the plot below:
The edge “jump” can be seen more easily if we take the first derivative (actually, here appears as a maximum)
Sobel Operator
- 1,The Sobel Operator is a discrete differentiation operator. It computes an approximation of the gradient of an image intensity function.
2,The Sobel Operator combines Gaussian smoothing and differentiation.
包括高斯滤波和差分(求导)
Formulation
Assuming that the image to be operated is :
We calculate two derivatives:
Horizontal changes: This is computed by convolving with a kernel with odd size. For example for a kernel size of 3, would be computed as:
Vertical changes: This is computed by convolving with a kernel with odd size. For example for a kernel size of 3, would be computed as:
At each point of the image we calculate an approximation of the gradient in that point by combining both results above:
Although sometimes the following simpler equation is used:
OpenCV addresses this inaccuracy for kernels of size 3 by using the Scharr function. This is as fast but more accurate than the standar Sobel function.
It implements the following kernels:
calculate the “derivatives” in x and y directions.
Mat grad_x, grad_y;Mat abs_grad_x, abs_grad_y;/// Gradient XSobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT );/// Gradient YSobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT );The function takes the following arguments:
- src_gray: In our example, the input image. Here it is CV_8U
- grad_x/grad_y: The output image.
- ddepth: The depth of the output image. We set it to CV_16S to avoid overflow.
- x_order: The order of the derivative in x direction.
- y_order: The order of the derivative in y direction.
- scale, delta and BORDER_DEFAULT: We use default values.
convert our partial results back to CV_8U:
convertScaleAbs( grad_x, abs_grad_x );convertScaleAbs( grad_y, abs_grad_y );
Code
#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; /// Load an image src = http://www.mamicode.com/imread( argv[1] );>
OpenCV Tutorials —— Sobel Derivatives