RTSP 실시간 영상을 python, opencv를 이용해 녹화할 수 있다.
python 3.8.16
opencv-python 4.7.0.72
import cv2
import time
from absl import app, flags
from absl.flags import FLAGS
flags.DEFINE_string("rtsp", None, "RTSP URL")
flags.DEFINE_boolean("display", False, "Display Video")
flags.DEFINE_integer("time", 10, "Recording time (sec)")
flags.DEFINE_string("output", "output.mp4", "Output path")
def record_rtsp(_argv):
# RTSP 영상을 불러옴.
print("Loading...")
video_capture = cv2.VideoCapture(FLAGS.rtsp)
# 웹캠 설정
width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = video_capture.get(cv2.CAP_PROP_FPS) % 100
fps = fps if fps > 0 else 2 #fps 정보가 없다면 fps = 2
if width + height < 1:
assert False, "올바른 RTSP URL 인지 확인"
print(f"FPS: {fps}")
print(f"Recording time: {FLAGS.time} sec")
# 저장할 video 코덱 설정 (mp4) 및 VideoWriter 정의
fourcc = cv2.VideoWriter_fourcc("m", "p", "4", "v")
out = cv2.VideoWriter(FLAGS.output, fourcc, fps, (width, height))
# 녹화
print("Processing...")
start_time = time.time()
while True:
ret, frame = video_capture.read()
# 영상 가져오기 실패시 에러
assert ret, "영상 로딩 실패"
# Display RTSP streaming
if FLAGS.display:
cv2.imshow("streaming video", frame)
#Write
out.write(frame)
if time.time() - start_time >= FLAGS.time:
break
video_capture.release()
out.release()
cv2.destroyAllWindows()
print("END!")
if __name__ == "__main__":
app.run(record_rtsp)
python {python file path} -rtsp "{rtsp url}" -time {recoding time}
(예시)
python .\record_rtsp.py -rtsp "rtsp://admin: ..." -time 60