Python调用海康SDK抓取红外图像

Python调用海康SDK抓取红外图像

2 年前 · 来自专栏 Python使用经验

海康SDK提供了C++、C#、Java等示例代码,可以使用这些语言进行二次开发。对于做算法开发的人来说,就想快速采集到图像,然后在Matlab或Python里对图像进行分析,使用C++、C#、Java就小题大做了。所以能不能使用Python访问海康SDK快速抓取图像呢?答案是可以的。

Github上有人提供了一个示例,使用ctypes模块调dll:

不过示例只给了抓取jpg图像的方法,如果想抓取红外相机的原始温度数据就得自己编写代码添加功能。

为此对代码进行封装,实现了抓取红外数据的功能,封装代码比较长,就不贴了。使用代码如下

import cv2
import datetime
import numpy as np
import scipy.io as sio
from utils import HKCapture # SDK封装
def temp2gray(timg, clim=[]):
    ''' 温度数据转灰度 '''
    if len(clim)==0:
        clim = [timg.min(), timg.max()]
    img = (timg-clim[0])/(clim[1]-clim[0])*255
    img[img>255]=255
    img[img<0]=0
    img = img.astype('uint8')
    return img
if __name__ == "__main__":
    hk = HKCapture(strDllPath='./dll/HCNetSDK.dll')
    ip = "192.168.7.1"
    username = 'admin'
    password = '123456'
    hk.login(ip, username, password)
    # 抓取红外图像
    if 1:
        suss, errinfo, res = hk.capture()
        if suss == 0:
            print("采集失败!(Errinfo:%s)"%errinfo)
        else:
            print("采集成功!")
            timg = res['timg']
            img = temp2gray(timg)
            img = cv2.applyColorMap(img, cv2.COLORMAP_HOT)
            cv2.imshow("capture", img)
            cv2.waitKey(0)
            cv2.destroyAllWindows()
            sio.savemat('tmp/tmp.mat', {'timg':timg})
    else:
        while 1:
            suss, errinfo, res = hk.capture()
            if suss != 0:
                timg = res['timg']
                img = temp2gray(timg)
                img = cv2.applyColorMap(img, cv2.COLORMAP_HOT)
                cv2.imshow("capture", img)
                if cv2.waitKey(100) & 0xFF == ord('q'):
                    break
    hk.logout()

封装代码中加入了Matlab接口,可以方便的在Matlab中调用Python采集图像,进而在Matlab中开发图像处理算法:

%% 从海康相机采集图像
clear
close all
%% 重载python模块
%clear classes
%utils = py.importlib.import_module('utils');
%py.importlib.reload(utils);
%% 获取数据
dllpath = './dll/HCNetSDK.dll';
hk = py.utils.HKCapture(dllpath);
ip = '192.168.7.1';
username = 'admin';
password = '123456';
hk.login(ip, username, password)
% 采集图像
data = struct(hk.captureMatlab());
suss = double(data.suss);
h = double(data.shape{1});
w = double(data.shape{2});
timg = double(data.timg);
timg1 = reshape(timg, [w, h])';
hk.logout()