【问题标题】:converting byte array to Mat将字节数组转换为 Mat
【发布时间】:2021-01-12 09:54:12
【问题描述】:

我有一个 CCD 驱动程序,它返回 IntPtr 给我。我使用 Marshal.Copy 到字节数组(bytearray_Image),bytearray_Image 中的每个元素存储 8bit R/G/B 值,序列为 byte[0] = R 值,byte[1] = G 值,byte[2] = B价值……等等。我已使用以下代码 sn-p 成功转换为 3 Channels Mat:

var src = new Mat(rows: nHeight, cols: nWidth, type: MatType.CV_8UC3); var indexer = src.GetGenericIndexer();

        int x = 0;
        int y = 0;
        for (int z = 0; z < (bytearray_Image.Length - 3); z += 3)
        {
            byte blue = bytearray_Image[(z + 2)];
            byte green = bytearray_Image[(z + 1)];
            byte red = bytearray_Image[(z + 0)];

            Vec3b newValue = new Vec3b(blue, green, red);
            indexer[y, x] = newValue;
            x += 1;

            if (x == nWidth)
            {
                x = 0;
                y += 1;
            }
        }

由于图像非常大,这种方法转换图像似乎太慢了。有什么方法可以有效地进行这种转换吗?

【问题讨论】:

    标签: c# opencvsharp


    【解决方案1】:

    此代码适用于我:

    var image = new Mat(nHeight, nWidth, MatType.CV_8UC3);
    int length = nHeight * nWidth * 3; // or image.Height * image.Step;
    Marshal.Copy(bytearray_Image, 0, image.ImageData, length);
    

    但只有当 byte[] 数据的步长等于 Mat 的步长时,它才对你有用

    【讨论】:

    • 感谢您的回复,image.ImageData 是指 Mat.Data 属性吗?由于我找不到 image.ImageData,我使用的是 opencvsharp ver。 4.5
    • 我确实尝试过使用 image.Data 而不是 image.ImageData,它有效!与使用 GetGenericIndexer(7xxMB 与 3xxMB)方法相比,性能提高了很多,但内存使用量大约是 2 倍。无论如何,谢谢user2250152回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    相关资源
    最近更新 更多