C# 如何将EmguCV图像转换为Unity3D Sprite?

C# 如何将EmguCV图像转换为Unity3D Sprite?,c#,unity3d,emgucv,unity3d-gui,C#,Unity3d,Emgucv,Unity3d Gui,我尝试在新的Unity3D用户界面系统上渲染Emgu相机拍摄的图像。 到目前为止,我使用了这个存储库中的ImageToTexture2d: 然后使用Sprite.Create最终达到想要的效果 但是!在我运行Unity editor 2-3分钟后,它突然占用了大约3GB的内存,而开始的内存大约为200MB 我有两个问题: 更可能的是,我使用的方法没有清除内存。它使用互操作并创建一些不安全的指针——它有泄漏的味道。 每帧运行的Sprite.Create会在内存中保存旧的Sprite,并且不会删除它

我尝试在新的Unity3D用户界面系统上渲染Emgu相机拍摄的图像。 到目前为止,我使用了这个存储库中的ImageToTexture2d: 然后使用Sprite.Create最终达到想要的效果

但是!在我运行Unity editor 2-3分钟后,它突然占用了大约3GB的内存,而开始的内存大约为200MB

我有两个问题:

更可能的是,我使用的方法没有清除内存。它使用互操作并创建一些不安全的指针——它有泄漏的味道。 每帧运行的Sprite.Create会在内存中保存旧的Sprite,并且不会删除它们。 你们中有谁知道有没有其他方法可以将Emgu的图像转换为Sprite/Texturewithout,而不需要使用互操作或我可以在新Unity的UI上显示的任何其他方式。它必须是Emgu的图像,因为我也对从相机接收到的图像进行了一些操作


提前感谢您的回复和帮助:D

在不知道游戏的大部分内容的情况下,您是否正在销毁内存中创建的对象的可能复制品


3GB的突然增加是否与游戏中的任何行为有关?即使没有活动,它也会增加吗?

经过一些研究,我发现了问题所在,但没有时间描述它。我不知道每个帧创建的纹理都保存在引擎的某个地方。在从Emgu图像生成新图像之前,必须先将其销毁

以下是我在项目中使用的部分代码:

//Capture used for taking frames from webcam
private Capture capture;
//Frame image which was obtained and analysed by EmguCV
private Image<Bgr,byte> frame;
//Unity's Texture object which can be shown on UI
private Texture2D cameraTex;

//...

if(frame!=null)
    frame.Dispose();
frame = capture.QueryFrame();
if (frame != null)
{
    GameObject.Destroy(cameraTex);
    cameraTex = TextureConvert.ImageToTexture2D<Bgr, byte>(frame, true);
    Sprite.DestroyImmediate(CameraImageUI.GetComponent<UnityEngine.UI.Image>().sprite);
    CameraImageUI.sprite = Sprite.Create(cameraTex, new Rect(0, 0, cameraTex.width, cameraTex.height), new Vector2(0.5f, 0.5f));
}

但是,您是如何从EmguCV图像实现阵列的?此外,你拼写错单词高度。请考虑编辑和解释你的答案用一个小文本。帮助其他读者理解问题的实质。
public static Texture2D ArrayToTexture2d(Image<Rgb, byte> picture) {
    Array bytes = picture.ManagedArray;
    int h = bytes.GetLength(0);
    int w = bytes.GetLength(1);
    Texture2D t2d = new Texture2D(w, h);
    double r, b, g;

    for (int heigth = 0; heigth < bytes.GetLength(0); heigth++)
    {
        for (int width = 0; width < bytes.GetLength(1); width++)
        {
            r = Convert.ToDouble(bytes.GetValue(heigth, width, 0));
            g = Convert.ToDouble(bytes.GetValue(heigth, width, 1));
            b = Convert.ToDouble(bytes.GetValue(heigth, width, 2));

            t2d.SetPixel(width, h - heigth - 1, new Color((float)r / 256, (float)g / 256, (float)b / 256, 1f));                
        }
    }

    t2d.Apply();
    return t2d;
}
RawImage targetRawImage;
Image<Rgb, byte> scanned = new Image<Rgb, byte>("Assets/Textures/scanned.png");
Texture2D loaded = new Texture2D(scanned.Width, scanned.Height);
loaded.LoadImage(scanned.ToJpegData());
targetRawImage.texture = loaded;