参考链接:
https://blog.csdn.net/ustczhang/article/details/79030715
按照这篇博客来做的,中间还是遇到一些问题,可能之前的博客没有提及,我也纪录下来吧。
-------------------------------------------------------------------------------------------------------------------------------
Windows下Python调用海康SDK实时视频流获取:https://blog.csdn.net/weixin_41869700/article/details/104214134
----------------------------------------------------------------------------------------------------------------------------------------
window下可以直接使用官方编译好的,但是linux下环境依赖,需要自己编译安装。
下载链接: https://opencv.org/releases/page/3/
参考链接: https://docs.opencv.org/3.4.0/d7/d9f/tutorial_linux_install.html
# 安装依赖项:
sudo apt-get install build-essential
sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
# 编译安装。
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_opencv_world=True -D CMAKE_INSTALL_PREFIX=/usr/local ..
make -j8
sudo make install
如果安装了cuda9.0以上的话,以上方法可能会出错(反正我就出错了),以下是用cmake-gui去掉cuda依赖。
把python2依赖也去掉。
把opencv_world 勾上, 把所有lib都集中到一个, 然后Generate。
然后进行编译安装。
make -j8
sudo make install
最后进行环境变量配置。
# 新建配置文件
sudo gedit /etc/ld.so.conf.d/opencv.conf
# 输入下文保存
/usr/local/lib
# 使配置生效
sudo ldconfig
# 继续配置bash
sudo gedit /etc/bash.bashrc
# 输入下文保存
PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/home/rookie/opencv3.4/install/lib/pkgconfig
export PKG_CONFIG_PATH
#更新系统库缓存
source /etc/bash.bashrc
#更新数据库索引
sudo updatedb
下载页面: https://www.hikvision.com/cn/download_more_570.html
sudo apt install swig
该文件用于预编译 OpenCV 相关函数,是一系列.i后缀的文件。所用到的东西也就cpp的Mat格式python的numpy格式。
下载页面:https://github.com/renatoGarcia/opencv-swig
sudo apt-get install libboost-dev
sudo apt install codeblocks
HKIPcamera.cpp 和window的不太一样。 还有LinuxPlayM4.h, 需要在海康SDK包中找到,一起放入头文件目录incCn。
//HKIPcamera.cpp
#include
#include
#include
#include
#include
#include
#include
#include "HCNetSDK.h"
#include "LinuxPlayM4.h"
#include
#include
#define USECOLOR 1
#define WINAPI
using namespace cv;
using namespace std;
//--------------------------------------------
int iPicNum = 0;//Set channel NO.
LONG nPort = -1;
HWND hWnd = NULL;
pthread_mutex_t g_cs_frameList;
list g_frameList;
LONG lUserID;
NET_DVR_DEVICEINFO_V30 struDeviceInfo;
LONG lRealPlayHandle = -1;
void yv12toYUV(char *outYuv, char *inYv12, int width, int height, int widthStep)
{
int col, row;
unsigned int Y, U, V;
int tmp;
int idx;
//printf("widthStep=%d.\n",widthStep);
for (row = 0; row>1;
tmp = (row / 2)*(width / 2) + (col / 2);
// if((row==1)&&( col>=1400 &&col<=1600))
// {
// printf("col=%d,row=%d,width=%d,tmp=%d.\n",col,row,width,tmp);
// printf("row*width+col=%d,width*height+width*height/4+tmp=%d,width*height+tmp=%d.\n",row*width+col,width*height+width*height/4+tmp,width*height+tmp);
// }
Y = (unsigned int)inYv12[row*width + col];
U = (unsigned int)inYv12[width*height + width*height / 4 + tmp];
V = (unsigned int)inYv12[width*height + tmp];
// if ((col==200))
// {
// printf("col=%d,row=%d,width=%d,tmp=%d.\n",col,row,width,tmp);
// printf("width*height+width*height/4+tmp=%d.\n",width*height+width*height/4+tmp);
// return ;
// }
if ((idx + col * 3 + 2)> (1200 * widthStep))
{
//printf("row * widthStep=%d,idx+col*3+2=%d.\n",1200 * widthStep,idx+col*3+2);
}
outYuv[idx + col * 3] = Y;
outYuv[idx + col * 3 + 1] = U;
outYuv[idx + col * 3 + 2] = V;
}
}
//printf("col=%d,row=%d.\n",col,row);
}
//解码回调 视频为YUV数据(YV12),音频为PCM数据
void CALLBACK DecCBFun(int nPort, char * pBuf, int nSize, FRAME_INFO * pFrameInfo, void * nReserved1, int nReserved2)
{
long lFrameType = pFrameInfo->nType;
if (lFrameType == T_YV12)
{
#if USECOLOR
//int start = clock();
static IplImage* pImgYCrCb = cvCreateImage(cvSize(pFrameInfo->nWidth, pFrameInfo->nHeight), 8, 3);//???????????????????Y????????????
yv12toYUV(pImgYCrCb->imageData, pBuf, pFrameInfo->nWidth, pFrameInfo->nHeight, pImgYCrCb->widthStep);//????????????????RGB????????
static IplImage* pImg = cvCreateImage(cvSize(pFrameInfo->nWidth, pFrameInfo->nHeight), 8, 3);
cvCvtColor(pImgYCrCb, pImg, CV_YCrCb2RGB);
//int end = clock();
#else
static IplImage* pImg = cvCreateImage(cvSize(pFrameInfo->nWidth, pFrameInfo->nHeight), 8, 1);
memcpy(pImg->imageData, pBuf, pFrameInfo->nWidth*pFrameInfo->nHeight);
#endif
//printf("%d\n",end-start);
//Mat frametemp(pImg), frame;
//frametemp.copyTo(frame);
// cvShowImage("IPCamera",pImg);
// cvWaitKey(1);
pthread_mutex_lock(&g_cs_frameList);
Mat mat=cvarrToMat(pImg);
g_frameList.push_back(mat);
pthread_mutex_unlock(&g_cs_frameList);
#if USECOLOR
// cvReleaseImage(&pImgYCrCb);
// cvReleaseImage(&pImg);
#else
/*cvReleaseImage(&pImg);*/
#endif
//此时是YV12格式的视频数据,保存在pBuf中,可以fwrite(pBuf,nSize,1,Videofile);
//fwrite(pBuf,nSize,1,fp);
}
/***************
else if (lFrameType ==T_AUDIO16)
{
//此时是音频数据,数据保存在pBuf中,可以fwrite(pBuf,nSize,1,Audiofile);
}
else
{
}
*******************/
}
///实时流回调
void CALLBACK fRealDataCallBack(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer, DWORD dwBufSize, void *pUser)
{
DWORD dRet;
switch (dwDataType)
{
case NET_DVR_SYSHEAD: //系统头
if (!PlayM4_GetPort(&nPort)) //获取播放库未使用的通道号
{
break;
}
if (dwBufSize > 0)
{
if (!PlayM4_OpenStream(nPort, pBuffer, dwBufSize, 1024 * 1024))
{
dRet = PlayM4_GetLastError(nPort);
break;
}
//设置解码回调函数 只解码不显示
if (!PlayM4_SetDecCallBack(nPort, DecCBFun))
{
dRet = PlayM4_GetLastError(nPort);
break;
}
//设置解码回调函数 解码且显示
//if (!PlayM4_SetDecCallBackEx(nPort,DecCBFun,NULL,NULL))
//{
// dRet=PlayM4_GetLastError(nPort);
// break;
//}
//打开视频解码
if (!PlayM4_Play(nPort, hWnd))
{
dRet = PlayM4_GetLastError(nPort);
break;
}
//打开音频解码, 需要码流是复合流
// if (!PlayM4_PlaySound(nPort))
// {
// dRet=PlayM4_GetLastError(nPort);
// break;
// }
}
break;
case NET_DVR_STREAMDATA: //码流数据
if (dwBufSize > 0 && nPort != -1)
{
BOOL inData = PlayM4_InputData(nPort, pBuffer, dwBufSize);
while (!inData)
{
sleep(10);
inData = PlayM4_InputData(nPort, pBuffer, dwBufSize);
cout << (L"PlayM4_InputData failed \n") << endl;
}
}
break;
}
}
void CALLBACK g_ExceptionCallBack(DWORD dwType, LONG lUserID, LONG lHandle, void *pUser)
{
char tempbuf[256] = { 0 };
switch (dwType)
{
case EXCEPTION_RECONNECT: //预览时重连
printf("----------reconnect--------%d\n", time(NULL));
break;
default:
break;
}
}
bool OpenCamera(char* ip, char* usr, char* password)
{
lUserID = NET_DVR_Login_V30(ip, 8000, usr, password, &struDeviceInfo);
if (lUserID == 0)
{
cout << "Log in success!" << endl;
return TRUE;
}
else
{
printf("Login error, %d\n", NET_DVR_GetLastError());
NET_DVR_Cleanup();
return FALSE;
}
}
void * ReadCamera(void* IpParameter)
{
//---------------------------------------
//设置异常消息回调函数
NET_DVR_SetExceptionCallBack_V30(0, NULL, g_ExceptionCallBack, NULL);
//cvNamedWindow("Mywindow", 0);
//cvNamedWindow("IPCamera", 0);
//HWND h = (HWND)cvGetWindowHandle("Mywindow");
//h = cvNamedWindow("IPCamera");
//---------------------------------------
//启动预览并设置回调数据流
NET_DVR_CLIENTINFO ClientInfo;
ClientInfo.lChannel = 1; //Channel number 设备通道号
ClientInfo.hPlayWnd = NULL; //窗口为空,设备SDK不解码只取流
ClientInfo.lLinkMode = 1; //Main Stream
ClientInfo.sMultiCastIP = NULL;
LONG lRealPlayHandle;
lRealPlayHandle = NET_DVR_RealPlay_V30(lUserID, &ClientInfo, fRealDataCallBack, NULL, TRUE);
if (lRealPlayHandle<0)
{
printf("NET_DVR_RealPlay_V30 failed! Error number: %d\n", NET_DVR_GetLastError());
//return -1;
}
else
cout << "码流回调成功!" << endl;
sleep(-1);
//fclose(fp);
//---------------------------------------
//关闭预览
if (!NET_DVR_StopRealPlay(lRealPlayHandle))
{
printf("NET_DVR_StopRealPlay error! Error number: %d\n", NET_DVR_GetLastError());
return 0;
}
//注销用户
NET_DVR_Logout(lUserID);
NET_DVR_Cleanup();
//return 0;
}
void init(char* ip, char* usr, char* password){
pthread_t hThread;
cout << "IP:" << ip << " UserName:" << usr << " PassWord:" << password << endl;
NET_DVR_Init();
NET_DVR_SetConnectTime(2000, 1);
NET_DVR_SetReconnect(10000, true);
OpenCamera(ip, usr, password);
pthread_mutex_init(&g_cs_frameList, NULL);
//hThread = ::CreateThread(NULL, 0, ReadCamera, NULL, 0, 0);
pthread_create(&hThread, NULL, ReadCamera, NULL);
}
Mat getframe(){
Mat frame1;
pthread_mutex_lock(&g_cs_frameList);
while (!g_frameList.size()){
pthread_mutex_unlock(&g_cs_frameList);
pthread_mutex_lock(&g_cs_frameList);
}
list::iterator it;
it = g_frameList.end();
it--;
Mat dbgframe = (*(it));
(*g_frameList.begin()).copyTo(frame1);
frame1 = dbgframe;
g_frameList.pop_front();
//imshow("camera", frame1);
//waitKey(1);
g_frameList.clear();
pthread_mutex_unlock(&g_cs_frameList);
return(frame1);
}
void release(){
//close(hThread);
NET_DVR_StopRealPlay(lRealPlayHandle);
//注销用户
NET_DVR_Logout(lUserID);
NET_DVR_Cleanup();
}
//HKIPcamera.h
#include
using namespace cv;
void init(char* ip, char* usr, char* password);
Mat getframe();
void release();
// HKIPcamera.i
/* Example of wrapping a C function that takes a C double array as input using
* numpy typemaps for SWIG. */
%module HKIPcamera
%include
%cv_mat__instantiate_defaults
%header %{
/* Includes the header in the wrapper code */
#include "HKIPcamera.h"
%}
%include "HKIPcamera.h"
通过命令行使用 swig 生成HKIPcamera_wrap.cxx和HKIPcamera.py
文件(注意修改自己opencv的路径)。
swig -I/home/rookie/opencv3.4/install/include -python -c++ HKIPcamera.i
这次和window不一样,后面可能会出现编译成功,调用成功,登陆却返回错误码29的情况。所以先测试程序是否能正常运行。创建console application项目。使用的是Release x64, 别使用Debug版本。
int main()
{
char ip[] = "192.168.101.65";
char user[] = "admin";
char password[] = "admin";
init(ip, user, password);
Mat frame = getframe();
imshow("camera", frame);
waitKey();
}
添加依赖: 这里运行的依赖和后面创建动态链接库的依赖差不多。干脆就一起写了。反正也没事。
1、codeblocks已经建好的工程下右键——Build options——Linker settings——linker libraries中添加
(1)opencv的libopencv_world.so.3.4.0
(2)海康SDK中lib下所有的so文件(包括HCNetSDKCom中的)。
2、project – build option – search directories – Compiler中添加头文件
(1)opencv头文件 (2)海康头文件 (3)python头文件
3、 project – build option – search directories – Linker中添加 /usr/local/lib路径
4、 project – build option – Compiler settings – Other compiler options 添加 -fPIC
5、 主界面 – Settings – Compiler settings – linker settings – linker libraries 添加 /usr/lib/x86_64-linux-gnu/libpthread.a 右边 other linker options 添加 -lpthread
运行, 若出现:
就是动态链接库没有完全加载。代码中添加以下代码。
char cryptoPath[2048] = {0};
sprintf(cryptoPath, "/home/rookie/HKSDK/lib/libcrypto.so");
NET_DVR_SetSDKInitCfg(NET_SDK_INIT_CFG_LIBEAY_PATH, cryptoPath);
char sslPath[2048] = {0};
sprintf(sslPath, "/home/rookie/HKSDK/lib/libssl.so");
NET_DVR_SetSDKInitCfg(NET_SDK_INIT_CFG_SSLEAY_PATH, sslPath);
NET_DVR_LOCAL_SDK_PATH struComPath = {0};
sprintf(struComPath.sPath, "/home/rookie/HKSDK/lib/HCNetSDKCom"); //HCNetSDKCom文件夹所在的路径
NET_DVR_SetSDKInitCfg(NET_SDK_INIT_CFG_SDK_PATH, &struComPath);
1、右键工程-Add files,HKIPcameracpp,HKIPcamera.h,HKIPcamera_wrap.cxx加入到工程。
2、 按照上面方法添加依赖。
3、将HKIPcamera动态链接库地址添加进系统路径, 在/etc/ld.so.conf文件结尾添加网络sdk库的路径,如/XXX 和/XXX/HCNetSDKCom/,保存之后,然后执行ldconfig。
sudo gedit /etc/ld.so.conf
# 添加
/home/rookie/HKSDK/lib
/home/rookie/HKSDK/lib/HCNetSDKCom
# 保存退出
sudo ldconfig
4、最后右键工程build或者rebuild,就会在工程目录下HKIPcamera/bin/Release生成的so文件改名为_HKIPcamera.so文件。
将上面swig生成的HKIPcamera.py和_HKIPcamera.so放在同级目录,给python调用。
import HKIPcamera
import numpy as np
import cv2
ip = str('192.168.101.65') # 摄像头IP地址,要和本机IP在同一局域网
name = str('admin') # 管理员用户名
pw = str('admin') # 管理员密码
HKIPcamera.init(ip, name, pw)
while True:
fram = HKIPcamera.getframe()
cv2.imshow('frame', np.array(fram))
if cv2.waitKey(24) & 0xff == 27:
break
HKIPcamera.release()
ps:如果在docker中运行,可能出现一下错误
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
解决:
apt install libgl1-mesa-glx