本文记录Python 调用海康威视摄像头,开启预览画面的方法。
准备工作
- 安装好 Python , Opencv-python
- 配置测试机与摄像头 IP,二者在同一个网段
rtsp
支持 RTSP(Runtime Stream Protocol)协议的摄像头可以很方便地用 opencv i调用
代码语言:txt复制#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 文档写的不好,网上资料也不多,我勉强搞了个能显示模糊图像的:
代码语言:txt复制# 导入必要的库
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.cnblogs.com/yszr/p/15954826.html
- https://blog.51cto.com/u_16099217/6482128
- https://huaweicloud.csdn.net/63806cb9dacf622b8df87ef6.html
- https://github.com/MissiaL/hikvision-client
- https://www.jianshu.com/p/2e37283f565d
- https://blog.csdn.net/john_and_jane/article/details/130747233
文章链接: https://cloud.tencent.com/developer/article/2419854