本文记录Python 调用海康威视摄像头,开启预览画面的方法。
支持 RTSP(Runtime Stream Protocol)协议的摄像头可以很方便地用 opencv i调用
#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()
也可以用第三方 API 实现,不过这个 API 文档写的不好,网上资料也不多,我勉强搞了个能显示模糊图像的:
# 导入必要的库
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 没跑起来,后续更新吧。