简体   繁体   English

如何使用C#脚本在Unity中将OpenCV Mat转换为Texture2D?

[英]How can I convert OpenCV Mat to Texture2D in Unity using C# script?

I just want to convert Mat type variable to Texture2D type. 我只想将Mat类型变量转换为Texture2D类型。

I can convert texture2D to mat and this only use EncodeToJPG() function. 我可以将texture2D转换为mat,这只能使用EncodeToJPG()函数。 like this: 像这样:

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

Texture2D -> Mat is easy...but I cannot convert "MAT -> Texture2D" Texture2D-> Mat很容易...但是我不能转换“ MAT-> Texture2D”

With opencvsharp, use Mat.GetArray to get the byte array data of the mat then loop over it based on the the height and width of the mat. 对于opencvsharp,请使用Mat.GetArray来获取mat的字节数组数据,然后根据mat的高度和宽度在其上循环。 Copy the mat data to Color32 in that loop and finally use Texture2D.SetPixels32() and Texture2D.Apply() to set and apply the pixel. 在该循环中将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();
}

If you're not using opencvsharp but making the plugin yourself with C++ and C# then see this post. 如果您不是使用opencvsharp,而是使用C ++和C#自己制作插件,请参阅这篇文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM