【FFmpeg 教程 一】截图

本章使用 ffmpeg 实现观影中经常会用到的功能,截图。
以下给出两种方式。

课程需具备的基础能力:Python 

1. 使用 subprocess 调用 FFmpeg 命令

import subprocess
def extract_frame(video_path, output_image_path, timestamp="00:00:05")
	"""
	从视频中截取指定时间点的帧作为图片
	:param video_path: 输入视频文件路径
	:param output_image_path: 输出图片文件路径
	:param timestamp: 截取时间点,格式为 'HH:MM:SS', 默认为 00:00:05
	"""
	try:
		# 调用 ffmpeg 命令
		command = [
			'ffmpeg',
			"-i", video_path,		# 输入视频文件
			"-ss", timestamp,		# 截取的时间点
			"-vframes", "1",		# 截取一帧
			output_image_path,		# 输出图片文件路径
			"-y"
		]
		suprocess.run(command, check=True)
		print(f"成功截取帧: {output_image_path}")
	except subprocess.CalledProcessError as e:
		print(f"错误:{e}")

// 使用
video_file = "example.mp4"
output_image = "screenshot.jpg"
timestamp = "00:01:00" # 截取 1 分钟时的帧
extract_frame(video_file, output_image, timestamp)

2. 使用 ffmpeg-python

示例代码:

import ffmpeg

def extract_frame_ffmpeg(video_path, output_image_path, timestamp=5.0):
    """
    使用 ffmpeg-python 从视频中截取指定时间点的帧并保存为图片。
    
    :param video_path: 输入视频文件路径
    :param output_image_path: 输出图片文件路径
    :param timestamp: 截取的时间点,单位秒
    """
    try:
        # 使用 ffmpeg-python 提取帧
        ffmpeg.input(video_path, ss=timestamp).output(output_image_path, vframes=1).run(overwrite_output=True)
        print(f"成功截取帧并保存到 {output_image_path}")
    except ffmpeg.Error as e:
        print(f"错误: {e.stderr.decode()}")

# 使用示例
video_file = "example.mp4"
output_image = "screenshot2.jpg"
timestamp = 60.0  # 截取 60 秒时的帧
extract_frame_ffmpeg(video_file, output_image, timestamp)

解释

  1. ffmpeg.input(video_path, ss=timestamp)

    • input() 函数用来指定输入视频路径。
    • ss 参数指定截取的时间戳,可以是秒数(例如 60.0)或者 HH:MM:SS 格式。
  2. output(output_image_path, vframes=1)

    • output() 用于指定输出文件路径。
    • vframes=1 表示我们只提取视频中的一帧。
  3. run(overwrite_output=True)

    • run() 执行 FFmpeg 命令,overwrite_output=True 表示如果目标文件已存在,会被覆盖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值