簡體   English   中英

使用 ffmpeg-python 將視頻分割成圖像

[英]Split video into images with ffmpeg-python

據我了解ffmpeg-python主要是Python中的package直接操作ffmpeg

現在我想拍攝一段視頻並將其幀保存為某些 fps 的單獨文件。

有很多命令行方法可以做到這一點,例如這里描述ffmpeg -i video.mp4 -vf fps=1 img/output%06d.png

但我想在 Python 中完成。還有解決方案[1] [2]使用 Python 的subprocess進程調用ffmpeg CLI,但它對我來說看起來很臟。

有什么辦法可以使用ffmpeg-python來實現嗎?

以下對我有用:

ffmpeg
.input(url)
.filter('fps', fps='1/60')
.output('thumbs/test-%d.jpg', 
        start_number=0)
.overwrite_output()
.run(quiet=True)

我建議您嘗試使用imageio 模塊並使用以下代碼作為起點:

import imageio

reader = imageio.get_reader('imageio:cockatoo.mp4')

for frame_number, im in enumerate(reader):
    # im is numpy array
    if frame_number % 10 == 0:
        imageio.imwrite(f'frame_{frame_number}.jpg', im)

您也可以為此使用openCV

參考代碼:

import cv2

video_capture = cv2.VideoCapture("your_video_path")
video_capture.set(cv2.CAP_PROP_FPS, <your_desired_fps_here>)

saved_frame_name = 0

while video_capture.isOpened():
    frame_is_read, frame = video_capture.read()

    if frame_is_read:
        cv2.imwrite(f"frame{str(saved_frame_name)}.jpg", frame)
        saved_frame_name += 1

    else:
        print("Could not read the frame.")

@norus 解決方案實際上很好,但對我來說它缺少輸入中的 ss 和 r 參數。 我使用本地文件而不是 url。

這是我的解決方案:

  ffmpeg.input(<path/to/file>, ss = 0, r = 1)\
        .filter('fps', fps='1/60')\
        .output('thumbs/test-%d.jpg', start_number=0)\
        .overwrite_output()]
        .run(quiet=True)

ss 是上面代碼中的起始秒數 starts on 0 r 是比率,因為過濾器 fps 設置為 1/60 1 的 r 將每秒返回 1 幀,2 1 幀每 2 秒,0.5 幀每半秒……

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM