首先声明一个解码类,解码出图像后调用回调
#include <iostream>
#include <string>
#include <cstdlib>
#include <opencv2\opencv.hpp>
#include <Windows.h>
#include <process.h>
using namespace std;
using namespace cv;
//利用回调函数在解码类中取图像数据
typedef void(*AVFunction)(Mat img); //定义回调函数类型
class MyCoder
{
public:
MyCoder(string VideoPath, void(*vfun)(Mat img));
~MyCoder();
private:
public:
bool m_bStart;
string mVideoPath;
AVFunction mCallFunction;
static unsigned _stdcall ThreadFunc(void* param);
};
MyCoder::MyCoder(string VideoPath, void(*vfun)(Mat img))
{
m_bStart = true;
mVideoPath = VideoPath;
mCallFunction = vfun;
HANDLE handle2 = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc, (void*)this, NULL, NULL);
}
MyCoder::~MyCoder()
{
}
unsigned MyCoder::ThreadFunc(void * param)
{
MyCoder * helper = (MyCoder*)param;
VideoCapture vcap(helper->mVideoPath);
if (!vcap.isOpened())
{
return -1;
}
while (helper->m_bStart)
{
Mat frame;
vcap >> frame;
if (frame.empty())
{
break;
}
helper->mCallFunction(frame);
waitKey(30);
}
}
再声明一个显示的类
class MyPlay
{
public:
MyPlay();
~MyPlay();
private:
public:
bool m_bStart;
void StartPlay(string VideoPath, int durtion);
//回调,需设为静态
static void CallFunction(Mat img);
};
MyPlay::MyPlay()
{
m_bStart = false;
}
MyPlay::~MyPlay()
{
m_bStart = false;
}
void MyPlay::CallFunction(Mat img)
{
//回调取数据显示
imshow("img", img);
}
void MyPlay::StartPlay(string VideoPath, int durtion)
{
m_bStart = true;
MyCoder * mCoder = new MyCoder(VideoPath, CallFunction);
int count = 0;
while (count<durtion)
{
count += 1;
Sleep(1000);
}
mCoder->m_bStart = false;
Sleep(1000);
m_bStart = false;
}
启动解码器,
int main()
{
MyPlay * player = new MyPlay();
player->StartPlay("video.mp4", 10);
return 0;
}