欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何使用Python和OpenCV通过FFmpeg实现实时RTSP流推送

最编程 2024-02-22 15:33:52
...

python-opencv基于ffmpeg实现rtsp推流

代码
import cv2
import subprocess


'''拉流url地址,指定 从哪拉流'''
# video_capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) # 自己摄像头
pull_url = 'rtsp://192.168.107.189/stream1' # "rtsp_address"
video_capture = cv2.VideoCapture(pull_url) # 调用摄像头的rtsp协议流
# pull_url = "rtmp_address"


'''推流url地址,指定 用opencv把各种处理后的流(视频帧) 推到 哪里'''
push_url = "rtsp://192.168.107.65:8554/room55"

width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(video_capture.get(cv2.CAP_PROP_FPS)) # Error setting option framerate to value 0. 
print("width", width, "height", height,  "fps:", fps) 


# command = [r'D:\Softwares\ffmpeg-5.1-full_build\bin\ffmpeg.exe', # windows要指定ffmpeg地址
command = ['ffmpeg', # linux不用指定
    '-y', '-an',
    '-f', 'rawvideo',
    '-vcodec','rawvideo',
    '-pix_fmt', 'bgr24', #像素格式
    '-s', "{}x{}".format(width, height),
    '-r', str(fps), # 自己的摄像头的fps是0,若用自己的notebook摄像头,设置为15、20、25都可。 
    '-i', '-',
    '-c:v', 'libx264',  # 视频编码方式
    '-pix_fmt', 'yuv420p',
    '-preset', 'ultrafast',
    '-f', 'rtsp', #  flv rtsp
    '-rtsp_transport', 'tcp',  # 使用TCP推流,linux中一定要有这行
    push_url] # rtsp rtmp  
pipe = subprocess.Popen(command, shell=False, stdin=subprocess.PIPE)

def frame_handler(frame):
    ...
    return frame


process_this_frame = True 
while True: # True or video_capture.isOpened():
    # Grab a single frame of video
    ret, frame = video_capture.read()

    # handle the video capture frame
    start = time.time()
    
    frame = frame_handler(frame) 
    
    # Display the resulting image. linux 需要注释该行代码
    # cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(delay=100) & 0xFF == ord('q'): #  delay=100ms为0.1s .若dealy时间太长,比如1000ms,则无法成功推流!
        break
    
    pipe.stdin.write(frame.tostring())
    # pipe.stdin.write(frame.tobytes())
    
video_capture.release()
cv2.destroyAllWindows()
pipe.terminate()

©著作权归作者所有,转载或内容合作请联系作者

推荐阅读