我正在运行
rtsp-simple-server
,我正在尝试将相机馈送至 rtsp 流,但 VideoWriter
返回未打开。我做错了什么吗?
我创建了一个小样本,重现了问题。
import cv2
# camera index
camera_index = 0
# RTSP address
rtsp_address = "rtsp://localhost:8554/stream1"
# create a video capture object
cap = cv2.VideoCapture(camera_index)
# check if the capture object was successfully created
if not cap.isOpened():
print("Failed to open camera")
exit()
# create a video writer object
fourcc = cv2.VideoWriter_fourcc(*"H264")
try :
out = cv2.VideoWriter(rtsp_address, fourcc, 20.0,(int(cap.get(3)),int(cap.get(4))))
except Exception as ex :
print(ex)
# check if the video writer object was successfully created
if not out.isOpened():
print("Failed to open RTSP stream")
exit()
# loop through frames
while True:
# capture a frame from the camera
ret, frame = cap.read()
# check if the frame was successfully captured
if not ret:
print("Failed to capture frame")
break
# write the frame to the video writer object
out.write(frame)
# display the frame (optional)
cv2.imshow("frame", frame)
# wait for key press to exit
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# release resources
cap.release()
out.release()
cv2.destroyAllWindows()
对于 RTSP,我们需要使用以下编解码器格式,它对我有用 fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
更新程序
import cv2
camera_index = 0
rtsp_address = "rtsp://localhost:8554/stream1"
cap = cv2.VideoCapture(camera_index)
if not cap.isOpened():
print("Failed to open camera")
exit()
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
try :
out = cv2.VideoWriter('v21.avi', fourcc, 20.0, (int(cap.get(3)),int(cap.get(4))))
except Exception as ex :
print(ex)
if not out.isOpened():
print("Failed to open RTSP stream")
exit()
while True:
ret, frame = cap.read()
if not ret:
print("Failed to capture frame")
break
out.write(frame)
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
out.release()
cv2.destroyAllWindows()