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();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM