簡介
opencv是一個開源計算機視覺庫,功能非常多,這裏簡單介紹一下OpenCV解碼播放Mp4文件,並將圖像顯示到Qt的QLabel上面。
核心代碼
頭文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
#include "opencv2/opencv.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgproc/types_c.h>
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
using namespace std;
using namespace cv;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void InitVideo();
private slots:
void on_play_clicked();
void playTimer();
void on_stop_clicked();
private:
Ui::MainWindow *ui;
QTimer *m_pTimer;
VideoCapture *m_pVideo;
};
#endif // MAINWINDOW_H
實現代碼
這裏需要注意的一點,Qt上顯示圖像的格式和OpenCV讀取的數據格式不一樣,需要轉換一下:
cv::cvtColor(frame, frame, COLOR_BGR2RGB);//圖像格式轉換
QImage disImage = QImage((const unsigned char*)(frame.data),frame.cols,frame.rows,frame.cols*frame.channels(),QImage::Format_RGB888);
ui->label->setPixmap(QPixmap::fromImage(disImage));//顯示圖像
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgproc/types_c.h>
using namespace cv;
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_pTimer = new QTimer;
m_pTimer->setInterval(30); //定時30毫秒讀取一幀數據
connect(m_pTimer, &QTimer::timeout, this, &MainWindow::playTimer);
ui->play->setEnabled(true);
ui->stop->setEnabled(false);
InitVideo();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::playTimer()
{
Mat frame;
//從cap中讀取一幀數據,存到fram中
*m_pVideo >> frame;
if ( frame.empty() )
{
return;
}
cv::cvtColor(frame, frame, COLOR_BGR2RGB);//圖像格式轉換
QImage disImage = QImage((const unsigned char*)(frame.data),frame.cols,frame.rows,frame.cols*frame.channels(),QImage::Format_RGB888);
ui->label->setPixmap(QPixmap::fromImage(disImage));//顯示圖像
}
void MainWindow::InitVideo()
{
m_pVideo = new VideoCapture("test.mp4");
}
void MainWindow::on_play_clicked()
{
m_pTimer->start();
ui->play->setEnabled(false);
ui->stop->setEnabled(true);
}
void MainWindow::on_stop_clicked()
{
ui->play->setEnabled(true);
ui->stop->setEnabled(false);
m_pTimer->stop();
}
控件
用於測試,界面比較簡單,中間是一個QLabel,下面兩個按鍵用於控制播放。
運行結果
錄屏工具效果不太好,實際上是很清晰的。
微信公衆號: