cv::Mat轉QImage導致影像色彩異常

乐吴發表於2024-05-07

問題:

 1 QPixmap MainWindow::opencvToQImage(const QString &str)
 2 {
 3     cv::Mat cvImage = cv::imread(str.toStdString(),cv::IMREAD_REDUCED_COLOR_2);
 4     cv::Mat resizeMat;
 5      cv::resize(cvImage, resizeMat, cv::Size(ui->label->width(),ui->label->height()), 0, 0, cv::INTER_AREA);
 6     QImage qtImage(resizeMat.data, resizeMat.cols, resizeMat.rows, resizeMat.step, QImage::Format_RGB888);
 7 resizeMat.rows, bytesPerLine, QImage::Format_RGB888);
 8 
 9     return QPixmap::fromImage(qtImage);
10 }

解決方法:

 1 QPixmap MainWindow::opencvToQImage(const QString &str)
 2 {
 3     cv::Mat cvImage = cv::imread(str.toStdString(),cv::IMREAD_REDUCED_COLOR_2);
 4     cv::Mat resizeMat;
 5      cv::resize(cvImage, resizeMat, cv::Size(ui->label->width(),ui->label->height()), 0, 0, cv::INTER_AREA);
 6     //QImage qtImage(resizeMat.data, resizeMat.cols, resizeMat.rows, resizeMat.step, QImage::Format_RGB888);
 7 //    qtImage.rgbSwapped();
 8 
 9     cv::cvtColor(resizeMat, resizeMat, cv::COLOR_BGR2RGB);
10 
11         // 計算 QImage 的步長
12         int bytesPerLine = resizeMat.cols * resizeMat.elemSize();
13 
14         // 建立 QImage
15         QImage qtImage((uchar*)resizeMat.data, resizeMat.cols, resizeMat.rows, bytesPerLine, QImage::Format_RGB888);
16 
17     return QPixmap::fromImage(qtImage);
18 }

相關文章