Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab gradient equivalent in opencv

I am trying to migrate some code from Matlab to Opencv and need an exact replica of the gradient function. I have tried the cv::Sobel function but for some reason the values in the resulting cv::Mat are not the same as the values in the Matlab version. I need the X and Y gradient in separate matrices for further calculations.

Any workaround that could achieve this would be great

like image 461
Arpan Shah Avatar asked Dec 10 '25 10:12

Arpan Shah


1 Answers

Sobel can only compute the second derivative of the image pixel which is not what we want.

(f(i+1,j) + f(i-1,j) - 2f(i,j)) / 2

What we want is

(f(i+i,j)-f(i-1,j)) / 2

So we need to apply

Mat kernelx = (Mat_<float>(1,3)<<-0.5, 0, 0.5);
Mat kernely = (Mat_<float>(3,1)<<-0.5, 0, 0.5);
filter2D(src, fx, -1, kernelx)
filter2D(src, fy, -1, kernely);

Matlab treats border pixels differently from inner pixels. So the code above is wrong at the border values. One can use BORDER_CONSTANT to extent the border value out with a constant number, unfortunately the constant number is -1 by OpenCV and can not be changed to 0 (which is what we want).

So as to border values, I do not have a very neat answer to it. Just try to compute the first derivative by hand...

like image 157
Pei Guo Avatar answered Dec 12 '25 04:12

Pei Guo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!