Matlab gradient equivalent in opencv

前端 未结 5 946
感情败类
感情败类 2020-12-10 21:54

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 22:43

    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_(1,3)<<-0.5, 0, 0.5);
    Mat kernely = (Mat_(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...

提交回复
热议问题