c++ - 将 MATLAB 代码转换为 OpenCV C++

标签 c++ matlab opencv

我是 OpenCV 的新手,正在尝试使用 C++ 将以下 MATLAB 代码转换为 OpenCV:

    [FX,FY]=gradient(mycell{index});

到目前为止我已经尝试了以下方法,但我的值与我的 MATLAB 结果完全不同

    Mat abs_FXR;
    Mat abs_FYR;
    int scale = 1;
    int delta = 0;

    // Gradient X
    Sobel(myImg, FXR, CV_64F, 1, 0, 3, scale, delta, BORDER_DEFAULT);
    convertScaleAbs( FXR, abs_FXR );
    imshow( window_name2, abs_FXR );

    // Gradient Y
    Sobel(myImg, FYR, CV_64F, 0, 1, 3, scale, delta, BORDER_DEFAULT);
    convertScaleAbs( FYR, abs_FYR );
    imshow( window_name3, abs_FYR );

我也尝试根据这个问题使用 filter2D,但它仍然给出不同的结果:Matlab gradient equivalent in opencv

Mat kernelx = (Mat_<float>(1,3)<<-0.5, 0, 0.5);
Mat kernely = (Mat_<float>(3,1)<<-0.5, 0, 0.5);
filter2D(myImg, FXR, -1, kernelx);
filter2D(myImg, FYR, -1, kernely);
imshow( window_name2, FXR );
imshow( window_name3, FYR );

我不知道这是偏离轨道还是只是我需要更改的参数。任何帮助将不胜感激。

更新 这是我预期的 MATLAB 输出:

enter image description here enter image description here

但这是我使用 Sobel 从 OpenCV 获得的结果:

enter image description here enter image description here

这是我使用 Filter2D 方法从 OpenCV 得到的输出(我尝试增加我的高斯滤波器的大小,但与 MATLAB 相比仍然得到不同的结果)

enter image description here enter image description here

我还使用以下方法将图像转换为 double :

eye_rtp.convertTo(eye_rt,CV_64F);

最佳答案

为了匹配梯度,您需要进行中心差分计算而不是使用 Sobel 滤波器(尽管 Sobel 确实给出了一个很好的导数)是正确的。顺便说一句,如果您有图像处理工具箱,imgradientimgradientxy 可以选择使用 Sobel 计算梯度。 (请注意,the answer in the question you referenced错误的,因为 Sobel 仅提供二阶导数,因为有可用的一阶和二阶 Sobel 算子)。

关于您看到的差异,您可能需要在 filter2D 之前将 myImg 转换为 float 或 double。检查FXL等的输出类型

此外, double 为 CV_64F,单精度为 CV_32F,尽管在​​这种情况下这可能只会造成非常小的差异。

关于c++ - 将 MATLAB 代码转换为 OpenCV C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22943336/

相关文章:

Matlab/Octave/Numpy 数值差异

matlab - 精度 Matlab 的斜线矩阵运算符

c++ - all() matlab 函数 opencv

java - rpi 上的 OpenCV - System.loadLibrary 中的段错误

c++ - Qt:qthread 在关闭期间线程仍在运行时被销毁

c++ - Qt中的实时像素绘制

c++ - 创建指向没有默认构造函数的类的智能指针数组

C++ 输出到 .CSV 文件

arrays - MATLAB 中的矩阵数组

algorithm - 打开 Find CornerSubPix 算法