首页 > 代码库 > 【转】Mat、Ipllmage与 QImage 的相互转换

【转】Mat、Ipllmage与 QImage 的相互转换

(1) cv::Mat ->  QImage

OpenCV存储图片默认使用BGR顺序,而QImage使用RGB顺序,所以需要用cvtColor转换一下。

使用QImage如下构造函数:QImage(uchar * data, int width, int height, Format format)

QImage mat2qimage(const Mat& mat) {
      Mat rgb;
      cvtColor(mat, rgb, CV_BGR2RGB); 
      return QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, QImage::Format_RGB888); 
};

(2) QImage -> cv::Mat

QImage使用 RGBa(?) 四个通道保存图像数据,转换成的Mat应该删掉第四个通道。

Mat qimage2mat(const QImage& qimage) {
      cv::Mat mat = cv::Mat(qimage.height(), qimage.width(), CV_8UC4, (uchar*)qimage.bits(), qimage.bytesPerLine()); 
      cv::Mat mat2 = cv::Mat(mat.rows, mat.cols, CV_8UC3 ); 
      int from_to[] = { 0,0, 1,1, 2,2 };
      cv::mixChannels( &mat, 1, &mat2, 1, from_to, 3 );
      return mat2;
}

3、QImage 转 IplImage(imageRGB32 --> originalImage):

QImage imageRGB32(fileName);
QImage image = imageRGB32.convertToFormat(QImage::Format_RGB888);
IplImage *Oimage = cvCreateImageHeader(cvSize(image.width(), image.height()), IPL_DEPTH_8U, 3);
Oimage->imageData = http://www.mamicode.com/(char *)image.bits();
IplImage *originalImage = cvCreateImage(cvSize(image.width(), image.height()), IPL_DEPTH_8U, 3);
cvConvertImage(Oimage, originalImage, CV_CVTIMG_SWAP_RB);
cvReleaseImageHeader(&Oimage);


4、IplImage 转 QImage(BGRimage --> Qimage):

IplImage *BGRimage = cvLoadImage(filename, CV_LOAD_IMAGE_COLOR);
IplImage *RGBimage = cvCreateImage(cvSize(BGRimage->width, BGRimage->height), IPL_DEPTH_8U, 3);
cvConvertImage(BGRimage, RGBimage, CV_CVTIMG_SWAP_RB);
QImage Qimage((uchar *)RGBimage->imageData, RGBimage->width, RGBimage->height, RGBimage->widthStep, QImage::Format_RGB888);
cvReleaseImage(&BGRimage);
cvReleaseImage(&RGBimage);