c# - 将OpenCV C++重写为EmguCV C#-如何使用指针?

标签 c# c++ opencv emgucv

我正在尝试将用OpenCV 2.x编写的C++代码转换为C#中的Emgu.CV。
我在C++中有一个函数:

cv::Mat computeMatXGradient(const cv::Mat &mat) {
    cv::Mat out(mat.rows, mat.cols, CV_64F);
    for (int y = 0; y < mat.rows; ++y) {
        const uchar* Mr = mat.ptr<uchar>(y);
        double* Or = out.ptr<double>(y);
        Or[0] = Mr[1] - Mr[0];
        for (int x = 1; x < mat.cols - 1; ++x) {
            Or[x] = (Mr[x + 1] - Mr[x - 1]) / 2.0;
        }
        Or[mat.cols - 1] = Mr[mat.cols - 1] - Mr[mat.cols - 2];
    }
    return out;
}
如何使用EmguCV在C#中有效地执行相同的操作?
到目前为止-我有以下C#代码:
(我无法测试它,因为缺少很多代码)
Mat computeMatXGradient(Mat inMat)
{
    Mat outMat = new Mat(inMat.Rows, inMat.Cols, DepthType.Cv64F, inMat.NumberOfChannels);
    for (int y = 0; y < inMat.Rows; ++y)
    {
        // unsafe is required if I'm using pointers
        unsafe {
            byte* Mr = (byte*) inMat.DataPointer;
            double* Or = (double*) outMat.DataPointer;
            Or[0] = Mr[1] - Mr[0];
            for (int x = 1; x < inMat.Cols - 1; ++x)
            {
               Or[x] = (Mr[x + 1] - Mr[x - 1]) / 2.0;
            }
            Or[inMat.Cols - 1] = Mr[inMat.Cols - 1] - Mr[inMat.Cols - 2];
        }
    }
    return outMat;
}
问题:
  • 我的C#代码正确吗?
  • 有更好/更有效的方法吗?
  • 最佳答案

    您可以尝试将inMat转换为inM数组,然后计算另一个数组Or中所需的值,最后将后一个数组转换为输出Mat outMat
    注意:我认为NumberOfChannels为1,因为我认为情况总是如此。

    Mat computeMatXGradient(Mat inMat)
    {
        int x, y;
        byte[] inM, Mr;
        double[] Or;
        inM = new byte[(int)inMat.Total];
        inMat.CopyTo(inM);
        Mr = new byte[inMat.Cols];
        Or = new double[inMat.Rows * inMat.Cols];
        for (y = 0; y < inMat.Rows; y++)
        {
            Array.Copy(inM, y * inMat.Cols, Mr, 0, inMat.Cols);
            Or[y * inMat.Cols] = Mr[1] - Mr[0];
            for (x = 1; x < inMat.Cols - 1; x++)
               Or[y * inMat.Cols + x] = (Mr[x + 1] - Mr[x - 1]) / 2.0;
            Or[y * inMat.Cols + inMat.Cols - 1] = Mr[inMat.Cols - 1] - Mr[inMat.Cols - 2];
        }
        Mat outMat = new Mat(inMat.Rows, inMat.Cols, DepthType.Cv64F, 1);
        Marshal.Copy(Or, 0, outMat.DataPointer, inMat.Rows * inMat.Cols);
        return outMat;
    }
    

    关于c# - 将OpenCV C++重写为EmguCV C#-如何使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62898662/

    相关文章:

    c# - 并非所有程序集都从 bin 文件夹加载到 AppDomain

    c# - 不在焦点时将键盘输入发送到 Spotify

    c# - 使用 C# 在 IIS 中以编程方式创建网站并设置端口号

    c++ - 函数原型(prototype)与 C++ 类中的任何原型(prototype)都不匹配

    c++ - 在 cv::imshow() 中出现错误 - 断言:文件 qasciikey.cpp 中的 "false",第 501 行

    c# - 使用 Entity Framework 作为 DataGridView 的数据源的正确方法是什么?

    c++ - 替代控制台输出流

    c++ - 类定义中的 sizeof(*this)

    c++ - 在 OpenCV C++ 接口(interface)中更改 Mat 类实例的数据类型

    python - 如何从docker容器连接到rtsp相机?