前言
之前记录过,GStreamer与opencv实现rtsp推流实现,这次通过ffmpeg与opencv并且搭配ZLMediaKit实现rtsp推流。
代码
import cv2
import time
import subprocess as sp
import multiprocessing
class stream_pusher(object):
def __init__(self, rtmp_url=None, raw_frame_q=None):
self.rtmp_url = rtmp_url
self.raw_frame_q = raw_frame_q
fps = 20
width = 1920
height = 1080
self.command = ['ffmpeg',
'-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.rtmp_url]
def push_frame(self):
p = sp.Popen(self.command, stdin=sp.PIPE)
while True:
if not self.raw_frame_q.empty():
frame = self.raw_frame_q.get()
p.stdin.write(frame.tostring())
else:
time.sleep(0.01)
def run(self):
push_frame_p = multiprocessing.Process(target=self.push_frame, args=())
push_frame_p.daemon = True
push_frame_p.start()
if __name__ == '__main__':
cap = cv2.VideoCapture("rtsp://admin:admin110@192.168.2.64:554/main")
rtmpUrl = "rtmp://192.168.2.8/live/test666"
raw_q = multiprocessing.Queue()
my_pusher = stream_pusher(rtmp_url=rtmpUrl, raw_frame_q=raw_q)
my_pusher.run()
while True:
_, raw_frame = cap.read()
if not raw_q.full():
raw_q.put(raw_frame)
cv2.waitKey(1)
cap.release()
print('finish')
效果如下:
总结
工作中总会遇到各种问题,解决一个记录一个,向着更优秀的程序员迈进!!!继续加油喽!!! 如果阅读本文对你有用,欢迎一键三连呀!!! 2021年8月31日20:38:34
|