import subprocess as sp import time import cv2 import argparse # 解析参数 parser = argparse.ArgumentParser() parser.add_argument("-i","--inputUrl", help="url of input rtsp url", default="0", type=str, required=False) parser.add_argument("-r","--relayUrl", help="url of the video relay server", default="", type=str, required=True) parser.add_argument("-d","--debug", help="debug mode, True or False, set to False in prod env", default=False, type=bool, required=False) parser.add_argument("-s","--sampleInterval",help="sample 1 frame every n frames of the video, the bigger the more stuck", default=4, type=int,required=False) args = parser.parse_args() print(args) inputUrl = 0 if args.inputUrl=="0" else args.inputUrl relayUrl = args.relayUrl debug = args.debug sampleInterval = args.sampleInterval # 打开视频 cap=cv2.VideoCapture(inputUrl) # 执行ffmpeg管道命令 command= [ 'ffmpeg', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-pix_fmt', 'bgr24', '-s', '428x240', '-r','30', '-i', '-', '-r','30', '-q', '0', '-codec:v', 'mpeg1video', '-f', 'mpegts', relayUrl ] pipe = sp.Popen(command,stdin=sp.PIPE) # 启动推流子进程,不断推流 time.sleep(1) frame_counter = 0 while (cap.isOpened()): # print("+++++++++++++", frame_counter) ret, frame = cap.read() if not ret: print("not ret") break # 1. 图像写入管道 # 模n采样 if frame_counter%sampleInterval==0: try: frame = cv2.resize(frame, (428, 240)) if debug: cv2.imshow("debug",frame) if cv2.waitKey(1)==ord("q"): print("quit") break pipe.stdin.write(frame.tostring()) except Exception as e: print("may be broken pipe") print(e) break frame_counter = (frame_counter+1)%4 print("break out") cap.release() if debug: cv2.destroyAllWindows() pipe.terminate()