Python调用海康威视网络相机C++的SDK
本文参考:https://blog.youkuaiyun.com/c20081052/article/details/95082377 笔者将此文章中遗漏或未遇见的问题归纳总结,并分享自己在运行过程中遇到的问题,与君共勉。
一、运行环境
Win10系统 (64位)
Python3.7 (若是有用Python2.x版本的童鞋,尽量升级Python版本。在实验过程中,有其他童鞋由于Python版本问题,无法读取Python库)
Opencv3_4_2 、Visual Studio 2015(尽量使用同一版本)
海康硬件IDS-2DC7S420MW-A
海康SDK:CH-HCNetSDKV6.1.6.45_build20210302_win64
二、相关下载
建议在D盘或者E盘新建文件夹 ,名字为:App_install 。
1、海康SDK下载(文末有百度网盘,可自提)
下载地址:https://open.hikvision.com/download/5cda567cf47ae80dd41a54b3?type=10
选择自己对应的系统版本,笔者选的是设备网络SDK_Win64。
将其解压,主要会用到里面的头文件与库文件。将其汉语名称头文件改为include、库文件改为lib。
2、安装Opencv(文末有百度网盘,可自提)
笔者安装的是Opencv3_4_2。
在官网上下载3.4.2版本,双击即可解压。建议放到App_install文件夹,解压后将其bin路径添加到系统环境变量path下。
3、安装Swigwin(文末有百度网盘,可自提)
Swigwin是用来封装库的。
下载链接:http://www.swig.org/index.php
笔者选择的是3.0.12这个版本(本人之前选择的是最新版本,但是由于不明确的错误问题,还是按引用文章的版本安装),将其安装并解压到App_install目录下。
将此文件名路径添加到系统环境变量path中。
4、下载boost库(文末有百度网盘,可自提)
下载地址:https://www.boost.org/users/history/
笔者选择的是 boost_1_70_0.zip (因为本文主要是将win10环境下的), 将其解压到待会工程需要用的路径下即可;此处还是先解压到App_install文件夹下,待会会将解压后的文件夹拷贝到后面要用的路径下。
5、下载OpenCV-swig接口文件(文末有百度网盘,可自提)
下载地址:https://github.com/renatoGarcia/opencv-swig 将其下载并解压到App_install文件夹下。
需要用到其目录下lib文件夹中的文件opencv和opencv.i接口文件。
至此,前期准备工作搞定。App_install文件夹下的文件如下图:
三、实现步骤
1、使用swigwin编译生成Python和C++数据交换 的 .py和.cxx文件
复制以下三个文件(注意不要更改文件名),保存到同一文件夹下。笔者均将文件都放在新建文件夹 HicVision_python_SDK (建议名字一样)
HKIPcamera.h
#include <opencv2/opencv.hpp>
using namespace cv;
void init(char* ip, char* usr, char* password);
Mat getframe();
void release();
HKIPcamera.cpp
#include <opencv\cv.h>
#include <opencv\highgui.h>
#include <opencv2\opencv.hpp>
#include <iostream>
#include <time.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <windows.h>
#include "HCNetSDK.h"
#include "plaympeg4.h"
#define USECOLOR 1
using namespace cv;
using namespace std;
//--------------------------------------------
int iPicNum = 0;//Set channel NO.
LONG nPort = -1;
HWND hWnd = NULL;
CRITICAL_SECTION g_cs_frameList;
list<Mat> g_frameList;
LONG lUserID;
NET_DVR_DEVICEINFO_V30 struDeviceInfo;
HANDLE hThread;
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;
for (row = 0; row < height; row++)
{
idx = row * widthStep;
int rowptr = row * width;
for (col = 0; col < width; col++)
{
tmp = (row / 2)*(width / 2) + (col / 2);
Y = (unsigned int)inYv12[row*width + col];
U = (unsigned int)inYv12[width*height + width * height / 4 + tmp];
V = (unsigned int)inYv12[width*height + tmp];
outYuv[idx + col * 3] = Y;
outYuv[idx + col * 3 <