qt opencv打开摄像头录取视频 截图 的代码
时间: 2023-09-03 19:10:34 浏览: 121
以下是使用Qt和OpenCV打开摄像头,录取视频和截图的代码:
mainwindow.h
```c++
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <opencv2/opencv.hpp>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_OpenCamera_clicked();
void on_pushButton_Record_clicked();
void on_pushButton_Screenshot_clicked();
private:
Ui::MainWindow *ui;
cv::VideoCapture cap;
cv::VideoWriter writer;
bool isRecording;
};
#endif // MAINWINDOW_H
```
mainwindow.cpp
```c++
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
isRecording(false)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_OpenCamera_clicked()
{
if(!cap.isOpened()){
cap.open(0);
if(cap.isOpened()){
ui->pushButton_OpenCamera->setText("Close Camera");
}
else{
QMessageBox::warning(this, "Error", "Failed to open camera.");
}
}
else{
cap.release();
ui->pushButton_OpenCamera->setText("Open Camera");
}
}
void MainWindow::on_pushButton_Record_clicked()
{
if(!cap.isOpened()){
QMessageBox::warning(this, "Error", "Please open camera first.");
return;
}
if(!isRecording){
QString filename = QFileDialog::getSaveFileName(this, "Save Video", ".", "Videos (*.avi)");
if(filename.isEmpty()){
return;
}
writer.open(filename.toStdString(), cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 25.0, cv::Size(cap.get(cv::CAP_PROP_FRAME_WIDTH), cap.get(cv::CAP_PROP_FRAME_HEIGHT)));
if(!writer.isOpened()){
QMessageBox::warning(this, "Error", "Failed to save video.");
return;
}
isRecording = true;
ui->pushButton_Record->setText("Stop Record");
}
else{
writer.release();
isRecording = false;
ui->pushButton_Record->setText("Start Record");
}
}
void MainWindow::on_pushButton_Screenshot_clicked()
{
if(!cap.isOpened()){
QMessageBox::warning(this, "Error", "Please open camera first.");
return;
}
cv::Mat frame;
cap.read(frame);
if(frame.empty()){
QMessageBox::warning(this, "Error", "Failed to get frame.");
return;
}
QString filename = QFileDialog::getSaveFileName(this, "Save Screenshot", ".", "Images (*.png *.jpg)");
if(filename.isEmpty()){
return;
}
cv::imwrite(filename.toStdString(), frame);
}
```
这个代码利用了Qt的UI设计,包含了三个按钮:打开摄像头,开始/停止录制和截图。打开摄像头使用OpenCV的VideoCapture类,录制视频使用VideoWriter类,截图则是读取一帧图像并使用imwrite函数保存。
希望这个代码对你有所帮助!
阅读全文