3

I'm working with opencv and I have to integrate it to a Qt Gui, but I have some issue for showing the image in Qt ...

Here is the code that I'm using

#include <QApplication>
#include <QtGui>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

QImage const Mat2QImage(const cv::Mat& src){
  return QImage((unsigned char*)src.data, src.cols, src.rows, src.step, QImage::Format_RGB888);
}

int main(int argc, char **argv){

  QApplication app(argc, argv);
  cv::Mat src = cv::imread("lena.jpg");

  QLabel aLabel;
  QImage img = Mat2QImage(src);
  aLabel.resize(src.rows, src.cols);
  aLabel.setPixmap(QPixmap::fromImage(img));
  aLabel.show();

  return app.exec();

} 

And Here is the result : enter image description here

Note that if I change the format to QImage::FormatRGB32 I will get an empty window, I've also tried all the formats and that wasn't what I'm expacting ... Any idea about how to solve the issue ?

Thanks !

rednaks
  • 1,982
  • 1
  • 17
  • 23
  • 1
    well OpenCV uses this BGR thing and QT uses RGB, I think http://stackoverflow.com/questions/5026965/how-to-convert-an-opencv-cvmat-to-qimage will help you out ( espec calling `cvtColor(src, dst, CV_BGR2RGB)` before your Mat2QImage call – Najzero Jul 18 '13 at 10:28

1 Answers1

2

OpenCV saves the image in bgr format. This means the color values of the pixels are swapped. If you add this line to your program the image gets displayed correctly:

  img = img.rgbSwapped();
sietschie
  • 7,425
  • 3
  • 33
  • 54