python ffmpeg pipe交互

import os, sys, getopt
import numpy as np
import subprocess as sp

#command line parser
try:
    opts, args = getopt.getopt(sys.argv[1:], "i:s:",["help"])
except getopt.GetoptError:
    sys.exit()

for op, value in opts:
    if op == "-i":
        input_file = value
    elif op== "-s":
        widthheight = value.split('*')
        width = np.int(widthheight[0])
        height = np.int(widthheight[1])

# videoIO
FFMPEG_BIN = "/home/media/Downloads/ffmpeg/ffmpeg"
command_in = [ FFMPEG_BIN,
            '-i', input_file,
            '-f', 'rawvideo',
            '-s',str(width)+'*'+str(height),
            '-pix_fmt', 'bgr24',
            '-']
pipe_in = sp.Popen(command_in, stdout = sp.PIPE, bufsize = 10**8)

#这是处理每一帧图像的函数
def process(img):
    pass

# read width*height*3 bytes (= 1 frame)
while True:
    raw_image = pipe_in.stdout.read(width*height*3)
    image =  np.fromstring(raw_image, dtype='uint8')
    if(len(image)==0):
        break
    image = image.reshape((height,width,3)).copy()
    process(image)
    sys.stdout.write(image.tostring())
    pipe_in.stdout.flush()

参考

http://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-python-using-ffmpeg/ (这个代码有错)

https://stackoverflow.com/questions/38156265/getting-av-interleaved-write-frame-broken-pipe-error (对上一篇的修正)

https://stackoverflow.com/questions/5825173/pipe-raw-opencv-images-to-ffmpeg

你可能感兴趣的:(ffmpeg)