Ask Your Question

Revision history [back]

To illustrate @Spas Hristov his asnwer, here is some sample code on how to calculate gradient images.

void calculateGradientImage(Mat inputImage, Mat outputImage, Size kernelSize, int sigma){
   Mat grayImage, smoothedImage;
   // Some basic smoothing on the image to remove pixelation
   GaussianBlur( inputImage, smoothedImage, kernelSize, sigma);
   // Convert RBG towards grayscale image
   cvtColor( smoothedImage, grayImage, CV_RGB2GRAY );

   // Calculate gradient image
   Mat grad_X = Mat(inputImage.rows, inputImage.cols, CV_32F);
   Mat grad_Y = Mat(inputImage.rows, inputImage.cols, CV_32F);

   // Gradient for the X direction
   Sobel( grayImage, grad_X, CV_32F, 1, 0, 3, 1, 0, BORDER_DEFAULT );
   // Gradient for the Y direction
   Sobel( grayImage, grad_Y, CV_32F, 0, 1, 3, 1, 0, BORDER_DEFAULT );

   // Combine both gradient functions together
   // total = sqrt(dx² + dy²) <-- more correct than just adding both values weighted together
   Mat gradient = Mat(grayImage.rows, grayImage.cols, CV_64F);
   sum = grad_X.mul(grad_X)+ grad_Y.mul(grad_Y;
   sqrt(sum, gradient);

   // Push back the gradient image
   imageOutput = gradient;
};