【问题标题】:How can I convert OpenCV Mat to Texture2D in Unity using C# script?如何使用 C# 脚本在 Unity 中将 OpenCV Mat 转换为 Texture2D?
【发布时间】:2018-07-30 02:03:49
【问题描述】:

我只是想将 Mat 类型变量转换为 Texture2D 类型。

我可以将 texture2D 转换为 mat,这仅使用 EncodeToJPG() 函数。 像这样:

Mat mat = Mat.FromImageData(_texture.EncodeToPNG());

Texture2D -> Mat 很简单...但我无法转换 "MAT -> Texture2D"

【问题讨论】:

    标签: c# opencv unity3d opencvsharp


    【解决方案1】:

    使用 opencvsharp,使用Mat.GetArray 获取垫子的字节数组数据,然后根据垫子的高度和宽度对其进行循环。在该循环中将mat数据复制到Color32,最后使用Texture2D.SetPixels32()和Texture2D.Apply()设置和应用像素。

    void MatToTexture(Mat sourceMat) 
    {
        //Get the height and width of the Mat 
        int imgHeight = sourceMat.Height;
        int imgWidth = sourceMat.Width;
    
        byte[] matData = new byte[imgHeight * imgWidth];
    
        //Get the byte array and store in matData
        sourceMat.GetArray(0, 0, matData);
        //Create the Color array that will hold the pixels 
        Color32[] c = new Color32[imgHeight * imgWidth];
    
        //Get the pixel data from parallel loop
        Parallel.For(0, imgHeight, i => {
            for (var j = 0; j < imgWidth; j++) {
                byte vec = matData[j + i * imgWidth];
                var color32 = new Color32 {
                    r = vec,
                    g = vec,
                    b = vec,
                    a = 0
                };
                c[j + i * imgWidth] = color32;
            }
        });
    
        //Create Texture from the result
        Texture2D tex = new Texture2D(imgWidth, imgHeight, TextureFormat.RGBA32, true, true);
        tex.SetPixels32(c);
        tex.Apply();
    }
    

    如果您不使用 opencvsharp 而是使用 C++ 和 C# 自己制作插件,请参阅 this 帖子。

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2018-11-28
      • 2022-06-25
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多