Monday, October 18, 2010

Convert IPLImage (OpenCV) to QImage (Qt) vice versa

This snippet will convert QImages into iplImage with depth 8 and 3 channels. QImage can store data in several formats. This code accepts just 24-bit QImage::Format_RGB888 and the QImage::Format_RGB32. Alpha values in the 32-bit format will be removed during the conversion.

static IplImage* qImage2IplImage(const QImage& qImage)
{
  int width = qImage.width();
  int height = qImage.height();
  // Creates a iplImage with 3 channels
  IplImage *img = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
  char* imgBuffer = img->imageData;
  //Remove alpha channel
  int jump = (qImage.hasAlphaChannel())? 4 : 3;
  for(int y=0;yheight;y++){
    QByteArray a((constchar*)qImage.scanLine(y), qImage.bytesPerLine());
  for(int i=0; i<a.size(); i+="jump){
    //Swap from RGB to BGR
    imgBuffer[2]= a[i];
    imgBuffer[1]= a[i+1];
    imgBuffer[0]= a[i+2];
    imgBuffer+=3;
  }
}
return img;

This snippet will convert a iplImage with depth 8 and 3 channels into a 24-bit QImage.

static QImage IplImage2QImage(const IplImage *iplImage) 
{ 
  int height = iplImage->height; 
  int width = iplImage->width; 
  if (iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 3) 
  { 
      const uchar *qImageBuffer =(const uchar*)iplImage->imageData; 
      QImage img(qImageBuffer, width, height, QImage::Format_RGB888); 
      return img.rgbSwapped(); 
  }else{ 
    qWarning() << "Image cannot be converted."; 
   return QImage(); 
  } 
} 


http://wiki.forum.nokia.com/index.php?title=Special:PdfPrint&page=Using_OpenCV_with_Qt

Another method here:

http://umanga.wordpress.com/2010/04/19/how-to-covert-qt-qimage-into-opencv-iplimage-and-wise-versa/

Do they work for you?
Please leave a comment.

No comments:

Post a Comment