Ryan Kennedy
Ryan Kennedy

Reputation: 3637

Releasing unneeded QImages

My application streams webcam images to a QWidget, and then has no need for those images after they've been displayed. The application runs for about a minute or two before giving this error several dozen times and crashing:

QImage: out of memory, returning null image

The QWidget uses a displayImage(QImage) method which gets called several times per second. I have a feeling that the image should take a pointer as a parameter, but I have no reasoning to back that up.

How can I ensure that the QImages are released from memory?

Note: To create the images, I'm using the technique described in the accepted answer of the SO question how to convert an opencv cv::Mat to qimage .

Upvotes: 1

Views: 749

Answers (2)

Bill
Bill

Reputation: 11832

The QImage class uses implicit data sharing. Excerpts from the doc:

Many C++ classes in Qt use implicit data sharing to maximize resource usage and minimize copying. Implicitly shared classes are both safe and efficient when passed as arguments, because only a pointer to the data is passed around, and the data is copied only if and when a function writes to it, i.e., copy-on-write.

A shared class consists of a pointer to a shared data block that contains a reference count and the data.

When a shared object is created, it sets the reference count to 1. The reference count is incremented whenever a new object references the shared data, and decremented when the object dereferences the shared data. The shared data is deleted when the reference count becomes zero.

Implicit sharing takes place behind the scenes; the programmer does not need to worry about it.

This means that if you pass a QImage object into displayImage() by value then a new QImage will be created but the image data in the first QImage will not be duplicated but only a shared reference counter will be incremented. But this also means that if you would like to release the memory your first QImage object allocated then you need to make sure that both QImage objects go out of scope.

Upvotes: 1

cmannett85
cmannett85

Reputation: 22376

As noted in docs regarding implicit sharing:

When a shared object is created, it sets the reference count to 1. The reference count is incremented whenever a new object references the shared data, and decremented when the object dereferences the shared data. The shared data is deleted when the reference count becomes zero.

This means that you must have QImage frames referenced somewhere in your code.

Upvotes: 0

Related Questions