In today's rapidly evolving technological landscape, integrating computer vision capabilities into graphical user interfaces is becoming increasingly common. One powerful combination for such applications is using the Qt framework along with the OpenCV library. Qt provides a robust and user-friendly interface, while OpenCV offers a comprehensive set of tools for computer vision tasks. This tutorial shows how to display webcam frames in Qt 6 application using OpenCV.
Prepare environment
Ensure that Qt and OpenCV are installed on the system. The vcpkg
package manager can be used for an easy installation process
Code
The following steps are performed in the code:
- Using OpenCV, the program initializes the default webcam and configures the frame width and height.
- The
QLabel
widget is created for displaying the captured frames, and its dimensions are specified. - The
timeout
signal of the timer is connected to a lambda function. This function captures a frame from the webcam, converts it to theQImage
, and then assigns it as theQPixmap
for the associatedQLabel
. - The timer is started with a timeout interval corresponding to 30 frames per second.
- Finally, the
QLabel
is displayed in the application window.
#include <QApplication>
#include <QLabel>
#include <QImage>
#include <QTimer>
#include <opencv2/opencv.hpp>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QSize size(640, 480);
cv::VideoCapture cap(0);
cap.set(cv::CAP_PROP_FRAME_WIDTH, size.width());
cap.set(cv::CAP_PROP_FRAME_HEIGHT, size.height());
if (!cap.isOpened()) {
std::cout << "Cannot open webcam" << std::endl;
return -1;
}
auto *imageLabel = new QLabel();
imageLabel->resize(size);
cv::Mat frame;
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&]() {
cap >> frame;
QImage qimg(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_BGR888);
imageLabel->setPixmap(QPixmap::fromImage(qimg));
});
timer.start(1000 / 30); // 30 fps
imageLabel->show();
return QApplication::exec();
}
Leave a Comment
Cancel reply