海康摄像头opencv实时回调

由于项目的需求,需要对海康摄像头进行取流操作。

#include 
#include 
#include 
#include 
using namespace std;
using namespace cv;

LONG nPort = -1;
HWND hWnd = NULL;
Mat image;

//解码回调 视频为YUV数据(YV12),音频为PCM数据
void CALLBACK DecCBFun(long nPort, char * pBuf, long nSize, FRAME_INFO * pFrameInfo, long nReserved1, long nReserved2)
{
	if (pFrameInfo->nType == T_YV12)
	{
		if (image.empty())
		{
			image.create(pFrameInfo->nHeight, pFrameInfo->nWidth, CV_8UC3);
		}
		Mat YUVImage(pFrameInfo->nHeight + pFrameInfo->nHeight / 2, pFrameInfo->nWidth, CV_8UC1, (unsigned char*)pBuf);

		cvtColor(YUVImage, image, COLOR_YUV2BGR_YV12);
		resize(image, image, Size(1000, 600));
		imshow("view", image);
		waitKey(15);
		YUVImage.~Mat();
	}
}

///实时流回调
void CALLBACK fRealDataCallBack_V30(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer, DWORD dwBufSize, void *pUser)
{
	switch (dwDataType)
	{
	case NET_DVR_SYSHEAD:    //系统头
		if (!PlayM4_GetPort(&nPort)) //获取播放库未使用的通道号
		{
			nPort = -1;
			break;
		}
		if (dwBufSize > 0)
		{
			//实时流播放模式
			if (!PlayM4_SetStreamOpenMode(nPort, STREAME_REALTIME))
				break;
			//打开流接口
			if (!PlayM4_OpenStream(nPort, pBuffer, dwBufSize, 1024 * 1024 * 8))
				break;
			//播放开始
			if (!PlayM4_Play(nPort, NULL))
				break;
			//设置解码回调函数 仅仅解码不显示
			if (!PlayM4_SetDecCallBack(nPort, DecCBFun))
				break;
		}
		break;
	case NET_DVR_STREAMDATA:   //码流数据
		if (dwBufSize > 0 && nPort != -1)
		{
			if (!PlayM4_InputData(nPort, pBuffer, dwBufSize))
				break;
		}
		break;
	}
}


int main() 
{
	/*设备SDK初始化*/
	NET_DVR_Init();
	NET_DVR_SetConnectTime(2000, 1);
	NET_DVR_SetReconnect(2000, true);
	NET_DVR_SetRecvTimeOut(5000);

	//---------------------------------------
	// 注册设备
	LONG lUserID;
	NET_DVR_DEVICEINFO_V30 struDeviceInfo;
	lUserID = NET_DVR_Login_V30("192.168.1.64", 8000, "admin", "123456", &struDeviceInfo);
	if (lUserID < 0)
	{
		printf("Login error, %d\n", NET_DVR_GetLastError());
		NET_DVR_Cleanup();
		return -1;
	}
	printf("Login success!\n");

	//--------------------------------------
	long lRealPlayHandle;
	//HWND hWnd = GetConsoleWindow(); //获取窗口句柄
	NET_DVR_PREVIEWINFO struPlayInfo = { 0 };
	struPlayInfo.hPlayWnd = NULL; //需要 SDK 解码时句柄设为有效值,仅取流不解码时可为空(设置回调函数)
	struPlayInfo.lChannel = 1; //预览通道号
	struPlayInfo.dwStreamType = 0; //0-主码流,1-子码流,2-码流 3,3-码流 4,以此类推
	struPlayInfo.dwLinkMode = 0; //0- TCP 方式,1- UDP 方式,2- 多播方式,3- RTP 方式,4-RTP/RTSP,5-RSTP/HTTP
	struPlayInfo.bBlocked = 0; //0- 非阻塞取流,1- 阻塞取流
	lRealPlayHandle = NET_DVR_RealPlay_V40(lUserID, &struPlayInfo,fRealDataCallBack_V30, NULL);
	if (lRealPlayHandle < 0) //预览失败
	{
		printf("NET_DVR_RealPlay_V40 error, %d\n", NET_DVR_GetLastError());
		NET_DVR_Logout(lUserID);
		NET_DVR_Cleanup();
		return-1;
	}
	Sleep(5000);
	//关闭预览
	NET_DVR_StopRealPlay(lRealPlayHandle);
	//注销用户
	NET_DVR_Logout(lUserID);
	//释放 SDK 资源
	NET_DVR_Cleanup();



	return 0;
}

 

你可能感兴趣的:(opencv)