使用python将opencv图像管道传输到ffmpeg [英] Pipe opencv images to ffmpeg using python

查看:787
本文介绍了使用python将opencv图像管道传输到ffmpeg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将openCV图像通过管道传输到ffmpeg(将ffmpeg作为子进程运行)? (我正在使用spyder/anaconda)

How can I pipe openCV images to ffmpeg (running ffmpeg as a subprocess)? (I am using spyder/anaconda)

我正在从视频文件中读取帧,并对每个帧进行一些处理.

I am reading frames from a video file and do some processing on each frame.

import cv2   
cap = cv2.VideoCapture(self.avi_path)
img = cap.read()
gray = cv2.cvtColor(img[1], cv2.COLOR_BGR2GRAY)
bgDiv=gray/vidMed #background division

然后,将处理后的帧通过管道传输到ffmpeg,我在一个相关问题中找到了该命令:

then, to pipe the processed frame to ffmpeg, I found this command in a related question:

sys.stdout.write( bgDiv.tostring() )

下一步,我正在尝试将ffmpeg作为子进程运行:

next, I am trying to run ffmpeg as a subprocess:

cmd='ffmpeg.exe -f rawvideo -pix_fmt gray -s 2048x2048 -r 30 -i - -an -f avi -r 30 foo.avi'
sp.call(cmd,shell=True)

(这也来自提到的帖子) 但是,这使我的IPython控制台充满了神秘的象形文字,然后使其崩溃.有什么建议吗?

(this also from the mentioned post) However, this fills my IPython console with cryptic hieroglyphs and then crashes it. any advice?

最后,我想输出4个流,并用ffmpeg对这4个流进行并行编码.

ultimately, I would like to pipe out 4 streams and have ffmpeg encode those 4 streams in parallel.

推荐答案

我曾经遇到过类似的问题. 我在Github上打开了一个问题,事实证明可能是平台问题.

I had similar problem once. I opened an issue on Github, turns out it may be a platform issue.

关于您的问题,您也可以将OpenCV图像传输到FFMPEG.这是示例代码:

Related to your question, you can as well pipe OpenCV images to FFMPEG. Here's a sample code:

# This script copies the video frame by frame
import cv2
import subprocess as sp

input_file = 'input_file_name.mp4'
output_file = 'output_file_name.mp4'

cap = cv2.VideoCapture(input_file)
ret, frame = cap.read()
height, width, ch = frame.shape

ffmpeg = 'FFMPEG'
dimension = '{}x{}'.format(width, height)
f_format = 'bgr24' # remember OpenCV uses bgr format
fps = str(cap.get(cv2.CAP_PROP_FPS))

command = [ffmpeg,
        '-y',
        '-f', 'rawvideo',
        '-vcodec','rawvideo',
        '-s', dimension,
        '-pix_fmt', 'bgr24',
        '-r', fps,
        '-i', '-',
        '-an',
        '-vcodec', 'mpeg4',
        '-b:v', '5000k',
        output_file ]

proc = sp.Popen(command, stdin=sp.PIPE, stderr=sp.PIPE)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    proc.stdin.write(frame.tostring())

cap.release()
proc.stdin.close()
proc.stderr.close()
proc.wait()

这篇关于使用python将opencv图像管道传输到ffmpeg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆