QImage与IplImage之间的转换

2019-07-13 07:21发布

网上很多的QImageIplImage之间的转换代码,不知道别人能否顺利的用过,反正我是没顺利的使用过。主要问题是图像数据排列问题,最重要的是关注图像数据每行占多少个字节,因为涉及到对齐问题。两种不同的数据结构中都有相关的成员变量来表示,这个必须得统一,否则会发生错位或者segment fault的错误。 目前为止,嵌入式Linux 中并没有完全实现openCV类库,所以不能正常使用像cvLoadImage这类函数。我的大体思路是使用QT来读入、显示和存储图像,用openCV的库函数来处理图像。 使用openCV中绝大部分图像处理函数的输入都是IplImage类型的灰度图像,其中涉及最重要的代码就是QImage与IplImage之间的转换,在借鉴其他网友的代码基础上做了适合自己应用的修改,代码如下: IplImage *Lplimage2QImage::QImageToIplImageRGB(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; } IplImage *Lplimage2QImage::QImageToIplImageGray(const QImage * qImage) { int width = qImage->width(); int height = qImage->height(); int widthStep = 0; CvSize Size; Size.height = height; Size.width = width; IplImage *charIplImageBuffer = cvCreateImage(Size, IPL_DEPTH_8U, 1); widthStep = charIplImageBuffer->widthStep; char *charTemp = (char *) charIplImageBuffer->imageData; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { int index = y * widthStep + x; charTemp[index] = (char) qGray(qImage->pixel(x, y)); } } return charIplImageBuffer; } QImage *Lplimage2QImage::IplImageToQImageGray(const IplImage * iplImage) { int width = iplImage->width; int widthStep = iplImage->widthStep; int height = iplImage->height; QImage *qImage = new QImage((uchar*)iplImage->imageData,width,height, widthStep,QImage::Format_Indexed8); QVector grayColourTable; for(int i = 0; i < 256; i++) grayColourTable.append(qRgb(i, i, i)); qImage->setColorTable(grayColourTable); return qImage; } QImage *Lplimage2QImage::IplImageToQImageRGB(const IplImage * iplImage) { int width = iplImage->width; int widthStep = iplImage->widthStep; int height = iplImage->height; uchar *qImageBuffer = (uchar *) malloc(width*height*4*sizeof(uchar)); uchar *QImagePtr = qImageBuffer; const uchar *iplImagePtr = (const uchar *) iplImage->imageData; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { QImagePtr[0] = iplImagePtr[0]; QImagePtr[1] = iplImagePtr[1]; QImagePtr[2] = iplImagePtr[2]; QImagePtr[3] = 0; QImagePtr += 4; iplImagePtr += 3; } iplImagePtr += widthStep-3*width; } QImage *qImage = new QImage(qImageBuffer, width, height, QImage::Format_RGB32); return qImage; }