How to get camera frames from QCamera

205 views Asked by At

I want to get camera frames using Qt camera tools, and pass it to OpenCV.

I used the code below to read camera frames, which is compatible with Qt6.

{
    QApplication app(argc, argv);
    QLabel* label = new QLabel();
    label->setAlignment(Qt::AlignCenter);
    label->resize(300, 300);
    label->show();

    QMediaCaptureSession* captureSession = new QMediaCaptureSession();
    QCamera* camera = new QCamera;
    captureSession->setCamera(camera);
    QImageCapture* imageCapture = new QImageCapture();

    captureSession->setImageCapture(imageCapture);
    camera->start();

    QObject::connect(imageCapture, &QImageCapture::imageCaptured, [&](int id, const QImage &frame){
        Q_UNUSED(id);
        label->setPixmap(QPixmap::fromImage(frame.scaled(300, 300)));
        QImage image = frame.convertToFormat(QImage::Format_ARGB32);
        cv::Mat cvImage(image.height(), image.width(), CV_8UC4,(void *)image.constBits(), image.bytesPerLine());
        // some opencv codes
    });

    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, [&]() {
        imageCapture->capture();
    });
    timer.start();
    return app.exec();
}

Unfortunately, this code works well on some systems but is slow on others, so I need a better solution in for reading camera frames.

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QVideoWidget videoWidget;
    videoWidget.resize(300, 300);
    videoWidget.show();
    QCamera camera(QMediaDevices::defaultVideoInput());
    camera.start();
    QMediaCaptureSession mediaCaptureSession;
    mediaCaptureSession.setCamera(&camera);
    mediaCaptureSession.setVideoOutput(&videoWidget);
    QImageCapture imageCapture;
    return a.exec();
}

This code worked well on all systems, but I'm not sure how to extract camera frames from it.

0

There are 0 answers