本文最后更新于:2024年5月23日 下午

本文记录Python 调用海康威视摄像头,开启预览画面的方法。

准备工作

  1. 安装好 Python , Opencv-python
  2. 配置测试机与摄像头 IP,二者在同一个网段

rtsp

支持 RTSP(Runtime Stream Protocol)协议的摄像头可以很方便地用 opencv i调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#coding=utf-8
import cv2

ip_str = '192.168.1.64'
rtsp_port = '554'

url = "rtsp://admin:password@" + ip_str + ":" + rtsp_port + "/Streaming/Channels/2"
cap = cv2.VideoCapture(url)
ret,frame = cap.read()
while ret:
ret,frame = cap.read()
cv2.imshow("frame",frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

cv2.destroyAllWindows()
cap.release()

hikvisionapi

也可以用第三方 API 实现,不过这个 API 文档写的不好,网上资料也不多,我勉强搞了个能显示模糊图像的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 导入必要的库
import cv2
from hikvisionapi import Client
import numpy as np
import io
from PIL import Image

def string_to_image(string, width, height):
image = Image.frombytes('RGB', (width, height), string)
return image

# 连接到摄像头
cam_ip = 'http://192.168.1.64'
cam_username = 'admin'
cam_password = 'password'
cam = Client(cam_ip, cam_username, cam_password)


# Dict response (default)
response = cam.System.deviceInfo(method='get')

# 打印设备的信息
print(response)


cam.Streaming.channels[101]

while True:
response = cam.Streaming.channels[101].picture(method='get', type='opaque_data')
response2 = cam.Streaming.channels[101].picture_url
data = response.iter_content(chunk_size=999999)
for chunk in data:
image = Image.open(io.BytesIO(chunk))
cv2.imshow('Video Stream', np.array(image))

# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break

官方例程

搞了半天都是 bug 没跑起来,后续更新吧。

参考资料



文章链接:
https://www.zywvvd.com/notes/study/camera-imaging/hk-python-video-preview/hk-python-video-preview/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Python 调用海康威视 摄像头 显示预览画面
https://www.zywvvd.com/notes/study/camera-imaging/hk-python-video-preview/hk-python-video-preview/
作者
Yiwei Zhang
发布于
2024年5月22日
许可协议