本文目录导读:

- 方案一:使用 Python + Pillow (PIL)
- 方案二:使用 OpenCV (更专业的色彩平衡)
- 方案三:使用 ImageMagick (命令行工具)
- 方案四:使用 GIMP 脚本 (Batch Mode)
- 进阶:使用深度学习进行智能色彩校正
- 安装依赖
- 使用建议
我无法直接运行脚本或处理图片,但我可以为您提供多种实现批量调整图片色彩平衡的方法和代码示例,以下是几个主流方案:
使用 Python + Pillow (PIL)
from PIL import Image, ImageEnhance
import os
from pathlib import Path
def batch_adjust_color_balance(input_folder, output_folder, red_ratio=1.0, green_ratio=1.0, blue_ratio=1.0):
"""
批量调整图片色彩平衡
:param input_folder: 输入文件夹路径
:param output_folder: 输出文件夹路径
:param red_ratio: 红色通道调整系数 (0.0-3.0)
:param green_ratio: 绿色通道调整系数
:param blue_ratio: 蓝色通道调整系数
"""
# 创建输出文件夹
Path(output_folder).mkdir(parents=True, exist_ok=True)
# 支持的图片格式
supported_formats = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff'}
for filename in os.listdir(input_folder):
file_ext = Path(filename).suffix.lower()
if file_ext not in supported_formats:
continue
file_path = os.path.join(input_folder, filename)
try:
img = Image.open(file_path)
# 分离RGB通道
if img.mode == 'RGBA':
r, g, b, a = img.split()
elif img.mode == 'RGB':
r, g, b = img.split()
a = None
else:
print(f"跳过 {filename}: 不支持的图片模式 {img.mode}")
continue
# 调整各通道
r = r.point(lambda x: min(255, int(x * red_ratio)))
g = g.point(lambda x: min(255, int(x * green_ratio)))
b = b.point(lambda x: min(255, int(x * blue_ratio)))
# 合并通道
if a:
img_adjusted = Image.merge('RGBA', (r, g, b, a))
else:
img_adjusted = Image.merge('RGB', (r, g, b))
# 保存结果
output_path = os.path.join(output_folder, filename)
img_adjusted.save(output_path)
print(f"处理完成: {filename}")
except Exception as e:
print(f"处理 {filename} 时出错: {e}")
# 使用示例
batch_adjust_color_balance(
input_folder='./images',
output_folder='./adjusted_images',
red_ratio=1.2, # 红色增强20%
green_ratio=1.0, # 绿色不变
blue_ratio=0.8 # 蓝色减少20%
)
使用 OpenCV (更专业的色彩平衡)
import cv2
import numpy as np
import os
def simple_white_balance(img):
"""简单白平衡算法"""
result = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
avg_a = np.average(result[:, :, 1])
avg_b = np.average(result[:, :, 2])
result[:, :, 1] = result[:, :, 1] - ((avg_a - 128) * (result[:, :, 0] / 255.0) * 1.1)
result[:, :, 2] = result[:, :, 2] - ((avg_b - 128) * (result[:, :, 0] / 255.0) * 1.1)
result = cv2.cvtColor(result, cv2.COLOR_LAB2BGR)
return result
def adjust_color_balance_opencv(img, r_gain=1.0, g_gain=1.0, b_gain=1.0):
"""调整RGB增益"""
b, g, r = cv2.split(img)
b = np.clip(b * b_gain, 0, 255).astype(np.uint8)
g = np.clip(g * g_gain, 0, 255).astype(np.uint8)
r = np.clip(r * r_gain, 0, 255).astype(np.uint8)
return cv2.merge([b, g, r])
def batch_process_with_opencv(input_dir, output_dir, use_white_balance=False, **kwargs):
"""批量处理"""
os.makedirs(output_dir, exist_ok=True)
for file in os.listdir(input_dir):
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
img_path = os.path.join(input_dir, file)
img = cv2.imread(img_path)
if img is None:
continue
# 应用白平衡
if use_white_balance:
img = simple_white_balance(img)
# 调整RGB增益
img = adjust_color_balance_opencv(img, **kwargs)
cv2.imwrite(os.path.join(output_dir, file), img)
print(f"已处理: {file}")
# 使用示例
batch_process_with_opencv(
'./images',
'./adjusted',
use_white_balance=True,
r_gain=1.1,
g_gain=0.9,
b_gain=1.0
)
使用 ImageMagick (命令行工具)
#!/bin/bash
# batch_color_balance.sh
input_dir="./images"
output_dir="./adjusted"
mkdir -p "$output_dir"
# 调整色彩平衡: red=120%, green=100%, blue=80%
for img in "$input_dir"/*.{jpg,jpeg,png,bmp,tiff}; do
if [ -f "$img" ]; then
filename=$(basename "$img")
convert "$img" \
-color-matrix "1.2 0 0 0 1.0 0 0 0 0.8" \
"$output_dir/$filename"
echo "处理完成: $filename"
fi
done
使用 GIMP 脚本 (Batch Mode)
#!/usr/bin/env python
# GIMP batch color balance script
from gimpfu import *
import os
def batch_color_balance(input_dir, output_dir, shadows_r=0, shadows_g=0, shadows_b=0,
midtones_r=0, midtones_g=0, midtones_b=0,
highlights_r=0, highlights_g=0, highlights_b=0):
"""
批量调整色彩平衡
参数范围: -100 到 100
"""
for file in os.listdir(input_dir):
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff')):
image_path = os.path.join(input_dir, file)
image = pdb.gimp_file_load(image_path, file)
drawable = pdb.gimp_image_get_active_layer(image)
# 应用色彩平衡
pdb.gimp_color_balance(drawable, 0, # 阴影
True, # 保留亮度
shadows_r, shadows_g, shadows_b)
pdb.gimp_color_balance(drawable, 1, # 中间调
True,
midtones_r, midtones_g, midtones_b)
pdb.gimp_color_balance(drawable, 2, # 高光
True,
highlights_r, highlights_g, highlights_b)
# 保存
output_path = os.path.join(output_dir, file)
pdb.gimp_file_save(image, drawable, output_path, file)
pdb.gimp_image_delete(image)
print(f"处理完成: {file}")
register(
"batch-color-balance",
"Batch Color Balance",
"Adjust color balance for multiple images",
"Your Name",
"Your Name",
"2024",
"Batch Color Balance",
"",
[
(PF_DIRNAME, "input_dir", "Input Directory", ""),
(PF_DIRNAME, "output_dir", "Output Directory", ""),
(PF_INT, "shadows_r", "Shadows Red", 0),
# ... 添加其他参数
],
[],
batch_color_balance,
menu="<Image>/Filters/Batch"
)
main()
进阶:使用深度学习进行智能色彩校正
import torch
import torchvision.transforms as transforms
from PIL import Image
import os
from basicsr.archs.rrdbnet_arch import RRDBNet
from basicsr.utils import img2tensor, tensor2img
# 使用 ESRGAN 等模型进行色彩增强
def batch_ai_color_enhancement(input_dir, output_dir, model_path='RealESRGAN_x4plus.pth'):
"""
使用AI模型进行智能色彩校正
"""
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 加载模型
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
model.load_state_dict(torch.load(model_path)['params'])
model.eval()
model = model.to(device)
os.makedirs(output_dir, exist_ok=True)
for file in os.listdir(input_dir):
if file.lower().endswith(('.png', '.jpg')):
img_path = os.path.join(input_dir, file)
img = Image.open(img_path).convert('RGB')
# 预处理
img_tensor = img2tensor(img, bgr2rgb=True, float32=True).unsqueeze(0).to(device)
# 推理
with torch.no_grad():
output = model(img_tensor)
# 后处理
output_img = tensor2img(output, min_max=(-1, 1))
# 保存结果
output_path = os.path.join(output_dir, file)
Image.fromarray(output_img).save(output_path)
print(f"AI增强完成: {file}")
安装依赖
根据选择的方案安装所需库:
# 方案一 pip install Pillow # 方案二 pip install opencv-python numpy # 方案三 (MacOS) brew install imagemagick # 或 Linux sudo apt-get install imagemagick # 方案四 (需要 GIMP) # 需要单独安装 GIMP 及其 Python 绑定 # 进阶方案 pip install torch torchvision basicsr
使用建议
- 测试先行:先在小批量图片上测试参数效果
- 保留原始文件:始终备份原图
- 参数微调:
- 0 = 不变
- < 1.0 = 减少该通道
-
0 = 增强该通道
- 批量处理:根据图片数量和大小,选择适当的方案
选择哪个方案取决于您的具体需求和技术栈,Python方案最灵活,命令行方案最容易集成到工作流中,而AI方案效果最好但需要更多计算资源。