Capture Image From Webcam in Qt 6 Application using OpenCV

Capture Image From Webcam in Qt 6 Application using OpenCV

In many applications, especially those involving computer vision, capturing images from a webcam is a common requirement. However, achieving this task efficiently while integrating it into a Qt application can pose challenges. Qt provides a robust framework for building cross-platform applications with a user interface, while OpenCV offers powerful tools for image processing and computer vision tasks. Combining these two frameworks allows developers to create applications with sophisticated image capture capabilities. This tutorial explains how to capture image from webcam in Qt 6 application using OpenCV.

The provided code sets up a Qt application that captures images from a webcam using OpenCV. It initializes a Qt application instance and sets the size for the image display area. Then, it creates a video capture object using OpenCV, setting the desired frame width and height. If the webcam fails to open, an error message is printed and the program exits.

A Qt widget is created to hold the image display label and a button for capturing images. Inside a timer callback function, frames from the webcam are continuously retrieved, converted to Qt image format, and displayed in the label. Upon clicking the capture button, the current frame is saved as an image file. Finally, the layout is set up, the window is displayed, and the Qt application event loop is started.

#include <QApplication>
#include <QLabel>
#include <QImage>
#include <QVBoxLayout>
#include <QTimer>
#include <QPushButton>
#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 *window = new QWidget();
    QLabel imageLabel;
    imageLabel.setFixedSize(size);
    QPushButton captureButton("Capture Image");

    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));
    });
    QObject::connect(&captureButton, &QPushButton::clicked, [&]() {
        cv::imwrite("image.jpg", frame);
    });

    timer.start(1000 / 30); // 30 fps

    QVBoxLayout layout(window);
    layout.addWidget(&captureButton);
    layout.addWidget(&imageLabel);
    window->setLayout(&layout);
    window->show();

    return QApplication::exec();
}

Leave a Comment

Cancel reply

Your email address will not be published.