PDA

View Full Version : IplImage to QImage memory issue



p3l-outrepid
11th May 2010, 12:19
Dear forum,
I am using this method to change from IplImage captured by OpenCV library to a QImage to use QPainter class on and paint on it another QImage, now the problem is that I am using the method in a while loop which eats up my memory (over 1GB in mere seconds) and I can't find a way around it.

QImage MainWindow::IplImage2QImage(IplImage *iplImg)
{
this->h = iplImg->height;
this->w = iplImg->width;
this->channels = iplImg->nChannels;
this->qimg = new QImage(w, h, QImage::Format_ARGB32);
this->data = iplImg->imageData;

for (int y = 0; y < h; y++, data += iplImg->widthStep)
{
for (int x = 0; x < w; x++)
{
char r, g, b, a = 0;
if (channels == 1)
{
r = data[x * channels];
g = data[x * channels];
b = data[x * channels];
}
else if (channels == 3 || channels == 4)
{
r = data[x * channels + 2];
g = data[x * channels + 1];
b = data[x * channels];
}

if (channels == 4)
{
a = data[x * channels + 3];
qimg->setPixel(x, y, qRgba(r, g, b, a));
}
else
{
qimg->setPixel(x, y, qRgb(r, g, b));
}
}
}
return *qimg;
}
now that's the method itself and the while loop for looping on frames is the following

while(i<numFrames){
if(i<(SelectedFrame+numofFrames)){
cvGrabFrame(capture);
img2=cvRetrieveFrame(capture);
qimage=this->IplImage2QImage(img2);
QPainter p(&qimage);
p.drawImage(xcoordinate, ycoordinate, input , 0,0,-1,-1,Qt::AutoColor);
img3=this->qtToCv(&(qimage));
cvWriteFrame(writer,img3);
i++;
img2=0;
img3=0;
p.end();
qimage=QImage();
}
else {
cvGrabFrame(capture);
img2=cvRetrieveFrame(capture);
cvWriteFrame(writer,img2);
i++;
img2=0;
}
ui->progressBar_2->setValue(i);
}
now I know that the problem is with the method because I commented everything else and only the calling of the method caused the memory overload. All I need is for another method (or a change in this method) to ensure that not too much memory is used while applying it.
Thanks a lot and best regards,
p3l

high_flyer
12th May 2010, 09:35
The reason for the memory consumption is that you are only allocating memory, and never free it.
There is no need to allocate a new QImage for each iteration.
Allocate the QImage once, and reuse it.


QImage MainWindow::IplImage2QImage(IplImage *iplImg)
{
this->h = iplImg->height;
this->w = iplImg->width;
this->channels = iplImg->nChannels;
if(this->qimg == NULL); //don't forget to set qimg = NULL in the constructor, and delete it in the destructor (or give it a parent)
this->qimg = new QImage(w, h, QImage::Format_ARGB32);
this->data = iplImg->imageData;
.....
}