Qt的QImage 与 OpenCV的Mat 之间的转换

Mat转QImage

 1 Mat QImage2cvMat(QImage image)
 2 {
 3     cv::Mat mat;
 4     switch(image.format())
 5     {
 6     case QImage::Format_ARGB32:
 7     case QImage::Format_RGB32:
 8     case QImage::Format_ARGB32_Premultiplied:
 9         mat = cv::Mat(image.height(), image.width(), CV_8UC4, (void*)image.bits(), image.bytesPerLine());
10         break;
11     case QImage::Format_RGB888:
12         mat = cv::Mat(image.height(), image.width(), CV_8UC3, (void*)image.bits(), image.bytesPerLine());
13         cv::cvtColor(mat, mat, CV_BGR2RGB);
14         break;
15     case QImage::Format_Indexed8:
16         mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.bits(), image.bytesPerLine());
17         break;
18     }
19     return mat;
20 }

QImage转Mat

 1 QImage cvMat2QImage(const cv::Mat& mat)
 2 {
 3     // 8-bits unsigned, NO. OF CHANNELS = 1
 4     if(mat.type() == CV_8UC1)
 5     {
 6         QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
 7         // Set the color table (used to translate colour indexes to qRgb values)
 8         image.setNumColors(256);
 9         for(int i = 0; i < 256; i++)
10         {
11             image.setColor(i, qRgb(i, i, i));
12         }
13         // Copy input Mat
14         uchar *pSrc = mat.data;
15         for(int row = 0; row < mat.rows; row ++)
16         {
17             uchar *pDest = image.scanLine(row);
18             memcpy(pDest, pSrc, mat.cols);
19             pSrc += mat.step;
20         }
21         return image;
22     }
23     // 8-bits unsigned, NO. OF CHANNELS = 3
24     else if(mat.type() == CV_8UC3)
25     {
26         // Copy input Mat
27         const uchar *pSrc = (const uchar*)mat.data;
28         // Create QImage with same dimensions as input Mat
29         QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
30         return image.rgbSwapped();
31     }
32     else if(mat.type() == CV_8UC4)
33     {
34         // Copy input Mat
35         const uchar *pSrc = (const uchar*)mat.data;
36         // Create QImage with same dimensions as input Mat
37         QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);
38         return image.copy();
39     }
40     else
41     {
42         return QImage();
43     }
44 }

猜你喜欢

转载自www.cnblogs.com/ybqjymy/p/12801003.html