QImage和 Mat 转化

来源:互联网 发布:linux抓包工具 编辑:程序博客网 时间:2024/05/23 15:43
  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.setColorCount(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.         qDebug() << "CV_8UC4";  
  35.         // Copy input Mat  
  36.         const uchar *pSrc = (const uchar*)mat.data;  
  37.         // Create QImage with same dimensions as input Mat  
  38.         QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);  
  39.         return image.copy();  
  40.     }  
  41.     else  
  42.     {  
  43.         qDebug() << "ERROR: Mat could not be converted to QImage.";  
  44.         return QImage();  
  45.     }  
  46. }  
  47. cv::Mat QImage2cvMat(QImage image)  
  48. {  
  49.     cv::Mat mat;  
  50.     qDebug() << image.format();  
  51.     switch(image.format())  
  52.     {  
  53.     case QImage::Format_ARGB32:  
  54.     case QImage::Format_RGB32:  
  55.     case QImage::Format_ARGB32_Premultiplied:  
  56.         mat = cv::Mat(image.height(), image.width(), CV_8UC4, (void*)image.constBits(), image.bytesPerLine());  
  57.         break;  
  58.     case QImage::Format_RGB888:  
  59.         mat = cv::Mat(image.height(), image.width(), CV_8UC3, (void*)image.constBits(), image.bytesPerLine());  
  60.         cv::cvtColor(mat, mat, CV_BGR2RGB);  
  61.         break;  
  62.     case QImage::Format_Indexed8:  
  63.         mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine());  
  64.         break;  
  65.     }  
  66.     return mat;  
  67. }  
原创粉丝点击