1.h文件中,添加头文件,变量和private slot的函数声明
#include <QtWidgets/QMainWindow>
#include "ui_VideoProcess.h"
#include <qtimer.h>
#include <opencv2/opencv.hpp>
using namespace cv;
class VideoProcess : public QMainWindow
{
Q_OBJECT
public:
VideoProcess(QWidget *parent = Q_NULLPTR);
private:
Ui::VideoProcessClass ui;
Mat frame; //这里Mat是一个opencv里的类,这个类定义的变量不用释放内存。
QTimer m_pTimer;//这里是后边用到的定时器。
VideoCapture capture;
private slots:
void on_click_openvideoButton();
void shipin();
void paizhao();
void on_click_stopvideoButton();
void on_click_saveButton();
};
2. .cpp文件: 添加相应头文件,信号和槽的连接,相应的槽函数定义
void VideoProcess::on_click_openvideoButton()
{
Mat rgbImage;
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Video"), ".", tr("Video Files(*.avi *.rmvb *.flv *.mp4 *.mov *.mkv)"));
if (fileName.isEmpty())
{
QMessageBox::information(this, "警告", "没有选择文件");
return;
}
string str = fileName.toStdString();
capture.open(str);
m_pTimer.start(100);//设置定时器间隔
}
void VideoProcess::shipin()
{
capture >> frame;//读取视频帧
cvtColor(frame, frame, CV_BGR2RGB);//图像格式转换,由于opencvRGB图片通道跟Qt的是反的,所以这里将RGB转换为BGR
QImage img((unsigned char *)frame.data, frame.cols, frame.rows, QImage::Format_RGB888);
img = img.scaled(ui.videodisplaylabel->width(), ui.videodisplaylabel->height(), Qt::IgnoreAspectRatio);
ui.videodisplaylabel->setPixmap(QPixmap::fromImage(img));
}
void VideoProcess::paizhao()
{
QImage img1((unsigned char *)frame.data, frame.cols, frame.rows, QImage::Format_RGB888);//把当前帧转化为QImage并显示
ui.savedImagelabel->setPixmap(QPixmap::fromImage(img1));//输出当前帧即为拍照。
ui.savedImagelabel->setScaledContents(true);//为了使图片大小适应label的大小。
}
void VideoProcess::on_click_saveButton()
{
const QPixmap *savedimg = ui.savedImagelabel->pixmap();
QString Path = QFileDialog::getSaveFileName(this, tr("Save Image"), "", tr("*.jpg *.png"));//这个函数是调用windows的存储窗口,后边是可以存储的类型。
if (Path.isEmpty())
{
return;
}
else
{
if (!(savedimg->save(Path)))//执行save函数。
{
QMessageBox::information(this, tr("Failed to save the image"), tr("Failed to save the image!"));
return;
}
}
}