I found memory leak when converting images into texture2D in my project with unity3d(both in version 4.5 and 5.1). I notice that 20 MB memory increased in a second and the program crash after 10min with more than 10G+ system memory run out.
In my project, images are from web camera and then processed with emguCV. There emguCV exposes an interface Bitmap to exchange internal data with applications. Thus why I need to convert Bitmap into texture2D. I’ve goole for some days and tried some advises, but with no luck. The core code snippet is illustratedin the following . I’m wandering if anyone can show me the right way. Any advises will be appritiated. Thank you in advance!
code snippet:
void Update()
{
//dstImage is a emgucv type Mat.
Texture2D extracted = GameObject.Find(“Plane”).GetComponent().material.mainTexture as Texture2D;
FormatConvert.BitmapToTexture2D(ref extracted, dstImage.Bitmap, dstImage.Width, dstImage.Height);
}
public class FormatConvert
{
public static void BitmapToTexture2D(ref Texture2D target, Bitmap bmp, int texturewidth, int textureheight)
{
using (MemoryStream ms = new MemoryStream())
{
try
{
bmp.Save(ms, bmp.RawFormat);
}
catch (Exception ex)
{
throw ex;
}
target.LoadImage(ms.ToArray());
ms.Close();
}
}
}