OpenCV -- Mat 转 QImage 函数

OpenCV cv::Mat 转 QImage 函数,原来的版本会发生转换后失色的问题。

//格式转换: cv::Mat 转 QImage

QImage ImageMark::Mat2QImage(const cv::Mat &mat)
{
switch (mat.type())
   {
       // 8-bit, 4 channel
       case CV_8UC4:
           {
               QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_ARGB32);
               return image;
           }

        // 8-bit, 3 channel
        case CV_8UC3:
           {
               QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_RGB888);
               return image.rgbSwapped();
           }

        // 8-bit, 1 channel
       case CV_8UC1:
           {
               #if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
               QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_Grayscale8);
               #else
               static QVector<QRgb>  sColorTable;

               // only create our color table the first time
               if (sColorTable.isEmpty())
               {
                   sColorTable.resize( 256 );

                   for ( int i = 0; i < 256; ++i )
                   {
                       sColorTable[i] = qRgb( i, i, i );
                   }
               }

               QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_Indexed8 );
               image.setColorTable(sColorTable);
               #endif

               return image;
           }

       // wrong
       default:
           qDebug() << "ERROR: Mat could not be converted to QImage.";
           break;
   }
   return QImage();
}
posted @ 2020-11-13 14:03  手磨咖啡  阅读(1336)  评论(0编辑  收藏  举报