Display Image in Qt 6 Application using OpenCV

Display Image in Qt 6 Application using OpenCV

Displaying an image in a Qt application using OpenCV can help to create applications that leverage the strengths of both libraries. OpenCV can be used to perform a wide range of operations on images. The processed images can be displayed in a Qt application for visualizing the results and monitor the progress of the processing. We can make the user interface more intuitive and user-friendly by displaying the results of the computer vision algorithms in a Qt application. The powerful and flexible applications can be created by combining the image display capabilities of OpenCV with the user interface capabilities of Qt.

This tutorial provides code example how to display image in Qt 6 application using OpenCV.

Prepare environment

Make sure you have installed Qt and OpenCV on the system. The vcpkg package manager can be used to install them.

Code

The following steps are performed in the code:

  • The image is loaded using OpenCV.
  • OpenCV image is converted to a QImage. The img.step argument specifies the number of bytes per row in the Mat image data. Some images can fail to display if img.step argument is missing. So, img.step is necessary to correctly convert the image data to a QImage. Since OpenCV stores the channels in BGR order, we need to provide QImage::Format_BGR888 format to the QImage constructor for the conversion to work properly.
  • The QPixmap is created from the QImage.
  • Finally, the QPixmap is displayed in a QLabel.
#include <QApplication>
#include <QLabel>
#include <QImage>
#include <opencv2/opencv.hpp>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    cv::Mat img = cv::imread("test.jpg");
    QImage qimg(img.data, img.cols, img.rows, img.step, QImage::Format_BGR888);

    auto *imageLabel = new QLabel();
    imageLabel->setPixmap(QPixmap::fromImage(qimg));
    imageLabel->show();

    return QApplication::exec();
}

Leave a Comment

Cancel reply

Your email address will not be published.