7

How can we convert directly cv::Mat to QPixmap without going through filename loading?

I have made some research about it but no hints!

As a first step, what I have tried is that I save the image, and then load it. But it's not what I want to have.

user2354422
  • 169
  • 1
  • 2
  • 8
  • You could probably use the function `QPixmap::loadFromData(...)` to load the field `cv::Mat::data` directly into the `QPixmap`. I never tried to do such a thing though. – Jehan May 07 '13 at 14:03
  • And by the way, [possible duplicate](http://stackoverflow.com/questions/5026965/how-to-convert-an-opencv-cvmat-to-qimage) since it's easy to switch between Qimage and QPixmap. – Jehan May 07 '13 at 14:06
  • And how to switch between QImage and QPixmap? – user2354422 May 07 '13 at 14:09
  • 1
    Cannot be easier: `QPixmap::fromImage()`. – Jehan May 07 '13 at 14:19

2 Answers2

13

Jehan is right.

For people referring to this thread in the future: First convert image from BGR(used by OpenCV) to RGB.

Then:

QPixmap::fromImage(QImage((unsigned char*) mat.data, mat.cols, mat.rows, QImage::Format_RGB888));
mehfoos yacoob
  • 408
  • 3
  • 9
  • You can also use QPixmap::fromImage(QImage((unsigned char*) mat.data, mat.cols, mat.rows, QImage::Format_RGB888).rgbswapped()); so you dont have to convert image before starting – Muhammet Ali Asan Sep 07 '15 at 15:32
  • This isn't working for Mat3b. What exactly could be the reason? – d34th4ck3r Jul 28 '17 at 11:07
  • QPixmap pix= QPixmap::fromImage(QImage((unsigned char*) img.data, img.cols, img.rows, QImage::Format_RGB888).rgbSwapped()); ui->mylable->setPixmap(pix); – Milind Morey Aug 30 '18 at 11:15
  • 1
    After Qt 5.14 there is a new QImage format [`QImage::Format_BGR888`](https://doc.qt.io/qt-5/qimage.html#Format-enum) so a better method is to specify the format as `QImage::Format_BGR888` and no need to convert colors now. – Yang Hanlin Feb 08 '21 at 14:12
3

Mehfoos Yacoob is right, that is the best way to convert a cv::Mat to a QPixmap. First, you need to convert the cv::Mat to a QImage, and then using the fromImage function, assign its result to a QPixmap. It is important to keep in mind the type of the cv::Mat in order to use the correct QImage format.

This is a little example of how to do it: http://asmaloney.com/2013/11/code/converting-between-cvmat-and-qimage-or-qpixmap/

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
  • as additional information to this solution (as told in http://stackoverflow.com/a/12312326/2590275) is that "some images won't show properly without it." -> add the mat.step as 4th parameter. The example linked above to [asmaloney](http://asmaloney.com/2013/11/code/converting-between-cvmat-and-qimage-or-qpixmap/) also includes that parameter it his calls. – wambach Mar 24 '16 at 13:12