1. 程式人生 > >QT+Opencv實現簡單的視訊播放及抓拍

QT+Opencv實現簡單的視訊播放及抓拍

原理很簡單,採用opencv庫cvQueryFrame函式獲取一幀,然後將該幀影象在QLabel顯示出來。為實現連續播放,採用定時器。

#ifndef CAMERA_H
#define CAMERA_H

#include <QtWidgets/QWidget>
#include <QTimer>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "ui_camera.h"

//namespace Ui
//{
//	class camera;
//}
class camera : public QWidget
{
	Q_OBJECT

public:
	camera(QWidget *parent = 0);
	~camera();

private Q_SLOTS:
	void OnTimerOut();
	void OnClicked();
	void OnCaptureClicked();
	void OnCaptureClose();

private:
	Ui::cameraClass ui;
	IplImage*	m_pFrame;
	QTimer*		m_pTimer;
	CvCapture*	m_pCapture;
	QImage*		m_pImage;
};

#endif // CAMERA_H
#include "camera.h"

camera::camera(QWidget *parent)
	: QWidget(parent)
	//ui(new Ui::camera)
{
	ui.setupUi(this);
	m_pCapture = NULL;
	m_pImage = new QImage();
	m_pTimer = new QTimer(this);
	connect(m_pTimer, SIGNAL(timeout()), this, SLOT(OnTimerOut()));
	connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(OnClicked()));
	connect(ui.btnCapture, SIGNAL(clicked()), this, SLOT(OnCaptureClicked()));
	connect(ui.btnclose, SIGNAL(clicked()), this, SLOT(OnCaptureClose()));
}

camera::~camera()
{

}

void camera::OnClicked()
{
	m_pCapture = cvCreateFileCapture("D://learn//1.mp4");
	m_pTimer->start(33);

}

void camera::OnTimerOut()
{
	m_pFrame = cvQueryFrame(m_pCapture);
	if (m_pFrame == NULL)
		return;
	QImage image((const uchar*)m_pFrame->imageData, m_pFrame->width, m_pFrame->height, QImage::Format_RGB888);
	ui.label->setPixmap(QPixmap::fromImage(image));
}

void camera::OnCaptureClicked()
{
	m_pFrame = cvQueryFrame(m_pCapture);
	if (m_pFrame == NULL)
		return;
	QImage image((const uchar*)m_pFrame->imageData, m_pFrame->width, m_pFrame->height, QImage::Format_RGB888);
	ui.label_2->setPixmap(QPixmap::fromImage(image));
}

void camera::OnCaptureClose()
{
	m_pTimer->stop();
	cvReleaseCapture(&m_pCapture);
}