1. QImage转换成cv::Mat
cv::Mat QImage2cvMat(const QImage &image)
{
cv::Mat mat;
int temp = image.format(); //防止警告
switch(temp)
{
case QImage::Format_Grayscale8: // 灰度图,每个像素点1个字节(8位)
// Mat构造:行数,列数,存储结构,数据,step每行多少字节
mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine());
break;
case QImage::Format_ARGB32: // uint32存储0xAARRGGBB,pc一般小端存储低位在前,所以字节顺序就成了BGRA
case QImage::Format_RGB32: // Alpha为FF
case QImage::Format_ARGB32_Premultiplied:
mat = cv::Mat(image.height(), image.width(), CV_8UC4, (void*)image.constBits(), image.bytesPerLine());
break;
case QImage::Format_RGB888: // RR,GG,BB字节顺序存储
mat = cv::Mat(image.height(), image.width(), CV_8UC3, (void*)image.constBits(), image.bytesPerLine());
// opencv需要转为BGR的字节顺序
cv::cvtColor(mat, mat, cv::COLOR_RGB2BGR);
break;
case QImage::Format_RGBA64: // uint64存储,顺序和Format_ARGB32相反,RGBA
mat = cv::Mat(image.height(), image.width(), CV_16UC4, (void*)image.constBits(), image.bytesPerLine());
// opencv需要转为BGRA的字节顺序
cv::cvtColor(mat, mat, cv::COLOR_RGBA2BGRA);
break;
}
return mat;
}
2. cv::Mat转换成QImage
QImage cvMat2QImage(const cv::Mat &mat)
{
QImage image;
int temp = mat.type(); //防止警告
switch(temp )
{
case CV_8UC1:
// QImage构造:数据,宽度,高度,每行多少字节,存储结构
image = QImage((const unsigned char*)mat.data, mat.cols, mat.rows, mat.step, QImage::Format_Grayscale8);
break;
case CV_8UC3:
image = QImage((const unsigned char*)mat.data, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
image = image.rgbSwapped(); // BRG转为RGB
// Qt5.14增加了Format_BGR888
// image = QImage((const unsigned char*)mat.data, mat.cols, mat.rows, mat.cols * 3, QImage::Format_BGR888);
break;
case CV_8UC4:
image = QImage((const unsigned char*)mat.data, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);
break;
case CV_16UC4:
image = QImage((const unsigned char*)mat.data, mat.cols, mat.rows, mat.step, QImage::Format_RGBA64);
image = image.rgbSwapped(); // BRG转为RGB
break;
}
return image;
}
3. Pixmap转换成QImage
QImage Util::pix2img(QPixmap& p)
{
QImage qImage = p.toImage();
return qImage;
}
4. QImage转换成Pixmap
QPixmap Util::img2pix(QImage& p)
{
QPixmap qPixmap = QPixmap::fromImage(p);
return qPixmap;
}
5. Pixmap转换成cv:Mat
Mat Util::pix2mat(QPixmap& p)
{
QImage image = p.toImage();
cv::Mat mat = img2mat(image);
return mat;
}
6. cv:Mat转换成Pixmap
QPixmap Util::mat2pix(Mat& mat)
{
QImage image = mat2img(mat);
QPixmap pixmap = QPixmap::fromImage(image);
return pixmap;
}
参考: QT中常见QImage、Pixmap、Mat三种图像格式的转换_mat转qpixmap-CSDN博客
cv::Mat与QImage的互相转换_cvmat转qimage-CSDN博客