用FFMPEG视频转图片,并且for循环
import os
import subprocess
# 输入文件夹和输出文件夹路径
input_folder = r"I:\xxx"
output_base_folder = r"D:\xxx\YOLO\data\video"
output_subfolder_name = "20240609"
# 创建输出子文件夹
output_folder = os.path.join(output_base_folder, output_subfolder_name)
os.makedirs(output_folder, exist_ok=True)
# 循环处理输入文件夹中的所有视频文件
for file_name in os.listdir(input_folder):
# 检查是否是视频文件(扩展名可根据需要增加)
if file_name.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')):
input_path = os.path.join(input_folder, file_name)
output_name = os.path.splitext(file_name)[0] # 去掉扩展名
output_path_pattern = os.path.join(output_folder, f"{output_name}_frame_%04d.jpg")
# 构建 FFmpeg 命令
ffmpeg_command = [
"ffmpeg",
"-i", input_path, # 输入视频路径
"-vf", "fps=5", # 每秒提取 5 帧
"-q:v", "2", # 高质量图片
output_path_pattern # 输出图片路径模式
]
# 打印当前正在处理的文件
print(f"Processing video: {input_path} -> {output_folder}")
# 执行 FFmpeg 命令
subprocess.run(ffmpeg_command, check=True)
print("视频处理完成!图片已保存到:", output_folder)
改进以后的代码
import os
import subprocess
# 输入文件夹和输出文件夹路径
input_folder = r"H:\\xxxx"
output_base_folder = r"D:\\xxx"
output_subfolder_name = os.path.split(os.path.dirname(input_folder))[1]
# 创建输出子文件夹
output_folder = os.path.join(output_base_folder, output_subfolder_name)
os.makedirs(output_folder, exist_ok=True)
# 记录成功和失败的文件
processed_videos = []
skipped_videos = []
# 循环处理输入文件夹中的所有视频文件
for file_name in os.listdir(input_folder):
# 检查是否是视频文件(扩展名可根据需要增加)
if file_name.lower().endswith(('.mp4')):
input_path = os.path.join(input_folder, file_name)
output_name = os.path.splitext(file_name)[0] # 去掉扩展名
output_path_pattern = os.path.join(output_folder, f"{output_name}_frame_%04d.jpg")
# 构建 FFmpeg 命令
ffmpeg_command = [
"ffmpeg",
"-i", input_path, # 输入视频路径
"-vf", "fps=1", # 每秒提取 1 帧
"-q:v", "2", # 高质量图片
output_path_pattern # 输出图片路径模式
]
try:
print(f"Processing video: {input_path} -> {output_folder}")
subprocess.run(ffmpeg_command, check=True)
processed_videos.append(file_name)
except subprocess.CalledProcessError as e:
print(f"Error processing {input_path}: {e}")
skipped_videos.append(file_name)
# 保存处理结果到文件
with open(os.path.join(output_folder, "processed_videos.txt"), "w") as processed_file:
processed_file.write("\n".join(processed_videos))
with open(os.path.join(output_folder, "skipped_videos.txt"), "w") as skipped_file:
skipped_file.write("\n".join(skipped_videos))
print("处理完成!")
print(f"成功处理的视频列表已保存到: {os.path.join(output_folder, 'processed_videos.txt')}")
print(f"跳过的视频列表已保存到: {os.path.join(output_folder, 'skipped_videos.txt')}")