【QT+OpenCV】常用的Mat格式和QImage格式互相转换
1.Mat格式转化成QImage格式
QImage Widget::MatToImage(Mat &m) //Mat格式转化QImage类型 { switch (m.type()) { //判断Mat的类型,从而返回不同类型的img case CV_8UC1:{ // 通过QImage::QImage(uchar *data, int width, int height, int bytesPerLine, // QImage::Format format, QImageCleanupFunction cleanupFunction = nullptr, //void *cleanupInfo = nullptr),主要修改后两个非默认的参数 QImage img((uchar*)m.data,m.cols,m.rows,m.cols*1,QImage::Format_Grayscale8); return img; } case CV_8UC3:{ QImage img((uchar*)m.data,m.cols,m.rows,m.cols*3,QImage::Format_RGB888); return img.rgbSwapped(); } case CV_8UC4:{ QImage img((uchar*)m.data,m.cols,m.rows,m.cols*4,QImage::Format_ARGB32); return img; } default:{ QImage img; return img; } } }
2.QImage格式转化成Mat格式
Mat fromImage(const QImage& image) { switch (image.format()) { case QImage::Format_RGB32: //8UC4 return Mat(image.height(),image.width(), CV_8UC4, (void*)image.bits(), image.bytesPerLine()); case QImage::Format_RGB888: //8UC3 return Mat(image.height(),image.width(), CV_8UC3, (void*)image.bits(), image.bytesPerLine()); case QImage::Format_Indexed8: //8UC1 return Mat(image.height(),image.width(), CV_8UC1, (void*)image.bits(), image.bytesPerLine()); default: break; } return Mat(); }