将视频帧传输到OpenCV映像,然后传输到FFmpeg

时间:2017-12-29 02:57:24

标签: python ffmpeg pipe

这里有一个类似的问题: Getting 'av_interleaved_write_frame(): Broken pipe' error

但是如果我想写数据该怎么办?

我将pipe_out.stdin.write(image.tostring())放在while循环中,就像这样

FFMPEG_BIN = "/home/media/Downloads/ffmpeg"
import subprocess as sp
import sys
width = 360
height = 240
command_in = [ FFMPEG_BIN,
            '-i', '/home/media/Videos/mytestvideo/zhou.avi',
            '-f', 'image2pipe',
            '-pix_fmt', 'bgr24',
            '-vcodec', 'rawvideo', '-']
pipe_in = sp.Popen(command_in, stdout = sp.PIPE, bufsize = 10**8)

command_out = [ FFMPEG_BIN,
        '-y', # (optional) overwrite output file if it exists
        '-f', 'rawvideo',
        '-vcodec','rawvideo',
        '-s', '360x240', # size of one frame
        '-pix_fmt', 'bgr24',
        '-r', '28', # frames per second
        '-i', '-', # The imput comes from a pipe
        '-an', # Tells FFMPEG not to expect any audio
        #'-vcodec', 'mpeg',
        'my_output_videofile.mp4' ]

pipe_out = sp.Popen( command_out, stdin=sp.PIPE, stderr=sp.PIPE)

import numpy
import cv2
import pylab
# read width*height*3 bytes (= 1 frame)
while True:
    raw_image = pipe_in.stdout.read(width*height*3)
    image =  numpy.fromstring(raw_image, dtype='uint8')
    image = image.reshape((height,width,3))
    pipe_in.communicate()
    pipe_out.stdin.write(image.tostring())
    pipe_out.communicate()
    pipe_in.stdout.flush()
    #cv2.imshow('image',image)
    #cv2.waitKey(0)
    # throw away the data in the pipe's buffer.


'''
pipe_in.stdin.close()
pipe_in.stderr.close()
pipe_in.wait()
pipe_out.stdout.close()
pipe_out.stderr.close()
pipe_out.wait()
'''
#pipe_out.stdin.write(image.tostring())

但是,输出视频只有1帧(输入视频的第一帧)

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

@Pureheart,尝试这样的事情:

import numpy
import cv2
import pylab
# read width*height*3 bytes (= 1 frame)
while True:
    t_end = time.time() + 15
    while time.time() < t_end:
        raw_image = pipe_in.stdout.read(width*height*3)
        image =  numpy.fromstring(raw_image, dtype='uint8')
        image = image.reshape((height,width,3))
        pipe_in.communicate()
        pipe_out.stdin.write(image.tostring())
        pipe_out.communicate()
        pipe_in.stdout.flush()

    proc.stdin.close()