您现在的位置是:首页 >技术杂谈 >unity emgucv Texture2D转Mat / Mat转Texture2D / Texture 转 Texture2D网站首页技术杂谈

unity emgucv Texture2D转Mat / Mat转Texture2D / Texture 转 Texture2D

吴梓穆 2024-10-01 00:01:02
简介unity emgucv Texture2D转Mat / Mat转Texture2D / Texture 转 Texture2D

Mat是emgucv的类,需要导入dll
首先需要导入emgucv要用的dll
免积分下载

Texture2D转Mat

    private Mat Texture2DToMat(Texture2D texture2D)
    {
        using (MemoryStream baseTexture_ms = new MemoryStream(texture2D.EncodeToPNG(), false))
        {    
            Bitmap bitemap = new Bitmap(baseTexture_ms);
            Image<Bgr, byte> imageCV = new Image<Bgr, byte>(bitemap);//注意Image的命名空间是Emgu.CV
            return imageCV.Mat;
        }
    }

Mat转Texture2D

    private Texture2D MatToTexture2D(Mat mat)//Mat转Texture2D
    {
        Image<Bgr, byte> resultImage = mat.ToImage<Bgr, byte>();
        Texture2D resultTexture = new Texture2D(1, 1);
        resultTexture.LoadImage(resultImage.ToJpegData());
        resultImage.Dispose();
        return resultTexture;
    }

这些不需要emgucv的dll,什么都不需要额外导入

Texture 转Texture2D

    private Texture2D GetTexture2D(Texture texture)
    {
        Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);

        RenderTexture renderTexture = new RenderTexture(texture.width, texture.height, 32);
        RenderTexture.active = renderTexture;
        UnityEngine.Graphics.Blit(texture, renderTexture);//将纹理从Texture渲染到RenderTexuture

        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();

        RenderTexture.active = null;
        GameObject.Destroy(renderTexture);

        return texture2D;
    }

Texture2D 转Texture

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。