回调函数使用:以视频推拉流为例
h文件:
#ifndef RTSPCAMERA_H
#define RTSPCAMERA_H
#include <iostream>
#include <string.h>
using namespace std;
#define RTSPCAMERA extern "C" __declspec(dllexport)
struct rtspCameraData
{
int width;
int height;
int length;
unsigned char* data;
} ;
typedef void (*callback)(struct rtspCameraData* data);
RTSPCAMERA bool __stdcall openRtspCamera(string path, callback func);
RTSPCAMERA void __stdcall stopRtspCamera();
#endif // RTSPCAMERA_H
cpp文件:
#include "rtspcamera.h"
#include <opencv2/opencv.hpp>
using namespace cv;
static VideoCapture capture;
static Mat image;
static int frame_cnt = 0;
static bool isGetRtspCamera = false;
bool __stdcall openRtspCamera(string path, callback func)
{
capture.open(path);
if(!capture.isOpened())
return false;
isGetRtspCamera = true;
struct rtspCameraData data;
while (isGetRtspCamera) {
if((frame_cnt % 8) == 0) {
capture.read(image);
}
else {
capture.grab();
}
frame_cnt ++;
data.width = capture.get(CAP_PROP_FRAME_WIDTH);
data.height = capture.get(CAP_PROP_FRAME_HEIGHT);
data.data = image.data;
data.length = image.rows * image.cols * image.elemSize();
// cout<<"width: "<<data.width
// <<"\nheight: "<<data.height
// <<"\nsize: "<<data.length
// <<"\nfps: "<<capture.get(CAP_PROP_FPS)<<endl;
func(&data);
}
return true;
}
void __stdcall stopRtspCamera()
{
isGetRtspCamera = false;
capture.release();
}
main.cpp
#include <opencv2/opencv.hpp>
#include "rtspcamera.h"
using namespace cv;
int ss = 0;
void getCameraData(struct rtspCameraData *cameradata)
{
//while(true) {
Mat image = cv::Mat(cameradata->height, cameradata->width, CV_8UC3, cameradata->data);
//namedWindow("image", WINDOW_AUTOSIZE);
//imshow("image", image);
ss ++;
QString str = QString::number(ss) + ".png";
imwrite(str.toStdString(), image);
// cout<<"width: "<<cameradata->width
// <<" height: "<<cameradata->height
// <<" size: "<<cameradata->length
// <<" data: "<<cameradata->data<<endl;
//waitKey(1);
//}
}
int main(int argc, char *argv[])
{
bool ret = openRtspCamera("rtsp://admin:admin@192.168.1.110:554/ch1/main/av_stream", getCameraData);
if(ret == false) {
cout<<"open rtsp error."<<endl;
}
while (true) {
waitKey(1);
}
stopRtspCamera();
return 0;
}