回掉函数这块一直似懂非懂,现在理解依旧是:自己的函数,将地址交给别人去调用,具体执行什么内容,由自己决定,什么时候执行,由别人决定。
这几天有空,写了个小 demo 玩玩。
写了一个解码的类,将回调函数传入进去,处理解码数据。
回掉函数具体只是显示了当前帧图像。
解码类如下:
#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:
string mVideoPath;
AVFunction mCallFunction;
static unsigned _stdcall ThreadFunc(void* param);
};
MyCoder::MyCoder(string VideoPath, void(*vfun)(Mat img))
{
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 (vcap.isOpened())
{
Mat frame;
vcap >> frame;
if (frame.empty())
{
break;
}
helper->mCallFunction(frame);
waitKey(30);
}
}
调用如下:
void CallFunction(Mat img)
{
//回调取数据显示
imshow("img", img);
}
int main()
{
MyCoder * mCoder = new MyCoder("video.mp4", CallFunction);
int count = 0;
while (count<10)
{
count += 1;
Sleep(1000);
//waitKey(1000);
}
return 0;
}
执行10秒,不知道为啥 opencv 的时延函数失效了,用了 windows 的。