How to display a Mat image in Qt

You can use this method to convert an OpenCV Mat image to a Qt QImage which then can be easily turned into a QPixmap and then displayed on a QLabel. It might sound a little bit confusing but I’ll explain all of its parts. Check the method and my descriptions below:

Let’s say you have a OpenCV Mat variable named img:

Mat img;

And you have filled it with an actual image using OpenCV imread function:

img = imread("c:/test.jpg");


You should note that OpenCV always uses BGR color space by default but Qt, like many other programs and libraries, uses RGB so you have to convert the color space to match Qt’s. For this you can use OpenCV cvtColor function with CV_BGR2RGB parameter:

cvtColor(img, img, CV_BGR2RGB);

Now to be able to display your image you just need the following line of code. It is assumed that you have a QLabel named image_label on your window:

ui->image_lbl->setPixmap(QPixmap::fromImage(QImage(img.data, img.cols, img.rows, img.step, QImage::Format_RGB888)));

As you can see you can put the whole thing in a single line. First your OpenCV Mat image is converted to QImage and then to QPixmap, and finally setPixmap method of QLabel sets your image’s bitmap.



One Reply to “How to display a Mat image in Qt”

  1. What’s Going down i’m new to this, I stumbled upon this I’ve found It positively helpful and it has aided me out loads. I hope to give a contribution & assist other users like its helped me. Good job.|

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.