cv::Mat 与 QImage 的相互转换

目录

cv::Mat 与 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;
};

—————————————

引自:http://opencv-users.1802565.n2.nabble.com/QImage-to-OpenCV-td5121181.html

I found out what is wrong, QImage has a forth channel for alpha. When you read the qimage data into a 4 channel mat and remove the fourth channel everything is okay. The weird thing is that somehow the QIMage seems to be in BGRA order, but maybe I’m doing something wrong.

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;
};

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);
};