本文目录导读:

我来介绍几种批量调整图片色彩量化的方法,主要使用 Python 和命令行工具。
使用 Python + Pillow (PIL)
from PIL import Image
import os
def batch_quantize_colors(input_dir, output_dir, colors=256, method=0):
"""
批量量化图片颜色
参数:
input_dir: 输入文件夹路径
output_dir: 输出文件夹路径
colors: 目标颜色数量(2-256)
method: 量化方法(0=中值切割, 1=最大覆盖, 2=固定调色板)
"""
# 创建输出目录
os.makedirs(output_dir, exist_ok=True)
# 支持的图片格式
image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
# 遍历输入文件夹
for filename in os.listdir(input_dir):
if filename.lower().endswith(image_extensions):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
try:
# 打开图片
with Image.open(input_path) as img:
# 转换为RGB模式(如果不是)
if img.mode != 'RGB':
img = img.convert('RGB')
# 量化颜色
quantized = img.quantize(colors=colors, method=method)
# 保存结果
quantized.save(output_path, optimize=True)
print(f"✓ 已处理: {filename} -> {colors}色")
except Exception as e:
print(f"✗ 处理失败 {filename}: {str(e)}")
# 使用示例
if __name__ == "__main__":
# 参数设置
input_directory = "./input_images/" # 输入文件夹
output_directory = "./output_images/" # 输出文件夹
target_colors = 64 # 目标颜色数
quantize_method = 0 # 量化方法
# 执行批量处理
batch_quantize_colors(input_directory, output_directory, target_colors, quantize_method)
使用 ImageMagick 命令行
#!/bin/bash
# Linux/Mac 系统
# 1. 基础颜色量化(减少到256色)
for img in ./input/*.{jpg,png}; do
convert "$img" -colors 256 "./output/$(basename "$img")"
done
# 2. 高质量颜色量化
for img in ./input/*.jpg; do
convert "$img" \
-dither FloydSteinberg \
-colors 64 \
-quantize YIQ \
"./output/$(basename "$img")"
done
# 3. 批量处理所有图片(更完整的版本)
for file in ./input/*; do
if [[ -f "$file" ]]; then
filename=$(basename "$file")
convert "$file" \
-colorspace RGB \
-colors 128 \
-dither FloydSteinberg \
"./output/$filename"
echo "已处理: $filename"
fi
done
使用 scikit-image 进行高级量化
from skimage import io, color
from sklearn.cluster import KMeans
import numpy as np
import os
def advanced_color_quantization(image_path, output_path, n_colors=16):
"""
使用K-means聚类进行高级颜色量化
"""
# 读取图片
image = io.imread(image_path)
# 转换颜色空间(可选)
# hsv_image = color.rgb2hsv(image)
# 重塑数据
h, w, c = image.shape
pixels = image.reshape(-1, c)
# 使用K-means进行聚类
kmeans = KMeans(n_clusters=n_colors, random_state=42)
labels = kmeans.fit_predict(pixels)
# 用聚类中心替换颜色
quantized = kmeans.cluster_centers_[labels]
quantized = quantized.reshape(h, w, c)
# 转换为8位整数
quantized = (quantized * 255).astype(np.uint8)
# 保存结果
io.imsave(output_path, quantized)
return quantized
def batch_advanced_quantization(input_dir, output_dir, n_colors=32):
"""
批量高级颜色量化
"""
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, f"quantized_{filename}")
try:
advanced_color_quantization(input_path, output_path, n_colors)
print(f"✓ 已完成高级量化: {filename}")
except Exception as e:
print(f"✗ 处理失败 {filename}: {e}")
# 使用示例
batch_advanced_quantization("./input/", "./output/", n_colors=16)
Python 批量处理 + 多进程加速
from concurrent.futures import ProcessPoolExecutor, as_completed
from PIL import Image
import os
import argparse
def process_single_image(args):
"""处理单张图片的函数"""
input_path, output_path, colors, method, dither = args
try:
with Image.open(input_path) as img:
# 转换模式
if img.mode != 'RGB':
img = img.convert('RGB')
# 量化
quantized = img.quantize(
colors=colors,
method=method,
dither=dither
)
# 保存
quantized.save(output_path, optimize=True)
return True, os.path.basename(input_path), None
except Exception as e:
return False, os.path.basename(input_path), str(e)
def batch_process_multiprocessing(input_dir, output_dir, colors=256,
method=0, dither=True, max_workers=4):
"""
使用多进程批量处理图片
"""
# 创建输出目录
os.makedirs(output_dir, exist_ok=True)
# 收集所有图片路径
image_files = []
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
image_files.append((input_path, output_path, colors, method, dither))
# 多进程处理
total = len(image_files)
completed = 0
failed = 0
with ProcessPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(process_single_image, args)
for args in image_files]
for future in as_completed(futures):
success, filename, error = future.result()
if success:
completed += 1
print(f"✓ [{completed}/{total}] {filename}")
else:
failed += 1
print(f"✗ [{completed+failed}/{total}] {filename} - 错误: {error}")
print(f"\n处理完成! 成功: {completed}, 失败: {failed}")
# 命令行接口
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='批量图片颜色量化工具')
parser.add_argument('input_dir', help='输入文件夹路径')
parser.add_argument('output_dir', help='输出文件夹路径')
parser.add_argument('--colors', type=int, default=256, help='目标颜色数量 (2-256)')
parser.add_argument('--method', type=int, default=0,
choices=[0, 1, 2], help='量化方法 (0=中值切割, 1=最大覆盖, 2=固定调色板)')
parser.add_argument('--workers', type=int, default=4, help='并行处理线程数')
args = parser.parse_args()
batch_process_multiprocessing(
args.input_dir,
args.output_dir,
colors=args.colors,
method=args.method,
dither=True,
max_workers=args.workers
)
使用建议
-
选择颜色数量:
- 网页图片:64-128色
- GIF动图:256色
- 复古效果:8-32色
- 极简风格:2-16色
-
量化方法选择:
- 中值切割 (method=0):速度快,效果均衡
- 最大覆盖 (method=1):颜色分布更均匀
- K-means:效果最好,但速度慢
-
安装依赖:
pip install Pillow scikit-image scikit-learn numpy
-
ImageMagick 安装:
# Ubuntu/Debian sudo apt-get install imagemagick
macOS
brew install imagemagick
Windows
下载安装包:https://imagemagick.org/script/download.php
选择最适合你需求的方案,根据需要调整颜色数量和量化方法!