Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Memory leak in converting image to texture2D

Discussion in 'Scripting' started by tyxxy, Sep 5, 2015.

  1. tyxxy

    tyxxy

    Joined:
    Sep 5, 2015
    Posts:
    3
    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<Renderer>().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();
    }
    }
    }
     
  2. Agent_007

    Agent_007

    Joined:
    Dec 18, 2011
    Posts:
    899
  3. tyxxy

    tyxxy

    Joined:
    Sep 5, 2015
    Posts:
    3

    Great Thanks for you Agent_007, it works! :p


    void Update()
    {
    //dstImage is a emgucv type Mat.
    Texture2D extracted = GameObject.Find("Plane").GetComponent<Renderer>().material.mainTexture as Texture2D;
    Destroy(extracted); // Add this line
    FormatConvert.BitmapToTexture2D(ref extracted, dstImage.Bitmap, dstImage.Width, dstImage.Height);
    }