import cv2
import time
import multiprocessing as mp
# RTSP视频流地址
rtsp_url = "rtsp://192.168.1.6:8554/video"
def recovery_stream(cap,rtsp_url,retry_delay=10):
while True:
try:
print(f"正在重新连接RTSP流:{rtsp_url}...")
cap.release()
cap = cv2.VideoCapture(rtsp_url)
if cap.isOpened():
print(f"RTSP流恢复成功:{rtsp_url}")
return cap
except Exception as e:
print(f"尝试恢复RTSP流时遇到错误:{e}")
time.sleep(retry_delay) # 等待10秒
def image_put(q,rtsp_url):
# 创建VideoCapture对象,指定RTSP流地址
cap = cv2.VideoCapture(rtsp_url)
fps = cap.get(cv2.CAP_PROP_FPS)
print("FPS:", fps)
if not cap.isOpened():
print(f"无法打开RTSP流:{rtsp_url}")
cap = recovery_stream(cap,rtsp_url,retry_delay=10)
while True:
ret, frame = cap.read()
if not ret:
cap = recovery_stream(cap,rtsp_url,retry_delay=10)
ret,frame = cap.read()
while q.qsize() > 1:
try:
_ = q.get_nowait()
except Exception as e:
pass
q.put(frame)
# time.sleep(1/fps)
time.sleep(0.01)
def image_get(q, rtsp_url):
windowname = rtsp_url
cv2.namedWindow(windowname)
while True:
frame = q.get(block=True)
resized_frame = cv2.resize(frame, (640, 480))
cv2.imshow(windowname, resized_frame)
# 按'q'键退出循环
cv2.waitKey(1)
def run_multi_camera(rtsp_urls):
mp.set_start_method('spawn')
queues = [mp.Queue(maxsize=2) for _ in rtsp_urls]
processes = []
for queue,rtsp_url in zip(queues,rtsp_urls):
processes.append(mp.Process(target=image_put, args=(queue,rtsp_url)))
processes.append(mp.Process(target=image_get, args=(queue,rtsp_url)))
for process in processes:
process.daemon = True
process.start()
for process in processes:
process.join()
if __name__ == '__main__':
rtsp_urls = [
"rtsp://192.168.1.6:8554/video",
# "rtsp://192.168.1.6:8554/video",
]
run_multi_camera(rtsp_urls)
Python多进程读取多个RTSP视频流并显示
最新推荐文章于 2025-03-28 15:05:11 发布