Frage

I am using ffmpeg to extract a frame from a video. This works fine when I use ffmpeg from the command line, however, when I try to do the same thing using the python:

os.popen3('ffmpeg -i videoPath -an -ss 00:00:02 -an -r 1 -vframes 1 -y picturePath')

I have no idea on how to get the extracted image. So far, I get only text saying (ffmpeg version N-62039-gc00f368 Copyright (c) 2000....) which is what I see in the command line. Would you please guide through what I need to do to get the image extracted. Thank you.

War es hilfreich?

Lösung

I typically use the following function for that sort of tasks. It includes a timeout parameter for automatically aborting excessively long running processes. That's often handy when it comes to user uploaded content:

import subprocess
from threading import Timer

def run_with_timeout(cmd, sec):
    def kill_proc(p, killed):
        killed['val'] = True
        p.kill()
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    killed = {'val': False}
    timer = Timer(sec, kill_proc, [p, killed])
    timer.start()
    stdout, stderr = p.communicate()
    timer.cancel()
    return p.returncode, stdout, stderr, killed['val']

With that, you can simply call any shell command with options, which is run synchronously. That means the function waits until the process is finished. Therefore, when the function is done, the thumbnail is either created or an error is returned:

videoPath = '/path/to/video/source/file.mp4'
picturePath = '/path/to/output.jpg'
result = run_with_timeout(['ffmpeg', '-i', videoPath, '-an', '00:00:02', '-r', '1', '-vframes', '1', '-y', picturePath], 30)
if result[0] != 0:
    print 'error'
else:
    print 'success'
    # do something with videoPath 

Works in current Python versions 2.7.x.

Andere Tipps

os is deprecated. You should use subprocess.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top