pz1145 pz1145 - 1 month ago 27
C# Question

Images in EmguCV not releasing resources

I am using EmguCV 3.1.0.2282 and I found that when I use an image, there are times when it doesn't release its resources and eats up memory until the PC is out of resources and an out of memory exception is thrown.

Here is a test code I did within my application. When the button is clicked, a new local image is instantiated based on an existing bitmap in memory. It will do a manual dispose if the checkbox is checked.

private void button1_Click(object sender, EventArgs e)
{
Image<Bgr, Byte> TempImage = new Image<Bgr, Byte>(CurrentLeftBitmap);
TempImage.ThresholdBinary(new Bgr(2.2, 3.3, 4.4), new Bgr(100.0, 100.0, 100.0));
if (checkBox1.Checked)
{
TempImage.Dispose();
TempImage = null;
}
}


I found each time I click on the button, memory goes down and won't be released without an application restart. Even when I do a manual dispose, memory still goes down. Funny thing is that if I commented out the ThresholdBinary step, it works fine. However, it still requires a manual dispose. I've also tried the USING statement but still the same.

My question is that has anyone encounter something similar? What is the proper way of implementing these image objects?

Answer

Yes, doing this will run you out of memory. I managed to drain my 32GB system doing 5000 iterations of your method. The problem is ThresholdBinary return another Image, you are not taking that image so the memory gets allocated but has no way to be disposed of. Change

TempImage.ThresholdBinary(new Bgr(2.2, 3.3, 4.4), new Bgr(100.0, 100.0, 100.0));

To

Image<Bgr, byte> newImage = TempImage.ThresholdBinary(new Bgr(2.2, 3.3, 4.4), new Bgr(100.0, 100.0, 100.0));

Will help.

Because they are locals the GC will eventually get around to cleaning them up. But it is always a good idea to dispose of things. So I added

TempImage.Dispose();
newImage.Dispose();

Running this 5,000 time my memory usage hardly moved.