python 调用ffmpeg获取影片信息_在Python中使用ffmpeg提取视频的中间帧?

该博客展示了如何在Python中使用ffmpeg库来获取影片信息并提取视频的中间帧。通过调用ffmpeg命令行工具,解析输出结果,确定视频的持续时间,并计算目标帧的位置。最后,使用ffmpeg提取指定位置的帧并将其保存为图片。
摘要由CSDN通过智能技术生成

结果我不得不在前一段时间内解决几乎完全相同的问题。

另外一个要求是不使用ffprobe(因为它可能不可用,但是{}可以)。ffprobe正如@lordnickbeard所说,如果不是这样的话,获得持续时间的任务会更好。在

所以这里有一些文档不多的代码应该很容易理解。如果没有,尽管问。在#!/usr/bin/env python

# Any copyright is dedicated to the Public Domain.

# http://creativecommons.org/publicdomain/zero/1.0/

# Written in 2013 - Nils Maier

import datetime

import os

import re

import subprocess

import sys

def which(program):

""" Somewhat equivalent to which(1) """

def is_executable(fpath):

return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

if is_executable(program):

return program

path, program = os.path.split(program)

if path:

return None

for path in os.environ["PATH"].split(os.pathsep):

path = path.strip('"')

exe = os.path.join(path, program)

if is_executable(exe):

return exe

# Windows-style

exe = os.path.join(path, "{}.exe".format(program))

if is_executable(exe):

return exe

return None

def thumb_with_ffmpeg(infile, position=0.5, executable=None):

"""

Extract a thumbnail using ffmpeg

:param infile: File to thumbnail.

:param position: Position at which to take the thumbnail. Default: 0.5

:param executable: Executable to use. Default: first "ffmpeg" in $PATH

:returns: The thumbnail data (binary string)

"""

ffmpeg = which(executable or "ffmpeg")

if not ffmpeg:

raise RuntimeError(

"Failed to find ffmpeg executable: {}".format(executable))

if position < 0 or position >= 1.0:

raise ValueError(

"Position {} is not between 0.0 and 1.0".format(position))

proc = subprocess.Popen([ffmpeg, "-i", infile], stderr=subprocess.PIPE)

_, result = proc.communicate()

m = re.search(r"Duration:\s*(\d+):(\d+):(\d+)\.(\d+)", result)

if not m:

raise KeyError("Cannot determine duration")

# Avoiding strptime here because it has some issues handling milliseconds.

m = [int(m.group(i)) for i in range(1, 5)]

duration = datetime.timedelta(hours=m[0],

minutes=m[1],

seconds=m[2],

# * 10 because truncated to 2 decimal places

milliseconds=m[3] * 10

).total_seconds()

target = max(0, min(duration * position, duration - 0.1))

target = "{:.3f}".format(target)

args = [ffmpeg,

"-ss", target,

"-i", infile,

"-map", "v:0", # first video stream

"-frames:v", "1", # 1 frame

"-f", "mjpeg", # motion jpeg (aka. jpeg since 1 frame) output

"pipe:" # pipe output to stdout

]

proc = subprocess.Popen(args, stdout=subprocess.PIPE,

stderr=subprocess.PIPE)

output, _ = proc.communicate()

if proc.returncode:

raise subprocess.CalledProcessError(proc.returncode, args)

if not output:

raise subprocess.CalledProcessError(-2, args)

return output

if __name__ == "__main__":

from argparse import ArgumentParser, ArgumentTypeError

def percentage(x):

x = float(x)

if x < 0.0 or x >= 1.0:

raise ArgumentTypeError(

"{} not in percentage range [0.0, 1.0)".format(x))

return x

parser = ArgumentParser(

description="Extract a thumbnail from a media file using ffmpeg")

parser.add_argument("infile", type=str, help="Input file")

parser.add_argument("outfile", type=str, help="Output file")

parser.add_argument("-f", " ffmpeg", type=str, default=None,

help="use this ffmpeg binary, "

"default: check $PATH for ffmpeg")

parser.add_argument("-p", " position", type=percentage, default=0.5,

help="thumbnail at this position (percentage), "

"default: 0.5")

args = parser.parse_args()

try:

output = thumb_with_ffmpeg(args.infile, args.position, args.ffmpeg)

with open(args.outfile, "wb") as op:

op.write(output)

except Exception as ex:

print >>sys.stderr, "Error:", ex

sys.exit(ex.returncode or 1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python使用FFmpeg可以通过调用FFmpeg的命令行工具或者使用FFmpegPython库来实现。下面是两种方法的介绍: 1. 调用FFmpeg命令行工具: 可以使用Python的`subprocess`模块来调用FFmpeg的命令行工具。首先,确保你已经安装了FFmpeg,并将其添加到系统的环境变量。然后,可以使用`subprocess.run()`函数来执行FFmpeg命令。例如,要将视频文件转换为其他格式,可以使用以下代码: ```python import subprocess input_file = 'input.mp4' output_file = 'output.avi' command = f'ffmpeg -i {input_file} {output_file}' subprocess.run(command, shell=True) ``` 在上面的代码,`input.mp4`是输入视频文件的路径,`output.avi`是输出视频文件的路径。`ffmpeg -i`是FFmpeg的命令行选项,用于指定输入文件和输出文件。 2. 使用FFmpegPython库: 除了调用命令行工具,还可以使用FFmpegPython库来在Python进行音视频处理。有几个流行的FFmpeg Python库可供选择,例如`ffmpeg-python`和`pydub`。这些库提供了更高级的接口和功能,使得在Python处理音视频更加方便。 以`ffmpeg-python`为例,首先需要安装该库: ```shell pip install ffmpeg-python ``` 然后,可以使用以下代码来进行音视频处理: ```python import ffmpeg input_file = 'input.mp4' output_file = 'output.avi' ffmpeg.input(input_file).output(output_file).run() ``` 在上面的代码,`input.mp4`是输入视频文件的路径,`output.avi`是输出视频文件的路径。`ffmpeg.input()`用于指定输入文件,`output()`用于指定输出文件,`run()`用于执行转换操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值