前言
一個使用ffmpeg多進程將大量mp4文件轉換為對應多幀png/jpg/bmp等圖片文件的代碼實例,其中png存儲于與視頻同名的文件夾當中。
一、核心命令
ffmpeg -i *.mp4 -s 256x256 -r 25 %8d.png
其中 -i 指 輸入地址
-s 指定圖片分辨率
-r 指定幀數(shù)文章來源:http://www.zghlxwxcb.cn/news/detail-622275.html
二、代碼實例
核心思想使用 multiprocessing 讀取 MP4 文件列表,更改命名方式進行存儲文章來源地址http://www.zghlxwxcb.cn/news/detail-622275.html
import os
import argparse
from typing import List, Dict
from multiprocessing import Pool
import subprocess
from subprocess import Popen, PIPE
from glob import glob
from tqdm import tqdm, trange
def clip_vid2png(source_dir: os.PathLike, output_dir: os.PathLike, num_workers: int):
os.makedirs(output_dir, exist_ok=True)
# os.makedirs(os.path.join(output_dir, '_videos_raw'), exist_ok=True)
import pdb;pdb.set_trace()
video_queue = construct_video_queue(source_dir)
task_kwargs = [dict(
video_path=vd, # 視頻路徑
png_path= os.path.join(output_dir, os.path.basename(vd))# 圖像存儲路徑
) for vd in video_queue]
pool = Pool(processes=num_workers)
tqdm_kwargs = dict(total=len(task_kwargs), desc=f'Clips videos into {output_dir}')
for _ in tqdm(pool.imap_unordered(task_proxy_clip, task_kwargs), **tqdm_kwargs):
pass
print('Clip is finished')
def construct_video_queue(source_dir: os.PathLike) -> List[Dict]:
video_queue = sorted(glob(os.path.join(source_dir, "*.mp4")))
return video_queue
def task_proxy_clip(kwargs):
return clip_video(**kwargs)
def clip_video(video_path, png_path):
os.makedirs(png_path, exist_ok=True)
command = [
"ffmpeg",
"-loglevel", "quiet",
"-i",
f"{video_path}",
"-s", "256x256",
"-r", "25",
f"{png_path}/%08d.png"
]
return_code = subprocess.call(command)
return return_code
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="clip video to png")
parser.add_argument('-s', '--source_dir', type=str, default=None, help='Path to the directory with the dataset')
parser.add_argument('-o', '--output_dir', type=str, default=None, help='Where to save the videos?')
parser.add_argument('-w', '--num_workers', type=int, default=4, help='Number of workers for downloading')
args = parser.parse_args()
clip_vid2png(
args.source_dir,
args.output_dir,
args.num_workers,
)
到了這里,關于使用FFmpeg將視頻幀轉換為png圖像的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!