Skip to content

Instantly share code, notes, and snippets.

@takidog
Created October 19, 2019 18:21
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save takidog/2c981c34d5d5b41c0d712f8ef4ac60d3 to your computer and use it in GitHub Desktop.
Save takidog/2c981c34d5d5b41c0d712f8ef4ac60d3 to your computer and use it in GitHub Desktop.
push RTSP stream with ffmpeg by python
I have not found information on the Internet to implement the python push RTSP stream, so I try it.
I think RTMP can get more way to make it.
:)
import cv2
import subprocess as sp
if __name__ == "__main__":
rtsp_server = 'rtsp://example.org:554/...' # push server (output server)
#pull rtsp data, or your cv cap. (input server)
cap = cv2.VideoCapture(
'rtsp://example.org:554/pull from me ')
sizeStr = str(int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))) + \
'x' + str(int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fps = int(cap.get(cv2.CAP_PROP_FPS))
command = ['ffmpeg',
'-re',
'-s', sizeStr,
'-r', str(fps), # rtsp fps (from input server)
'-i', '-',
# You can change ffmpeg parameter after this item.
'-pix_fmt', 'yuv420p',
'-r', '30', # output fps
'-g', '50',
'-c:v', 'libx264',
'-b:v', '2M',
'-bufsize', '64M',
'-maxrate', "4M",
'-preset', 'veryfast',
'-rtsp_transport', 'tcp',
'-segment_times', '5',
'-f', 'rtsp',
rtsp_server]
process = sp.Popen(command, stdin=sp.PIPE)
while(cap.isOpened()):
ret, frame = cap.read()
ret2, frame2 = cv2.imencode('.png', frame)
process.stdin.write(frame2.tobytes())
@heavenThunder
Copy link

Hi,
It seems you have to pass a source video as argument in line 7.
You can specify a device as follow:
cap = cv2.VideoCapture(0) #This is for devices like webcams
Or
cap = cv2.VideoCapture("~/videos/stream.mp4")

Yes, you can use any source to push RTSP stream.

This gist just push RTSP stream, any input source is available.

Is there any documentation about using ffmpeg command in the format you posted above? For example, for changing the size video to a minor quality

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment