本文目录导读:

- 方法一:使用 Python (PIL/Pillow)
- 方法二:使用 ImageMagick 命令行
- 方法三:使用 Python + OpenCV (更专业)
- 方法四:使用 FFmpeg (视频/图片均可)
- 安装依赖
- 使用建议
我来介绍几种批量制作九宫格图片的方法。
使用 Python (PIL/Pillow)
import os
from PIL import Image
def make_grid(image_path, output_path, grid_size=3):
"""
将单张图片切成九宫格
"""
img = Image.open(image_path)
width, height = img.size
# 计算每格大小
cell_width = width // grid_size
cell_height = height // grid_size
# 切分并保存
base_name = os.path.splitext(os.path.basename(image_path))[0]
os.makedirs(output_path, exist_ok=True)
for i in range(grid_size):
for j in range(grid_size):
left = j * cell_width
top = i * cell_height
right = (j + 1) * cell_width
bottom = (i + 1) * cell_height
cell = img.crop((left, top, right, bottom))
cell.save(f"{output_path}/{base_name}_{i}_{j}.jpg")
def batch_process(input_folder, output_folder):
"""
批量处理文件夹中的所有图片
"""
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
input_path = os.path.join(input_folder, filename)
make_grid(input_path, output_folder)
# 使用示例
batch_process("input_images", "output_grids")
使用 ImageMagick 命令行
#!/bin/bash
# 批量处理脚本 batch_grid.sh
INPUT_DIR="input_images"
OUTPUT_DIR="output_grids"
GRID_SIZE=3
mkdir -p "$OUTPUT_DIR"
for img in "$INPUT_DIR"/*.{jpg,jpeg,png}; do
if [ -f "$img" ]; then
base_name=$(basename "$img" | cut -d. -f1)
# 获取图片尺寸
width=$(identify -format "%w" "$img")
height=$(identify -format "%h" "$img")
cell_width=$((width / GRID_SIZE))
cell_height=$((height / GRID_SIZE))
count=0
for ((i=0; i<GRID_SIZE; i++)); do
for ((j=0; j<GRID_SIZE; j++)); do
x=$((j * cell_width))
y=$((i * cell_height))
convert "$img" -crop "${cell_width}x${cell_height}+${x}+${y}" \
"$OUTPUT_DIR/${base_name}_${i}_${j}.jpg"
count=$((count + 1))
done
done
echo "处理完成: $base_name"
fi
done
使用 Python + OpenCV (更专业)
import cv2
import os
import numpy as np
def make_grid_opencv(image_path, output_path):
"""
使用OpenCV创建九宫格效果
"""
# 读取图片
img = cv2.imread(image_path)
h, w = img.shape[:2]
# 计算每格大小
grid_h, grid_w = h // 3, w // 3
# 创建输出目录
base_name = os.path.splitext(os.path.basename(image_path))[0]
os.makedirs(output_path, exist_ok=True)
# 切分图片
for i in range(3):
for j in range(3):
y1 = i * grid_h
y2 = (i + 1) * grid_h
x1 = j * grid_w
x2 = (j + 1) * grid_w
cell = img[y1:y2, x1:x2]
cv2.imwrite(f"{output_path}/{base_name}_{i}_{j}.jpg", cell)
# 批量处理
def batch_process_opencv(input_dir, output_dir):
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
input_path = os.path.join(input_dir, filename)
make_grid_opencv(input_path, output_dir)
print(f"处理完成: {filename}")
# 使用示例
batch_process_opencv("images", "grids")
使用 FFmpeg (视频/图片均可)
#!/bin/bash
# 批量处理脚本
for file in input_images/*.{jpg,jpeg,png}; do
if [ -f "$file" ]; then
base=$(basename "$file" | cut -d. -f1)
# 获取尺寸
width=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of default=noprint_wrappers=1:nokey=1 "$file")
height=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of default=noprint_wrappers=1:nokey=1 "$file")
cell_w=$((width / 3))
cell_h=$((height / 3))
# 使用 ffmpeg 裁剪
count=0
for i in 0 1 2; do
for j in 0 1 2; do
x=$((j * cell_w))
y=$((i * cell_h))
ffmpeg -i "$file" -vf "crop=$cell_w:$cell_h:$x:$y" \
"output_grids/${base}_${i}_${j}.jpg" -y
count=$((count + 1))
done
done
fi
done
安装依赖
Python 环境:
pip install pillow opencv-python
ImageMagick (Linux/macOS):
# Ubuntu/Debian sudo apt-get install imagemagick # macOS brew install imagemagick # Windows 下载安装 # https://imagemagick.org/script/download.php
FFmpeg:
# Ubuntu/Debian sudo apt-get install ffmpeg # macOS brew install ffmpeg
使用建议
- 推荐使用 Python 方案:灵活性强,易于定制
- 大文件处理:使用 ImageMagick 或 FFmpeg
- 批量处理大量图片:建议使用 OpenCV,性能更好
- 图片预处理:可以先统一图片尺寸,保证九宫格均匀
需要我详细说明某个方案或添加其他功能吗?