Python 訪問桌面文件夾下的圖片序列,生成動畫 (GIF/MP4)。
os/pathlib:遍歷文件夾。imageio / PIL (Pillow) / cv2:讀寫圖片、生成動畫。import os
import imageio.v2 as imageio # pip install imageio
from pathlib import Path
def make_animation(folder_path, output_gif, fps=10):
# 1. 獲取所有圖片文件 (按文件名排序保證幀序)
valid_ext = {'.png', '.jpg', '.jpeg', '.bmp', '.tiff'}
files = sorted(
[f for f in Path(folder_path).iterdir() if f.suffix.lower() in valid_ext],
key=lambda p: p.stem # 或按修改時間 p.stat().st_mtime
)
if not files:
print("未找到圖片")
return
# 2. 讀取幀
frames = []
for f in files:
try:
frames.append(imageio.imread(str(f)))
except Exception as e:
print(f"跳過 {f}: {e}")
# 3. 寫入 GIF
imageio.mimsave(output_gif, frames, fps=fps)
print(f"生成完成: {output_gif}, 共 {len(frames)} 幀")
if __name__ == '__main__':
# 桌面路徑 (Windows)
desktop = Path.home() / "Desktop" / "my_frames"
make_animation(desktop, "animation.gif", fps=12)
# 進階: 生成 MP4 (需安裝 ffmpeg: pip install imageio-ffmpeg)
# imageio.mimsave("animation.mp4", frames, fps=12, codec='libx264')
| 環節 | 代碼 | 說明 |
|---|---|---|
| 跨平台桌面路徑 | Path.home() / "Desktop" | Windows/Mac/Linux 通用 |
| 排序保證幀序 | sorted(..., key=lambda p: p.stem) | 文件名建議 frame_001.png 格式 |
| 異常容錯 | try/except 跳過損壞圖片 | 避免單張壞圖導致全失敗 |
| 內存優化 | 大量幀用 imageio.get_writer 流式寫入 | 避免全量載入內存 |