Mat默认是BGR空间,QImage默认是RGB空间。Mat侧重矩阵运算,而QImage侧重图像显示。
Mat ——> QImage:
QImage MatToQImage(Mat & mat)
{
Mat rgb;
QImage Img;
if(mat.channels() == 3)
{
cvtColor(mat, rgb, COLOR_BGR2RGB);
Img = QImage((const uchar*)(rgb.data), rgb.cols, rgb.rows, rgb.cols * rgb.channels(), QImage::Format_RGB888);
}
else
{
Img = QImage((const uchar*)(mat.data), mat.cols, mat.rows, mat.cols * mat.channels(), QImage::Format_Indexed8);
}
return Img;
}
QImage转Mat时,用QImage提供的format()方法判断数据类型,做好相应的数据转换
QImage ——> Mat:
Mat QImageToMat(QImage & image)
{
Mat mat;
switch (image.format())
{
case QImage::Format_ARGB32:
case QImage::Format_RGB32:
case QImage::Format_ARGB32_Premultiplied:
mat = Mat(image.height(), image.width(), CV_8UC4, (void*)image.constBits(), image.bytesPerLine());
break;
case QImage::Format_RGB888:
mat = Mat(image.height(), image.width(), CV_8UC3, (void*)image.constBits(), image.bytesPerLine());
cv::cvtColor(mat, mat, CV_BGR2RGB);
break;
case QImage::Format_Indexed8:
mat = Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine());
break;
}
}