本文目录导读:

- 方法一:使用 Python + Pillow 库
- 方法二:使用更高级的功能(支持色相/饱和度/亮度)
- 方法三:使用 ImageMagick 命令行工具
- 方法四:使用 OpenCV(更快的处理速度)
- 安装依赖
- 使用建议
使用 Python + Pillow 库
from PIL import Image, ImageEnhance
import os
import glob
def adjust_color_balance(img, red_factor=1.0, green_factor=1.0, blue_factor=1.0):
"""
调整图片色彩平衡
red_factor, green_factor, blue_factor: 各通道的调整系数 (0.0-2.0)
"""
# 分离RGB通道
r, g, b = img.split()
# 调整各通道
r = r.point(lambda i: min(255, int(i * red_factor)))
g = g.point(lambda i: min(255, int(i * green_factor)))
b = b.point(lambda i: min(255, int(i * blue_factor)))
# 合并通道
return Image.merge('RGB', (r, g, b))
def batch_adjust(input_folder, output_folder, red=1.0, green=1.0, blue=1.0):
"""批量处理文件夹中的图片"""
# 创建输出文件夹
os.makedirs(output_folder, exist_ok=True)
# 支持的图片格式
formats = ['*.jpg', '*.jpeg', '*.png', '*.bmp']
for fmt in formats:
for filepath in glob.glob(os.path.join(input_folder, fmt)):
# 打开图片
img = Image.open(filepath)
# 调整色彩平衡
adjusted = adjust_color_balance(img, red, green, blue)
# 保存图片
filename = os.path.basename(filepath)
output_path = os.path.join(output_folder, filename)
adjusted.save(output_path)
print(f"已处理: {filename}")
# 使用示例:增加红色,减少蓝色
if __name__ == "__main__":
batch_adjust(
input_folder="input_images",
output_folder="output_images",
red=1.2, # 红色增加20%
green=1.0, # 绿色不变
blue=0.8 # 蓝色减少20%
)
使用更高级的功能(支持色相/饱和度/亮度)
from PIL import Image, ImageEnhance, ImageFilter
import colorsys
import numpy as np
def advanced_color_adjust(img, hue_shift=0, saturation_factor=1.0, lightness_factor=1.0):
"""
高级色彩调整
hue_shift: 色相偏移 (0-360度)
saturation_factor: 饱和度系数
lightness_factor: 明度系数
"""
# 转换为RGB数组
img_array = np.array(img) / 255.0
# 转换为HSL
for y in range(img_array.shape[0]):
for x in range(img_array.shape[1]):
r, g, b = img_array[y, x]
# 转换为HSL
h, l, s = colorsys.rgb_to_hls(r, g, b)
# 调整色相
h = (h + hue_shift / 360) % 1.0
# 调整饱和度
s = min(1.0, max(0.0, s * saturation_factor))
# 调整明度
l = min(1.0, max(0.0, l * lightness_factor))
# 转换回RGB
r, g, b = colorsys.hls_to_rgb(h, l, s)
img_array[y, x] = [r, g, b]
# 转换回8位整数
img_array = (img_array * 255).astype(np.uint8)
return Image.fromarray(img_array)
def batch_advanced_adjust(input_folder, output_folder, **kwargs):
"""批量高级色彩调整"""
import os
import glob
os.makedirs(output_folder, exist_ok=True)
for filepath in glob.glob(os.path.join(input_folder, '*')):
try:
img = Image.open(filepath)
# 转换为RGB模式
if img.mode != 'RGB':
img = img.convert('RGB')
# 应用调整
adjusted = advanced_color_adjust(img, **kwargs)
# 保存
filename = os.path.basename(filepath)
output_path = os.path.join(output_folder, filename)
adjusted.save(output_path)
print(f"已处理: {filename}")
except Exception as e:
print(f"处理 {filepath} 时出错: {e}")
# 使用示例
if __name__ == "__main__":
batch_advanced_adjust(
input_folder="input_images",
output_folder="output_images",
hue_shift=30, # 色相偏移30度
saturation_factor=1.2, # 增加20%饱和度
lightness_factor=0.9 # 减少10%明度
)
使用 ImageMagick 命令行工具
#!/bin/bash
# 批量调整色彩平衡脚本
INPUT_DIR="input_images"
OUTPUT_DIR="output_images"
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
# 批量处理图片(调整RGB通道)
for img in "$INPUT_DIR"/*.{jpg,jpeg,png,bmp}; do
if [ -f "$img" ]; then
filename=$(basename "$img")
# color-matrix: r,g,b:调整RGB通道强度
convert "$img" -color-matrix "1.2 0 0 0 1.0 0 0 0 0.8" "$OUTPUT_DIR/$filename"
echo "已处理: $filename"
fi
done
使用 OpenCV(更快的处理速度)
import cv2
import numpy as np
import os
from pathlib import Path
def batch_adjust_opencv(input_folder, output_folder,
red_gain=1.0, green_gain=1.0, blue_gain=1.0,
brightness=0, contrast=1.0):
"""使用OpenCV批量调整图像"""
# 创建输出文件夹
Path(output_folder).mkdir(parents=True, exist_ok=True)
# 支持的图片格式
extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff']
for filepath in Path(input_folder).iterdir():
if filepath.suffix.lower() in extensions:
# 读取图片
img = cv2.imread(str(filepath))
if img is not None:
# 应用亮度对比度调整
adjusted = cv2.convertScaleAbs(img, alpha=contrast, beta=brightness)
# 应用色彩增益(BGR格式)
adjusted = adjusted.astype(np.float32)
adjusted[:, :, 0] *= blue_gain # B通道
adjusted[:, :, 1] *= green_gain # G通道
adjusted[:, :, 2] *= red_gain # R通道
# 裁剪到有效范围
adjusted = np.clip(adjusted, 0, 255).astype(np.uint8)
# 保存
output_path = Path(output_folder) / filepath.name
cv2.imwrite(str(output_path), adjusted)
print(f"已处理: {filepath.name}")
# 使用示例
batch_adjust_opencv(
input_folder="input_images",
output_folder="output_images",
red_gain=1.3, # 红色增强30%
green_gain=1.1, # 绿色增强10%
blue_gain=0.9, # 蓝色减少10%
brightness=10, # 增加亮度
contrast=1.1 # 增加对比度
)
安装依赖
# 对于 Python 脚本 pip install pillow numpy opencv-python # 对于 ImageMagick # Ubuntu/Debian sudo apt-get install imagemagick # macOS brew install imagemagick # Windows: 下载安装 https://imagemagick.org/script/download.php
使用建议
-
选择合适的工具:
- 小型批量:Python + Pillow(易用性)
- 大型批量:OpenCV(速度更快)
- 命令行操作:ImageMagick
-
调整参数建议:
- 色彩系数:0.8-1.2之间调整
- 饱和度:0.5-1.5之间调整
- 亮度和对比度:小幅度调整
-
备份原图:始终保持原图备份,以便恢复
-
预览效果:可以先处理一张图片测试效果,再批量处理
这些脚本可以根据您的具体需求进行修改和调整。