cpp
复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
this->setWindowTitle("Video Play With Qt");
// 高斯混合背景处理,创建一个 MOG2 背景提取器并应用
ptrMOG = createBackgroundSubtractorMOG2(500, 16, false);
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(importFrame()));
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::on_btnPlay_clicked() {
capture.open("D:\\BaiduNetdiskDownload\\bike.avi");
double rate = capture.get(CAP_PROP_FPS);
double timerDelay = 1000 / rate;
timer->start(timerDelay);
}
void MainWindow::on_btnStop_clicked() {
timer->stop();
capture.release();
}
void MainWindow::importFrame() {
Mat currentFrame;
Mat grayFrame, foreGround;
capture >> currentFrame;
if (!currentFrame.empty()) {
qDebug() << "Video is running...";
Mat result = currentFrame.clone();
ptrMOG->apply(currentFrame, foreGround, 0.05);
threshold(foreGround, foreGround, 25, 255, THRESH_BINARY);
// 腐蚀操作消除噪声
Mat kernelErode = getStructuringElement(MORPH_RECT, Size(5, 5));
erode(foreGround, foreGround, kernelErode);
// 膨胀操作突出目标
Mat kernelDilate = getStructuringElement(MORPH_RECT, Size(11, 11));
dilate(foreGround, foreGround, kernelDilate);
// 框选运动目标
vector<vector<Point>>contours;
findContours(foreGround, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
for (uint64 i = 0; i < contours.size(); i++) {
rectangle(result, boundingRect(contours[i]), Scalar(0, 255, 255), 1);
}
cvtColor(result, result, COLOR_BGR2RGB);
QImage showVideo = QImage((const unsigned char*)(result.data), result.cols, result.rows, result.step, QImage::Format_RGB888);
ui->labelVideo->setPixmap(QPixmap::fromImage(showVideo.scaled(ui->labelVideo->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)));
} else {
qDebug() << "Play is over.";
timer->stop();
}
}