【Qt】格式转换: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(mat.step), QImage::Format_ARGB32);
                   return image;
               }

            // 8-bit, 3 channel
            case CV_8UC3:
               {
                   QImage image(mat.data, mat.cols, mat.rows, static_cast(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(mat.step), QImage::Format_Grayscale8);
                   #else
                   static QVector  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(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();
}

 

你可能感兴趣的:(OpenCV,Qt,Qt,OpenCV,Mat,QImage,转换)