PyCharm中RTSP DESCRIBE请求返回401 Unauthorized问题求助
问题:OpenCV拉取RTSP流时遭遇401未授权错误
我尝试拉取RTSP视频流做人脸识别,同一个RTSP链接在VLC里能正常播放,但用OpenCV在PyCharm中运行时无法打开,报错401未授权。
我的代码
import cv2 import time # RTSP URL of the stream rtsp_url = "rtsp://********:*******@***.***.***.***:***" # Create a VideoCapture object cap = cv2.VideoCapture(rtsp_url) # Check if the camera opened successfully if not cap.isOpened(): print("Error: Unable to open RTSP stream.") exit() # Maximum number of retries max_retries = 3 retry_count = 0 # Read frames from the stream while True: # Read a frame ret, frame = cap.read() # Check if the frame was read successfully if ret: # Frame was successfully read, do something with it cv2.imshow('Frame', frame) else: # Frame read failed, increment retry count retry_count += 1 print(f"Failed to read frame. Retry count: {retry_count}/{max_retries}") # Check if maximum number of retries reached if retry_count >= max_retries: print("Maximum number of retries reached. Exiting.") break # Exit if 'q' is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # Add a delay before retrying time.sleep(1) # Release the VideoCapture object and close all windows cap.release() cv2.destroyAllWindows()
遇到的错误
pydev debugger: process 17812 is connecting Connected to pydev debugger (build 201.8538.36) Error: Unable to open RTSP stream. [rtsp @ 000001b3c7b02840] method DESCRIBE failed: 401 Unauthorized
解决方法
1. 显式设置认证参数
OpenCV的VideoCapture有时无法自动解析URL中的用户名密码,需要手动传入认证信息:
import cv2 import time rtsp_host = "***.***.***.***:***" username = "********" password = "*******" # 手动拼接带认证的URL,或单独设置参数 cap = cv2.VideoCapture(f"rtsp://{username}:{password}@{rtsp_host}") # 强制使用TCP传输,提升兼容性 cap.set(cv2.CAP_PROP_RTSP_TRANSPORT, cv2.CAP_RTSP_TRANSPORT_TCP)
2. 强制切换TCP传输
部分摄像头默认UDP传输可能存在权限校验问题,强制启用TCP:
cap = cv2.VideoCapture(rtsp_url) cap.set(cv2.CAP_PROP_RTSP_TRANSPORT, cv2.CAP_RTSP_TRANSPORT_TCP)
3. 检查FFmpeg兼容性
OpenCV依赖FFmpeg处理RTSP流,需确认:
- 当前Python环境的OpenCV编译时包含FFmpeg支持
- 运行
ffmpeg -protocols命令,确认输出中包含rtsp协议
4. 修正代码缩进错误
原代码存在缩进逻辑错误,while True循环内的代码未正确缩进,导致程序逻辑混乱,修正后的完整代码:
import cv2 import time rtsp_url = "rtsp://********:*******@***.***.***.***:***" cap = cv2.VideoCapture(rtsp_url) cap.set(cv2.CAP_PROP_RTSP_TRANSPORT, cv2.CAP_RTSP_TRANSPORT_TCP) if not cap.isOpened(): print("Error: Unable to open RTSP stream.") exit() max_retries = 3 retry_count = 0 while True: ret, frame = cap.read() if ret: cv2.imshow('Frame', frame) retry_count = 0 # 成功读取后重置重试计数 else: retry_count += 1 print(f"Failed to read frame. Retry count: {retry_count}/{max_retries}") if retry_count >= max_retries: print("Maximum number of retries reached. Exiting.") break time.sleep(1) # 处理退出按键 if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
内容的提问来源于stack exchange,提问作者Aref Yelghi
相关产品推荐
相关产品推荐

