用python 向rtmp流服务器推流
代码
'''
python3
opencv
ffmpeg
rtmp 推流视频直播pipe:: Invalid argumentb
'''
import cv2
import subprocess
import shlex
class FfmpegRemp(object):
def __init__(self, rtmpfile, videoid):
self.rtmpUrl = "rtmp://127.0.0.1:1935/" + rtmpfile
self.video_stream_path = videoid
self.WIDTH = 640
self.HEIGHT = 420
self.FPS = 30.0
self.stat = True
def open_opencv(self):
cap = cv2.VideoCapture(self.video_stream_path, cv2.CAP_DSHOW)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.WIDTH)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.HEIGHT)
cap.set(cv2.CAP_PROP_FPS, self.FPS)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
return cap
def open_ffmpeg(self):
cap = self.open_opencv()
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
command = ['./ffmpeg.exe',
'-y',
'-f', 'rawvideo',
'-vcodec','rawvideo',
'-pix_fmt', 'bgr24',
'-s', "{}x{}".format(width, height),
'-r', str(fps),
'-i', '-',
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
'-preset', 'ultrafast',
'-f', 'flv',
self.rtmpUrl]
p = subprocess.Popen(command, stdin=subprocess.PIPE)
print(cap.isOpened())
while(cap.isOpened()):
ret, frame = cap.read()
if not ret:
print("Opening camera is failed")
break
elif not self.stat:
p.kill()
print("停止推流")
break
p.stdin.write(frame.tostring())
def close_ffmpeg(self):
self.stat = False
self.open_ffmpeg()
if __name__ == "__main__":
fr = FfmpegRemp("Live003", 1)
fr.open_ffmpeg()