python調(diào)用海康sdk操作熱成像設(shè)備獲取對(duì)應(yīng)點(diǎn)溫度

Python調(diào)用号鲜Γ康sdk操作熱成像設(shè)備獲取對(duì)應(yīng)點(diǎn)溫度娶靡, 海康官方提供有Java版的sdk看锉,遺憾的是里面提供的api比較舊了新版的api需要根據(jù)c++版的開(kāi)發(fā)文檔自己寫(xiě)對(duì)應(yīng)的Python接口和類(lèi)姿锭。這對(duì)于不熟悉c++的開(kāi)發(fā)人員比較吃力。下面的代碼示例了通過(guò)翰常康的SDK獲取熱成像畫(huà)面上某一點(diǎn)的具體溫度呻此。hCNetSDK = CDLL('./libhcnetsdk.so')是海康sdk的目錄腔寡,可以是相對(duì)路徑也可以是絕對(duì)路徑趾诗。

1.dll動(dòng)態(tài)庫(kù)python函數(shù)封裝

from ctypes import c_int32, c_char_p, c_void_p, c_float, c_size_t, c_ubyte, c_long, cdll, POINTER, CDLL, c_bool, c_long, c_short
from hk_class import *
import sys

if 'linux' == sys.platform:
    hCNetSDK = CDLL('./libhcnetsdk.so')
else:
    hCNetSDK = CDLL('./HCNetSDK.dll')


SERIALNO_LEN = 48  # 序列號(hào)長(zhǎng)度
NAME_LEN = 32  # 用戶(hù)名長(zhǎng)度

# //boolean NET_DVR_Init();
NET_DVR_Init = hCNetSDK.NET_DVR_Init
NET_DVR_Init.restype = c_bool
NET_DVR_Init.argtypes = ()

# boolean NET_DVR_Cleanup();
NET_DVR_Cleanup = hCNetSDK.NET_DVR_Cleanup
NET_DVR_Cleanup.restype = c_bool
NET_DVR_Cleanup.argtypes = ()

# NativeLong NET_DVR_Login_V30(String sDVRIP, short wDVRPort, String sUserName, String sPassword, NET_DVR_DEVICEINFO_V30 lpDeviceInfo);
NET_DVR_Login_V30 = hCNetSDK.NET_DVR_Login_V30
NET_DVR_Login_V30.restype = c_long
NET_DVR_Login_V30.argtypes = (c_char_p, c_short, c_char_p, c_char_p, POINTER(NET_DVR_DEVICEINFO_V30))

# boolean NET_DVR_Logout_V30(NativeLong lUserID);
NET_DVR_Logout_V30 = hCNetSDK.NET_DVR_Logout_V30
NET_DVR_Logout_V30.restype = c_bool
NET_DVR_Logout_V30.argtypes = (c_long,)

# boolean NET_DVR_SetSTDConfig(NativeLong lUserID, int dwCommand, NET_DVR_STD_CONFIG lpInConfigParam);
NET_DVR_SetSTDConfig = hCNetSDK.NET_DVR_SetSTDConfig
NET_DVR_SetSTDConfig.restype = c_bool
NET_DVR_SetSTDConfig.argtypes = (c_long, c_int32, NET_DVR_STD_CONFIG)

# boolean NET_DVR_GetSTDConfig(NativeLong lUserID, int dwCommand, NET_DVR_STD_CONFIG lpOutConfigParam);
NET_DVR_GetSTDConfig = hCNetSDK.NET_DVR_GetSTDConfig
NET_DVR_GetSTDConfig.restype = c_bool
NET_DVR_GetSTDConfig.argtypes = (c_long, c_int32, NET_DVR_STD_CONFIG)

# boolean NET_DVR_CaptureJPEGPicture_WithAppendData(NativeLong lUserID, int lChannel, NET_DVR_JPEGPICTURE_WITH_APPENDDATA lpJpegWithAppend);
NET_DVR_CaptureJPEGPicture_WithAppendData = hCNetSDK.NET_DVR_CaptureJPEGPicture_WithAppendData
NET_DVR_CaptureJPEGPicture_WithAppendData.restype = c_bool
NET_DVR_CaptureJPEGPicture_WithAppendData.argtypes = (c_long, c_int32, POINTER(NET_DVR_JPEGPICTURE_WITH_APPENDDATA))

# int NET_DVR_GetLastError();
NET_DVR_GetLastError = hCNetSDK.NET_DVR_GetLastError
NET_DVR_GetLastError.restype = c_int32
NET_DVR_GetLastError.argtypes = ()

# 啟用日志文件寫(xiě)入接口
# boolean NET_DVR_SetLogToFile(int bLogEnable, String strLogDir, boolean bAutoDel);
NET_DVR_SetLogToFile = hCNetSDK.NET_DVR_SetLogToFile
NET_DVR_SetLogToFile.restype = c_bool
NET_DVR_SetLogToFile.argtypes = (c_int32, c_char_p, c_bool)


# 單幀數(shù)據(jù)捕獲并保存成JPEG存放在指定的內(nèi)存空間中。

# BOOL NET_DVR_CaptureJPEGPicture_NEW(
#   LONG                 lUserID,
#   LONG                 lChannel,
#   LPNET_DVR_JPEGPARA   lpJpegPara,
#   char                 *sJpegPicBuffer,
#   DWORD                dwPicSize,
#   LPDWORD              lpSizeReturned
# );
NET_DVR_CaptureJPEGPicture_new = hCNetSDK.NET_DVR_CaptureJPEGPicture_NEW
NET_DVR_CaptureJPEGPicture_new.restype = c_bool
NET_DVR_CaptureJPEGPicture_new.argtypes = (c_long, c_long, POINTER(NET_DVR_JPEGPARA), c_char_p, c_ulong, POINTER(c_ulong))

# BOOL NET_DVR_CaptureJPEGPicture_NEW(
#   LONG                 lUserID,
#   LONG                 lChannel,
#   LPNET_DVR_JPEGPARA   lpJpegPara,
#   char                 *sJpegPicBuffer,
#   DWORD                dwPicSize,
#   LPDWORD              lpSizeReturned
# );
NET_DVR_CaptureJPEGPicture = hCNetSDK.NET_DVR_CaptureJPEGPicture
NET_DVR_CaptureJPEGPicture.restype = c_bool
NET_DVR_CaptureJPEGPicture.argtypes = (c_long, c_long, POINTER(NET_DVR_JPEGPARA), c_char_p)

2.結(jié)構(gòu)體python類(lèi)封裝

from ctypes import *

SERIALNO_LEN = 48  # 序列號(hào)長(zhǎng)度
NAME_LEN = 32  # 用戶(hù)名長(zhǎng)度py

class NET_DVR_DEVICEINFO_V30(Structure):
    _fields_ = [('sSerialNumber', c_ubyte * SERIALNO_LEN), ('byAlarmInPortNum', c_byte), ('byAlarmOutPortNum', c_byte), ('byDiskNum', c_byte),
                ('byDVRType', c_byte), ('byChanNum', c_byte), ('byStartChan', c_byte), ('byAudioChanNum', c_byte), ('byIPChanNum', c_byte), ('byRes1', c_ubyte * 24)]

class NET_VCA_POINT(Structure):
    _fields_ = [('fX', c_float), ('fY', c_float)]

class NET_VCA_POLYGON(Structure):
    _fields_ = [('dwPointNum', c_ulong), ('struPos',NET_VCA_POINT * 10)] 

class NET_DVR_THERMOMETRY_PRESETINFO_PARAM(Structure):
    _fields_ = [('byEnabled', c_byte), ('byRuleID', c_short), ('wDistance', c_short), ('fEmissivity', c_float), ('byDistanceUnit', c_byte), ('byRes', c_ubyte * 2), ('byReflectiveEnabled', c_byte),
                ('fReflectiveTemperature', c_float), ('szRuleName', c_ubyte * NAME_LEN), ('byRes1', c_ubyte * 63), ('byRuleCalibType', c_byte), ('struPoint', NET_VCA_POINT), ('struRegion', NET_VCA_POLYGON)]

class NET_DVR_THERMOMETRY_PRESETINFO(Structure):
    _fields_ = [('dwSize', c_ulong), ('wPresetNo', c_short), ('byRes', c_ubyte * 2),
                ('struPresetInfo', NET_DVR_THERMOMETRY_PRESETINFO_PARAM * 40)]

class NET_DVR_THERMOMETRY_COND(Structure):
    _fields_ = [('dwSize', c_ulong), ('dwChannel', c_ulong),
                ('wPresetNo', c_short), ('byRes', c_ubyte * 62)]

class BYTE_ARRAY(Structure):
    _fields_ = [('byValue', c_byte * 2097152)]

class NET_DVR_STD_CONFIG(Structure):
    _fields_ = [('lpCondBuffer', POINTER(NET_DVR_THERMOMETRY_COND)), ('dwCondSize', c_ulong), ('lpInBuffer', POINTER(NET_DVR_THERMOMETRY_PRESETINFO)), ('dwInSize', c_ulong), ('lpOutBuffer', POINTER(NET_DVR_THERMOMETRY_PRESETINFO)), ('dwOutSize', c_ulong),
                ('lpStatusBuffer', POINTER(BYTE_ARRAY)), ('dwStatusSize', c_ulong), ('lpXmlBuffer', c_void_p), ('dwXmlSize', c_ulong), ('byDataType', c_bool), ('byRes', c_ubyte * 23)]

class NET_VCA_RECT(Structure):
    _fields_ = [('fX', c_char),('fY', c_char),('fWidth', c_char),('fHeight', c_char)]

class NET_DVR_JPEGPICTURE_WITH_APPENDDATA(Structure):
    _fields_ = [('dwSize', c_int32), ('dwChannel', c_int32), ('dwJpegPicLen', c_int32), ('pJpegPicBuff', POINTER(BYTE_ARRAY)), ('dwJpegPicWidth', c_int32),
                ('dwJpegPicHeight', c_int32), ('dwP2PDataLen', c_int32), ('pP2PDataBuff', POINTER(BYTE_ARRAY)), ('byIsFreezedata', c_byte), ('byRes', c_byte * 255)]

# JPEG圖像信息結(jié)構(gòu)體蹬蚁。

# struct{
#   WORD     wPicSize;
#   WORD     wPicQuality;
# }NET_DVR_JPEGPARA,*LPNET_DVR_JPEGPARA;

class NET_DVR_JPEGPARA(Structure):
    _fields_ = [('wPicSize', c_ulong),('wPicQuality', c_ulong)]

3.sdk自封裝

import hk_dll as hk_dll
import hk_class as hk_class
from ctypes import *
import struct
# from numba import njit

# 設(shè)備信息
m_strDeviceInfo = None

SERIALNO_LEN = 48  # 序列號(hào)長(zhǎng)度
NAME_LEN = 32  # 用戶(hù)名長(zhǎng)度py
point_bytes = (c_byte * 4)()

#用戶(hù)登錄信息

m_strDeviceInfo = None

#測(cè)溫信息

m_strJpegWithAppenData = None

# 初始化


def init():
    return hk_dll.NET_DVR_Init()

# 登錄


def login(ip, port, username, password):
    # 注冊(cè)
    m_strDeviceInfo = hk_class.NET_DVR_DEVICEINFO_V30()
    m_strDeviceInfo.sSerialNumber = (c_ubyte * SERIALNO_LEN)()
    m_strDeviceInfo.byRes1 = (c_ubyte * 24)()

    lUserID = hk_dll.NET_DVR_Login_V30(bytes(ip), port, bytes(username), bytes(password), byref(m_strDeviceInfo))

    # 打開(kāi)SDK寫(xiě)日志的功能
    hk_dll.NET_DVR_SetLogToFile(3, b'./sdklog', False)

    return lUserID

# 退出登錄


def logout(lUserID):
    hk_dll.NET_DVR_Logout_V30(lUserID)

# 釋放sdk


def cleanup():
    hk_dll.NET_DVR_Cleanup()

# 獲取抓拍圖片最高溫度


def get_temperature_all(lUserID):

    ret, m_strJpegWithAppenData = get_temperature0(lUserID)
    max_temperature = -50
    min_temperature = 120

    byValue = m_strJpegWithAppenData.pP2PDataBuff.contents.byValue

    if ret:
        for x in range(m_strJpegWithAppenData.dwJpegPicWidth):
            for y in range(m_strJpegWithAppenData.dwJpegPicHeight):

                temperature = struct.unpack('<f', struct.pack('4b', *get_bytes(byValue , (m_strJpegWithAppenData.dwJpegPicWidth * y + x) * 4, 4)))[0]

                max_temperature = temperature if temperature > max_temperature else max_temperature
                min_temperature = temperature if temperature < min_temperature else min_temperature

        return True, max_temperature, min_temperature

    return False, max_temperature, min_temperature

# 獲取給定點(diǎn)列表最高溫度


def get_temperature_max(points, sourceWidth, sourceHeight, lUserID):

    ret, m_strJpegWithAppenData = get_temperature0(lUserID)

    if(len(points) < 2):
        return False, -2

    if ret:
        x1, y1 = point2point(points[0][0], points[0][1], sourceWidth, sourceHeight,
                             m_strJpegWithAppenData.dwJpegPicWidth, m_strJpegWithAppenData.dwJpegPicHeight)

        x2, y2 = point2point(points[1][0], points[1][1], sourceWidth, sourceHeight,
                             m_strJpegWithAppenData.dwJpegPicWidth, m_strJpegWithAppenData.dwJpegPicHeight)

        if x1 > x2 or y1 > y2:
            return False, -3

        byValue = m_strJpegWithAppenData.pP2PDataBuff.contents.byValue

        max_temperature = -50.0
        for x in range(x1, x2 + 1):
            for y in range(y1, y2 + 1):
                # 160 * 120
                temperature = struct.unpack('<f', struct.pack('4b', *get_bytes(byValue,  (m_strJpegWithAppenData.dwJpegPicWidth * y + x) * 4, 4)))[0]
                max_temperature = temperature if temperature > max_temperature else max_temperature

        return True, max_temperature

    return False, -1

# 獲取某點(diǎn)的溫度


def get_temperature(x, y, sourceWidth, sourceHeight, lUserID):

    ret, m_strJpegWithAppenData = get_temperature0(lUserID)

    if ret:
        # m_strJpegWithAppenData.pP2PDataBuff.contents.byValue
        x, y = point2point(x, y, sourceWidth, sourceHeight, m_strJpegWithAppenData.dwJpegPicWidth, m_strJpegWithAppenData.dwJpegPicHeight)
        byValue = m_strJpegWithAppenData.pP2PDataBuff.contents.byValue

        return True, struct.unpack('<f', struct.pack('4b', *get_bytes(byValue, (m_strJpegWithAppenData.dwJpegPicWidth * y + x) * 4, 4)))[0]

    return False, 0.0

# 截取指定下標(biāo)的和長(zhǎng)度的返回?cái)?shù)據(jù)


def get_bytes(src_bytes, offset, length):
    global point_bytes

    for i in range(length):
        point_bytes[i] = src_bytes[offset + i]

    # del src_bytes

    return point_bytes


# 獲取溫度

def get_temperature0(lUserID):
    bRet = False
    global m_strJpegWithAppenData

    if m_strJpegWithAppenData is None:
        m_strJpegWithAppenData = hk_class.NET_DVR_JPEGPICTURE_WITH_APPENDDATA()
        m_strJpegWithAppenData.byRes = (c_byte * 255)()
        m_strJpegWithAppenData.dwChannel = 1
        m_strJpegWithAppenData.pJpegPicBuff = pointer(
            hk_class.BYTE_ARRAY((c_byte * 2097152)()))
        m_strJpegWithAppenData.pP2PDataBuff = pointer(
            hk_class.BYTE_ARRAY((c_byte * 2097152)()))
        m_strJpegWithAppenData.dwSize = sizeof(m_strJpegWithAppenData)

    bRet = hk_dll.NET_DVR_CaptureJPEGPicture_WithAppendData(lUserID, 2, byref(m_strJpegWithAppenData))

    if bRet:
        # 測(cè)溫?cái)?shù)據(jù)
        print(m_strJpegWithAppenData.dwP2PDataLen)
        if m_strJpegWithAppenData.dwP2PDataLen > 0:
            return True, m_strJpegWithAppenData

    return False, None

# 坐標(biāo)轉(zhuǎn)換
# @njit


def point2point(x, y, sourceWidth, sourceHeight, targetWidth, targetHeight):
    x = x * targetWidth / sourceWidth
    y = y * targetHeight / sourceHeight

    x = x if x <= targetWidth else targetWidth
    x = 0 if x < 0 else x

    y = y if y <= targetHeight else targetHeight
    y = 0 if y < 0 else y

    return int(x), int(y)

#抓拍圖片
# lUserID 登錄用戶(hù)id
# lChannel 渠道號(hào)
# dir 文件保存路徑
def captureJPEGPicture(lUserID, lChannel, dir):
    jpegpara= hk_class.NET_DVR_JPEGPARA()
    jpegpara.wPicSize = 0xff
    jpegpara.wPicQuality = 2

    p = c_char_p()
    s = byref(c_ulong())

    # return hk_dll.NET_DVR_CaptureJPEGPicture(lUserID, lChannel, byref(jpegpara), p, 2048, s)
    return hk_dll.NET_DVR_CaptureJPEGPicture(lUserID, lChannel, byref(jpegpara), dir)

def getLastError():
    return hk_dll.NET_DVR_GetLastError()

4.測(cè)試調(diào)用

import hk_sdk as hk_sdk
import hk_class as hkclass
import time


def test():
    result = hk_sdk.init()
    if not result:
        print('初始化失敗')
        return False
    print('初始化成功')
    lUserIDs = []

    lUserID = hk_sdk.login(b"192.168.8.16", 8000, b'admin', b'a1234567')
    if lUserID != -1:
        print('lUserID ', lUserID)
        lUserIDs.append(lUserID)

    time.sleep(5)

    lUserID = hk_sdk.login(b"192.168.8.15", 8000, b'admin', b'a1234567')
    if lUserID != -1:
        print('lUserID ', lUserID)
        lUserIDs.append(lUserID)

    for i in range(10):
        temperature_list = [[0, 0], [255, 255]]

        # result, max_temperature, min_temperature = hk_sdk.get_temperature_all();

        # if not result:
        #     print("獲取溫度失敗!")
        #     return False

        # print("max溫度是" , max_temperature,"min溫度是", min_temperature)
        userid = lUserIDs[int(i % 2)]
        result, temperature = hk_sdk.get_temperature_max(temperature_list, 1280, 720, userid)

        # result, temperature, m = hk_sdk.get_temperature_all();

        if result:
            print("獲取的溫度是", temperature, i)
        else:
            print("獲取溫度失敗 ", userid)

        time.sleep(1)

    # 退出登錄
    hk_sdk.logout(lUserIDs[0])

    # 釋放
    hk_sdk.cleanup()


if __name__ == "__main__":
    test()

好了代碼主要就這么多恃泪,喜歡的伙伴可以點(diǎn)贊留言加關(guān)注哦。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末犀斋,一起剝皮案震驚了整個(gè)濱河市贝乎,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌叽粹,老刑警劉巖览效,帶你破解...
    沈念sama閱讀 212,816評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異虫几,居然都是意外死亡锤灿,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)辆脸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)但校,“玉大人,你說(shuō)我怎么就攤上這事啡氢∽创眩” “怎么了术裸?”我有些...
    開(kāi)封第一講書(shū)人閱讀 158,300評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)亭枷。 經(jīng)常有香客問(wèn)我袭艺,道長(zhǎng),這世上最難降的妖魔是什么叨粘? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,780評(píng)論 1 285
  • 正文 為了忘掉前任猾编,我火速辦了婚禮,結(jié)果婚禮上升敲,老公的妹妹穿的比我還像新娘袍镀。我一直安慰自己,他們只是感情好冻晤,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,890評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著绸吸,像睡著了一般鼻弧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上锦茁,一...
    開(kāi)封第一講書(shū)人閱讀 50,084評(píng)論 1 291
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼雕拼。 笑死扬霜,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的稿存。 我是一名探鬼主播笨篷,決...
    沈念sama閱讀 39,151評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼瓣履!你這毒婦竟也來(lái)了率翅?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,912評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤袖迎,失蹤者是張志新(化名)和其女友劉穎冕臭,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體燕锥,經(jīng)...
    沈念sama閱讀 44,355評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡辜贵,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,666評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了归形。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片托慨。...
    茶點(diǎn)故事閱讀 38,809評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖暇榴,靈堂內(nèi)的尸體忽然破棺而出榴芳,到底是詐尸還是另有隱情嗡靡,我是刑警寧澤,帶...
    沈念sama閱讀 34,504評(píng)論 4 334
  • 正文 年R本政府宣布窟感,位于F島的核電站讨彼,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏柿祈。R本人自食惡果不足惜哈误,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,150評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望躏嚎。 院中可真熱鬧蜜自,春花似錦、人聲如沸卢佣。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)虚茶。三九已至戈鲁,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間嘹叫,已是汗流浹背婆殿。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,121評(píng)論 1 267
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留罩扇,地道東北人婆芦。 一個(gè)月前我還...
    沈念sama閱讀 46,628評(píng)論 2 362
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像喂饥,于是被迫代替她去往敵國(guó)和親消约。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,724評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容