Qt, a powerful cross-platform application framework, provides developers with a versatile toolkit for creating graphical user interfaces (GUIs) and handling various multimedia tasks. When it comes to working with video in Qt applications, integrating OpenCV can make a big difference. OpenCV, an open-source computer vision library, offers a wide range of tools for image and video processing. This tutorial explains how to display video in Qt 6 application using OpenCV.
Prepare environment
Make sure to have Qt and OpenCV installed on the system. You can simplify the installation process by utilizing the vcpkg
package manager.
Code
The following steps are performed in the code:
- Using OpenCV, the
VideoCapture
object is initialized to capture frames from a video file. - A
QLabel
widget is created, intended for the display of video frames. The widget size is changed to match the width and height of the video frames. - A connection is established between the
timeout
signal of the timer and a lambda function. This lambda function is responsible for capturing the video frames, checking for the end of the video, converting the frame to aQImage
, and assigning it as theQPixmap
for the associatedQLabel
. - The timer is started with a frequency determined by the frames per second (FPS) of the video, ensuring a consistent update rate for the display.
- The
QLabel
widget is displayed, making the graphical user interface visible.
#include <QApplication>
#include <QLabel>
#include <QImage>
#include <QTimer>
#include <opencv2/opencv.hpp>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
cv::VideoCapture cap("test.mp4");
if (!cap.isOpened()) {
std::cout << "Cannot open video file" << std::endl;
return -1;
}
auto width = (int) cap.get(cv::CAP_PROP_FRAME_WIDTH);
auto height = (int) cap.get(cv::CAP_PROP_FRAME_HEIGHT);
auto *imageLabel = new QLabel();
imageLabel->resize(width, height);
cv::Mat frame;
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&]() {
cap >> frame;
if (frame.empty()) {
timer.stop();
}
QImage qimg(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_BGR888);
imageLabel->setPixmap(QPixmap::fromImage(qimg));
});
timer.start(1000 / (int) cap.get(cv::CAP_PROP_FPS));
imageLabel->show();
return QApplication::exec();
}
Leave a Comment
Cancel reply