QImage和IplImage轉換總結
阿新 • • 發佈:2018-02-03
title tpi ews vsize ann channel pre tro pan
在arm中做圖像處理,因為不支持GTK,一般都會用到QT來實現顯示功能,所以不可避免的要涉及到QImage和IplImage兩種圖像格式之間的轉換,下面總結一下轉換的方法。
(下面格式轉換的代碼都是網友寫的,我這裏只是歸納修改了一下)
IplImage 轉換為 QImage
方法1
[plain] view plain copy- QImage *IplImageToQImage(const IplImage *img)
- {
- QImage *qmg;
- cvCvtColor(img,img,CV_BGR2RGB);
- qmg = new QImage((unsigned char*)img->imageData,img->width,img->height,img->widthStep,QImage::Format_RGB888);
- return qmg;
- }
這裏要註意的是,IplImage每個像素點存儲的格式為BGR,而QImage每個像素點存儲的格式為RGB,所以在轉換之前需要先使用opencv提供的cvCvtColor函數將BGR圖像變為RGB圖像。還有就是QImage最後一個參數QImage::Format_RGB888,這是指色彩空間R,G,B三個通道分別用8位來表示,如果是灰度圖,則參數為QImage::Format_Indexed8。
例如:
[plain] view plain copy
- QImage *IplImageToQImage(const IplImage *img)
- {
- QImage *qmg;
- IplImage *img_gray = cvCreateImage(cvGetSize(img),8,1);
- cvCvtColor(img,img_gray,CV_BGR2GRAY);
- qmg = new QImage((unsigned char*)img->imageData,img->width,img->height,img->widthStep,QImage::Format_Indexed8);
- return qmg;
- }
方法2
[plain] view plain copy- QImage *IplImageToQImage(*img)
- {
- QImage *qmg = new QImage (img->width,img-height,img->widthStep,QImage::Format_RGB32);
- for (int i=0; i<height; ++i)
- {
- for (int j=0; j<width; ++j)
- {
- int r,g,b;
- if( 3 == img->nChannels )
- {
- b = (int)CV_IMAGE_ELEM( img, uchar, i, j*3+0 );
- g = (int)CV_IMAGE_ELEM( img, uchar, i, j*3+1 );
- r = (int)CV_IMAGE_ELEM( img, uchar, i, j*3+2 );
- }
- else if( 1 == img->nChannels )
- {
- b = (int)CV_IMAGE_ELEM( img, uchar, i, j*3+0 );
- g = b;
- r = b;
- }
- qmg->setPixel( j, i, qRgb(r,g,b) );
- }
- }
- return qmg;
- }
這裏要註意的是qmg->setPixel( j, i, qRgb(r,g,b) );括號裏面是(j,i);而不是(i,j)。我還沒弄明白為什麽這裏要調換一下i,j的順序,希望知道的朋友指點一下。
QImage轉換為IplImage
方法1
[plain] view plain copy- IplImage *QImageToIplImage(const QImage * qImage)
- {
- int width = qImage->width();
- int height = qImage->height();
- CvSize Size;
- Size.height = height;
- Size.width = width;
- IplImage *IplImageBuffer = cvCreateImage(Size, IPL_DEPTH_8U, 3);
- for (int y = 0; y < height; ++y)
- {
- for (int x = 0; x < width; ++x)
- {
- QRgb rgb = qImage->pixel(x, y);
- cvSet2D(IplImageBuffer, y, x, CV_RGB(qRed(rgb), qGreen(rgb), qBlue(rgb)));
- }
- }
- return IplImageBuffer;
- }
方法2
[plain] view plain copy
- IplImage *QImageToIplImage(const QImage * qImage)
- {
- int width = qImage->width();
- int height = qImage->height();
- CvSize Size;
- Size.height = height;
- Size.width = width;
- IplImage *IplImageBuffer = cvCreateImage(Size, IPL_DEPTH_8U, 3);
- for (int y = 0; y < height; ++y)
- {
- for (int x = 0; x < width; ++x)
- {
- QRgb rgb = qImage->pixel(x, y);
- CV_IMAGE_ELEM( IplImageBuffer, uchar, y, x*3+0 ) = qBlue(rgb);
- CV_IMAGE_ELEM( IplImageBuffer, uchar, y, x*3+1 ) = qGreen(rgb);
- CV_IMAGE_ELEM( IplImageBuffer, uchar, y, x*3+2 ) = qRed(rgb);
- }
- }
- return IplImageBuffer;
- }
這兩種方法其實都是一樣的,只是表達形式有點不同,還有就是一個是生成RGB格式圖像,一個是生成BGR格式的圖像。
QImage和IplImage轉換總結