This code can display the video feed processed by OpenCV using Qt.
#include <QApplication>
#include <QLabel>
#include <QTimer>
#include <QImage>
#include <QVBoxLayout>
#include <opencv2/opencv.hpp>
class VideoWindow : public QWidget {
public:
VideoWindow(cv::VideoCapture &videoCapture) : QWidget() {
layout = new QVBoxLayout(this);
label = new QLabel(this);
layout->addWidget(label);
this->videoCapture = &videoCapture;
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &VideoWindow::updateFrame);
timer->start(33);
}
private:
void updateFrame() {
cv::Mat frame;
if (!videoCapture->read(frame)) {
return;
}
cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
QImage img(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
label->setPixmap(QPixmap::fromImage(img));
}
QVBoxLayout *layout;
QLabel *label;
cv::VideoCapture *videoCapture;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
cv::VideoCapture videoCapture(11);
if (!videoCapture.isOpened()) {
qWarning("Error: Could not open video source");
return -1;
}
videoCapture.set(cv::CAP_PROP_FRAME_WIDTH,640);
videoCapture.set(cv::CAP_PROP_FRAME_HEIGHT,480);
VideoWindow window(videoCapture);
window.show();
return app.exec();
}
Please use the following command to compile the code:
g++ qt.cpp -o qt `pkg-config --cflags --libs opencv4` $(pkg-config --cflags --libs Qt5Widgets) -fPIC