公司要IPC設備有獲取RTSP流的需求,之前是用VLC工具直接拉取,不方便測試延時,網(wǎng)絡閃斷等功能。在網(wǎng)上找了一些大神的博客,綜合一下,寫了下面的代碼。
測試環(huán)境:
win10 + python3.7.3 + opencv-python 4.1.0.25
# 拉取rtsp流
import cv2
import time
import traceback
def delay_time(rtsp_url):
"""
獲取拉取到第一幀數(shù)據(jù)的時間
:return:
"""
start_time = time.time()
cap = cv2.VideoCapture(rtsp_url)
if cap.isOpened():
success, frame = cap.read()
cost_time = time.time()-start_time
print(f"拉取到第一幀數(shù)據(jù)用時:{cost_time}秒")
return cost_time
else:
print("拉取流地址失敗")
def pull_rtsp(rtsp_url, run_time=60, save_file=""):
"""
拉取視頻流
:param run_time: 拉取的時長,單位秒。默認為60秒
:param save_file: 保存的文件名不帶尾綴,格式為avi,默認空時,不保存拉取 視頻流
:return:
"""
videoWrite = False
cap = cv2.VideoCapture(rtsp_url)
# 獲取視頻分辨率
if save_file:
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
# 獲取視頻幀率
fps = int(cap.get(cv2.CAP_PROP_FPS))
print(f"視頻流的分辨率{size}, FPS:{fps}")
# 設置視頻格式
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# 調用VideoWrite()函數(shù)
videoWrite = cv2.VideoWriter(f"{save_file}.avi", fourcc, fps, size)
# 運行指定的時長
start_time = time.time()
while (time.time() - start_time) < run_time:
if cap.isOpened():
try:
success, frame = cap.read()
if not videoWrite is False:
videoWrite.write(frame)
cv2.imshow("frame", frame)
cv2.waitKey(1)
# 獲取視頻流異常后重新拉取
except Exception as e:
print(traceback.format_exc())
cap = cv2.VideoCapture(rtsp_url)
time.sleep(1)
else:
print("拉取流地址失敗")
print("拉取結束,退出程序")
if __name__ == "__main__":
rtsp_url = "rtsp://admin:Admin123@192.168.54.53:554/Streaming/Channels/101?transportmode=unicast&profile=Profile_2144508492"
delay_time(rtsp_url)
file_name = "video"
pull_rtsp(rtsp_url, run_time=60, save_file=file_name)