广告
返回顶部
首页 > 资讯 > 后端开发 > Python >42、 ffmpeg 的简单使用
  • 178
分享到

42、 ffmpeg 的简单使用

简单ffmpeg 2023-01-31 03:01:26 178人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

一、FFmpeg-python 安装 pip3 install ffmpeg-Python 也可以通过克隆源码返回式进行安装: git clone git@GitHub.com:kkroening/ffmpeg-python.g

一、FFmpeg-python 安装

pip3 install ffmpeg-Python

也可以通过克隆源码返回式进行安装:

git clone git@GitHub.com:kkroening/ffmpeg-python.git
export PYTHONPATH=${PYTHONPATH}:ffmpeg-python
python
>>> import ffmpeg
>>> help(ffmpeg) # 通过help()可以查看ffmpeg提供的相应的Python api

二、常用的ffmpegpython API

1、probe 获取视频文件的详细信息
语法格式:
probe(filePath[, cmd="ffprobe"]) 

用于获取视频文件的详细信息,filePath是文件路径的字符串表示。[...]中的内容可选,一般使用默认值。其返回值是一个字典,字典中有两个key-value对。

示例
import ffmpeg

info = ffmpeg.probe("/xxx/xxx/test.mp4")
"""
{
  "streams": [
    {
      "index": 0,
      "codec_name": "h264",
      "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
      "profile": "Main",
      "codec_type": "video",
      "codec_time_base": "1001/48000",
      "codec_tag_string": "avc1",
      "codec_tag": "0x31637661",
      "width": 1024,
      "height": 576,
      "coded_width": 1024,
      "coded_height": 576,
      "has_b_frames": 1,
      "sample_aspect_ratio": "1:1",
      "display_aspect_ratio": "16:9",
      "pix_fmt": "yuv420p",
      "level": 31,
      "color_range": "tv",
      "color_space": "bt709",
      "color_transfer": "bt709",
      "color_primaries": "bt709",
      "chroma_location": "left",
      "refs": 1,
      "is_avc": "true",
      "nal_length_size": "4",
      "r_frame_rate": "24000/1001",
      "avg_frame_rate": "24000/1001",
      "time_base": "1/48000",
      "start_pts": 0,
      "start_time": "0.000000",
      "duration_ts": 2883840,
      "duration": "60.080000",
      "bit_rate": "944746",
      "bits_per_raw_sample": "8",
      "nb_frames": "1515",
      "disposition": {
        "default": 1,
        "dub": 0,
        "original": 0,
        "comment": 0,
        "lyrics": 0,
        "karaoke": 0,
        "forced": 0,
        "hearing_impaired": 0,
        "visual_impaired": 0,
        "clean_effects": 0,
        "attached_pic": 0,
        "timed_thumbnails": 0
      },
      "tags": {
        "language": "und",
        "handler_name": "Video Media Handler"
      }
    },
    {
      "index": 1,
      "codec_name": "aac",
      "codec_long_name": "AAC (Advanced Audio coding)",
      "profile": "LC",
      "codec_type": "audio",
      "codec_time_base": "1/44100",
      "codec_tag_string": "mp4a",
      "codec_tag": "0x6134706d",
      "sample_fmt": "fltp",
      "sample_rate": "44100",
      "channels": 2,
      "channel_layout": "stereo",
      "bits_per_sample": 0,
      "r_frame_rate": "0/0",
      "avg_frame_rate": "0/0",
      "time_base": "1/44100",
      "start_pts": 0,
      "start_time": "0.000000",
      "duration_ts": 2646441,
      "duration": "60.010000",
      "bit_rate": "125617",
      "max_bit_rate": "125617",
      "nb_frames": "2721",
      "disposition": {
        "default": 1,
        "dub": 0,
        "original": 0,
        "comment": 0,
        "lyrics": 0,
        "karaoke": 0,
        "forced": 0,
        "hearing_impaired": 0,
        "visual_impaired": 0,
        "clean_effects": 0,
        "attached_pic": 0,
        "timed_thumbnails": 0
      },
      "tags": {
        "language": "und",
        "handler_name": "GPAC ISO Audio Handler"
      }
    }
  ],
  "fORMat": {
    "filename": "/Users/didi/Desktop/Python/python3/code/section_35/data/1.mp4",
    "nb_streams": 2,
    "nb_programs": 0,
    "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
    "format_long_name": "QuickTime / MOV",
    "start_time": "0.000000",
    "duration": "63.189000",
    "size": "8500415",
    "bit_rate": "1076189",
    "probe_score": 100,
    "tags": {
      "major_brand": "isom",
      "minor_version": "512",
      "compatible_brands": "isomiso2avc1mp41",
      "encoder": "Lavf58.20.100"
    }
  }
}
"""

输入结果如下:

{
    'streams': [{'index': 0, 'codec_name': 'h264', ...}]
    'format': {'filename': '/Users/didi/isp-system/data/test_video.mp4', ...}
}

其中key:‘streams’对应的值是一个listlist中有两个dict类型的值,分别表示视频中视频流和音频流的相关信息。

key:‘format’对应的值是一个dict,其中包含了视频的相关的格式信息、视频时长信息、文件大小信息等。

我们可以通过一下代码获取我们关心的信息:

info = ffmpeg.probe(str(file))
vs = next(c for c in info['streams'] if c['codec_type'] == 'video')
duration_secs = float(vs['duration'])
format = info['format']['format_name']
codec_name = vs['codec_name']
width = vs['width']
height = vs['height']
num_frames = vs['nb_frames']
2、input(filePath, **kwargs)

输入文件的路径。

ffmpeg.input(filename, **ffmpeg_args)
  • ffmpeg.input() 等价与在命令行输入ffmpeg -i ...
  • kwargs 中可以包含的参数有:t、f、acodec

一般与outputrun联合使用。

3、output(*streams_and_filePath, **kwargs)

输入文件的路径。

ffmpeg.output(stream1[, stream2, stream3...], filename, **ffmpeg_args)
  • kwargs 中可以包含的参数有:t、f、acodec、vcodec

一般与outputrun联合使用。

4、run(stream_spec, cmd='ffmpeg', capture_stdout=False, capture_stderr=False, input=None, quiet=False, overwrite_output=False)

为提供的节点图调用ffmpeg

综合示例一:对视频文件进行全抽帧
import ffmpeg


# 全抽帧
def get_frames():
    input_file = '/Users/didi/Desktop/ffmpeg/test.mp4'
    output_file = '/Users/didi/Desktop/ffmpeg/image/image-%5d.jpg'
    out, err = (
        ffmpeg
            .input(input_file)
            .output(output_file)
            .run(quiet=False, overwrite_output=True)
    )
    if out == b'':
        print('do nothing')


# 按一定的频率抽帧
def get_frames_by_rate():
    input_file = '/Users/didi/Desktop/ffmpeg/test.mp4'
    output_file = '/Users/didi/Desktop/ffmpeg/image/image-%5d.jpg'
    out, err = (
        ffmpeg
            .input(input_file, ss=0)
            # .output(output_file, r='1', f='image2')
            .output(output_file, vf='fps=fps=1', f='image2')
            .run(quiet=False, overwrite_output=True)
    )
    if out == b'':
        print('do nothing')


# 按指定时间片段抽帧
def get_frames_by_times():
    times = [1, 5, 8, 10]
    for time in times:
        input_file = '/Users/didi/Desktop/ffmpeg/test.mp4'
        output_file = '/Users/didi/Desktop/ffmpeg/image/image-' + str(time) + '.jpg'
        out, err = (
            ffmpeg
                .input(input_file, ss=time)
                .output(output_file, vframes='1', f='image2')
                .run(quiet=False, overwrite_output=True)
        )
        if out == b'':
            print('do nothing')


if __name__ == '__main__':
    get_frames_by_rate()
5、concat(*streams, **kwargs)

连接音频和视频流,将它们一个接一个地连接在一起。

import ffmpeg


# 视频剪切
def cut_videos():
    input_file = '/Users/didi/Desktop/ffmpeg/test.mp4'
    output_file = '/Users/didi/Desktop/ffmpeg/video/video1.mp4'
    out, err = (
        ffmpeg
            # 注意ss,t的单位都是秒
            .input(input_file, ss=220, t=20)
            .output(output_file, codec="copy")
            .run(quiet=False, overwrite_output=True)
    )
    if out == b'':
        print('do nothing')


# 视频合并
def concat_video():
    # 注意:要合并的视频文件和txt文件需要放在同一个目录下
    input_file = '/Users/didi/Desktop/ffmpeg/video/aa.txt'
    output_file = '/Users/didi/Desktop/ffmpeg/video/Cam.mp4'
    try:
        out, err = (
            ffmpeg
                .input(input_file, f='concat')
                .output(output_file, c='copy')
                .run(quiet=False, overwrite_output=True)
        )
    except Exception as e:
        print(e)


if __name__ == '__main__':
    concat_video()
    #cut_videos()

--结束END--

本文标题: 42、 ffmpeg 的简单使用

本文链接: https://www.lsjlt.com/news/187525.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作