I am trying to capture images continuously so I can send them using UDP. I am doing this to implement a live video streaming program.
The code below captures images continuously and assigns images to QGraphicsScene so I can test if images play like a video. But when I run the program my computer freezes after couple seconds even though I delete the pointers. How can I fix this problem ?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
cam = new QCamera;
cam->setCaptureMode(QCamera::CaptureStillImage);
viewfinder = new QCameraViewfinder;
viewfinder->show();
QCameraImageCapture *cap = new QCameraImageCapture(cam);
cap->setCaptureDestination(QCameraImageCapture::CaptureToBuffer);
cam->setViewfinder(viewfinder);
QObject::connect(cap, &QCameraImageCapture::imageCaptured, [=] (int id, QImage img) {
while(true){
QByteArray *buf = new QByteArray;
QBuffer *buffer=new QBuffer(buf);
buffer->open(QIODevice::WriteOnly);
img.save(buffer, "BMP");
QPixmap *pixmap = new QPixmap();
pixmap->loadFromData(buffer->buffer());
scene->addPixmap(*pixmap);
delete buf;
delete buffer;
delete pixmap;
QThread::sleep(0.0416);
cap->capture();
}
});
QObject::connect(cap, &QCameraImageCapture::readyForCaptureChanged, [=] (bool state) {
if(state == true) {
cam->searchAndLock();
cap->capture();
cam->unlock();
}
});
cam->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
I'm not familiar with
QCameraand related classes but thelambdayou connect theQCameraImageCapture::imageCapturedsignal to doesn't look correct. That signal is emitted when a single frame is ready for preview. In yourlambda, however, you have...That
whileloop never exits and will block theQtevent processing loop. Note, also, that the code chunk...is overkill and (unless I'm mistaken) basically amounts to...
So I think your
lambdashould be more like (untested)...