ffmpeg와 ONVIF를 사용한 RTSP 영상 스트리밍
ONVIF는 목적상 스트리밍 용도로 사용하지는 않지만 사용하는 경우가 있기에 이번기회에 둘다 정리하려고 쓰는 글입니다. ONVIF, RTSP에 대한 설명으로 시작해서 ffmpeg, ONVIF python 환경 세팅과 테스트 코드 실행까지 해보는걸로 마무리하겠습니다
ONVIF와 RTSP
- ONVIF (Open Network Video Interface Forum):
- ONVIF는 네트워크 카메라 및 비디오 장비 간의 상호 운용성을 보장하기 위해 만든 표준
- 주로 카메라의 설정, 제어, 관리 등을 위해 사용함. 예를 들어, PTZ(팬, 틸트, 줌) 제어, 이벤트 알림, 비디오 분석 데이터 제공 등이 가능
- ONVIF를 통해 네트워크 카메라에서 사용할 수 있는 스트리밍 프로파일과 스트리밍 URL을 얻어냄
- RTSP (Real-Time Streaming Protocol):
- RTSP는 실시간 스트리밍 데이터를 전송하기 위한 프로토콜
- 주로 비디오 스트리밍을 위해 사용되며, 클라이언트가 서버에 스트리밍 미디어 세션을 설정하는 데 사용
- RTSP는 실시간 데이터를 제공하는 카메라와 같은 장치에서 데이터를 가져오는 데 사용
1. ffmpeg 스트리밍
Windows ffmpeg 설치
https://www.ffmpeg.org/download.html
Download FFmpeg
If you find FFmpeg useful, you are welcome to contribute by donating. More downloading options Git Repositories Since FFmpeg is developed with Git, multiple repositories from developers and groups of developers are available. Release Verification All FFmpe
www.ffmpeg.org
- OS 환경에 맞게 Windows 에서 'Windows builds from gyan.dev 클릭
ffmpeg RTSP 연결 예시코드
import cv2
import numpy as np
import ffmpeg
def stream_f(stream_url):
probe = ffmpeg.probe(stream_url)
cap_info = next(C for C in probe['streams'] if C['codec_type'] == 'video')
width = cap_info['width']
height = cap_info['height']
up, down = str(cap_info['r_frame_rate']).split('/')
fps = eval(up) / eval(down)
process = (
ffmpeg
.input(stream_url, fflags='nobuffer',flags='low_delay')
.output('pipe:', format='rawvideo', pix_fmt='rgb24')
.overwrite_output()
.run_async(pipe_stdout=True)
)
while True:
in_bytes = process.stdout.read(width * height * 3)
if not in_bytes:
break
frame = np.frombuffer(in_bytes, np.uint8).reshape([height, width, 3])
frame = cv2.resize(frame, (1280, 720))
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
cv2.imshow('Camera View', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
process.stdout.close()
process.wait()
cv2.destroyAllWindows()
if __name__ == "__main__":
stream_url = "rtsp_url"
stream_f(stream_url)
2. onvif 스트리밍
pip install onvif-zeep
- 패키지 다운로드 (패키지 파일을 통해 사용하는 방법)
git clone https://github.com/FalkTannhaeuser/python-onvif-zeep.git
GitHub - FalkTannhaeuser/python-onvif-zeep: ONVIF Client Implementation in Python 2+3 (using https://github.com/mvantellingen/py
ONVIF Client Implementation in Python 2+3 (using https://github.com/mvantellingen/python-zeep instead of suds as SOAP client) - FalkTannhaeuser/python-onvif-zeep
github.com
import cv2
from onvif import ONVIFCamera
def get_rtsp_url(host, port, user, password):
wsdl_dir = 'python-onvif-zeep/wsdl/'
camera = ONVIFCamera(host, port, user, password, wsdl_dir=wsdl_dir)
media_service = camera.create_media_service()
profiles = media_service.GetProfiles()
token = profiles[0].token
stream_uri = media_service.GetStreamUri({
'StreamSetup': {
'Stream': 'RTP-Unicast',
'Transport': {
'Protocol': 'RTSP'
}
},
'ProfileToken': token
})
return stream_uri.Uri
def stream_O(stream_url):
cap = cv2.VideoCapture(rtsp_url)
if not cap.isOpened():
print("connect fail")
else:
while True:
ret, frame = cap.read()
if not ret:
print("not frame")
break
cv2.imshow('ONVIF Camera Stream', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
host = "IP"
port = "port"
user = "USER"
password = "PW"
rtsp_url = get_rtsp_url(host, port, user, password)
stream_O(rtsp_url)
IP, port, User, PW는 따로 입력해주셔야합니다. 그리고 카메라에 따라 ONVIF는 제어 가능하도록 설정하는 과정이 필요합니다. 대게는 테스트 모드를 켜거나 URL을 통해 권한을 설정하도록 되어있음