使用python将opencv图像传输到ffmpeg

时间:2015-12-08 22:58:00

标签: python opencv video ffmpeg

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

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

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,我在一个相关的问题中找到了这个命令:

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

接下来,我试图将ffmpeg作为子进程运行:

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控制台充满神秘的象形文字然后崩溃。有什么建议吗?

最终,我想输出4个流并让ffmpeg并行编码这4个流。

2 个答案:

答案 0 :(得分:9)

我曾遇到过类似的问题。 I opened an issue on Github,事实证明可能是一个平台问题。

与您的问题相关,您也可以将OpenCV图像传输到FFMPEG。这是一个示例代码:

# 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()

答案 1 :(得分:0)

最近,您可以使用我强大的VidGear python库,该库仅使用其URL地址自动通过管道传输YouTube视频。这是一个示例:


# import libraries
from vidgear.gears import CamGear
import cv2

stream = CamGear(source='https://youtu.be/dQw4w9WgXcQ', y_tube =True,  time_delay=1, logging=True).start() # YouTube Video URL as input

# infinite loop
while True:

    frame = stream.read()
    # read frames

    # check if frame is None
    if frame is None:
        #if True break the infinite loop
        break

    # do something with frame here

    cv2.imshow("Output Frame", frame)
    # Show output window

    key = cv2.waitKey(1) & 0xFF
    # check for 'q' key-press
    if key == ord("q"):
        #if 'q' key-pressed break out
        break

cv2.destroyAllWindows()
# close output window

stream.stop()
# safely close video stream.

来源:https://github.com/abhiTronix/vidgear/wiki/CamGear-Class#2-camgear-class-with-live-youtube-piplineing-using-video-url