本文目录导读:

Python + Pillow 脚本(推荐)
from PIL import Image, ImageEnhance
import os
from pathlib import Path
def batch_adjust_contrast(input_dir, output_dir, contrast_factor=1.5):
"""
批量调整图片对比度
参数:
input_dir: 输入文件夹路径
output_dir: 输出文件夹路径
contrast_factor: 对比度因子 (1.0=原始, >1增强, <1减弱)
"""
# 创建输出目录
Path(output_dir).mkdir(parents=True, exist_ok=True)
# 支持的图片格式
extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
for filename in os.listdir(input_dir):
if filename.lower().endswith(extensions):
try:
# 打开图片
img_path = os.path.join(input_dir, filename)
img = Image.open(img_path)
# 调整对比度
enhancer = ImageEnhance.Contrast(img)
img_enhanced = enhancer.enhance(contrast_factor)
# 保存图片
output_path = os.path.join(output_dir, f"contrast_{filename}")
img_enhanced.save(output_path)
print(f"✓ 已处理: {filename}")
except Exception as e:
print(f"✗ 处理失败 {filename}: {str(e)}")
# 使用示例
if __name__ == "__main__":
# 调整参数
INPUT_DIR = "input_images" # 输入文件夹
OUTPUT_DIR = "output_images" # 输出文件夹
CONTRAST_FACTOR = 1.5 # 1.5倍对比度
batch_adjust_contrast(INPUT_DIR, OUTPUT_DIR, CONTRAST_FACTOR)
高级版:支持对比度范围和自动均衡
import cv2
import numpy as np
import os
def auto_contrast(img, clip_percent=1):
"""自动对比度均衡"""
# 计算直方图
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
# 计算累计直方图
cdf = hist.cumsum()
cdf_normalized = cdf / cdf[-1]
# 找到裁剪点
low_val = np.searchsorted(cdf_normalized, clip_percent/100)
high_val = np.searchsorted(cdf_normalized, 1 - clip_percent/100)
# 应用对比度拉伸
img_stretched = np.clip((img - low_val) * 255 / (high_val - low_val), 0, 255).astype(np.uint8)
return img_stretched
def batch_adjust_contrast_advanced(input_dir, output_dir, method='manual', factor=1.5, clip_percent=1):
"""
批量调整对比度(高级版)
参数:
method: 'manual' 手动调节, 'auto' 自动均衡, 'clahe' 自适应直方图均衡
"""
Path(output_dir).mkdir(parents=True, exist_ok=True)
extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
for filename in os.listdir(input_dir):
if filename.lower().endswith(extensions):
try:
img_path = os.path.join(input_dir, filename)
img = cv2.imread(img_path)
if method == 'manual':
# 手动调整对比度
img_adjusted = cv2.convertScaleAbs(img, alpha=factor, beta=0)
suffix = f"contrast_{factor}"
elif method == 'auto':
# 自动对比度均衡
img_adjusted = auto_contrast(img, clip_percent)
suffix = "auto_equalized"
elif method == 'clahe':
# CLAHE (自适应直方图均衡)
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
l = clahe.apply(l)
lab = cv2.merge([l, a, b])
img_adjusted = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
suffix = "clahe"
# 保存结果
name, ext = os.path.splitext(filename)
output_path = os.path.join(output_dir, f"{name}_{suffix}{ext}")
cv2.imwrite(output_path, img_adjusted)
print(f"✓ 已处理: {filename} -> {suffix}")
except Exception as e:
print(f"✗ 处理失败 {filename}: {str(e)}")
# 使用示例
batch_adjust_contrast_advanced(
"input_images",
"output_images",
method='manual', # 可选: 'manual', 'auto', 'clahe'
factor=1.5,
clip_percent=1
)
命令行工具:ImageMagick
# 安装ImageMagick (如果未安装)
# macOS: brew install imagemagick
# Ubuntu: sudo apt-get install imagemagick
# 批量调整对比度(所有jpg文件)
for file in *.jpg; do
convert "$file" -contrast-stretch 10%x10% "enhanced_$file"
done
# 更精确的对比度调整(+50%对比度)
for file in *.jpg; do
convert "$file" -sigmoidal-contrast 50,50% "contrast_$file"
done
图形化批量处理工具
Adobe Bridge + Camera Raw
- 在Bridge中选中所有图片
- 右键选择"在Camera Raw中打开"
- 调整一张图片的对比度
- 全选,同步设置
FastStone Image Viewer
- 打开图片文件夹
- 选择所有图片 (Ctrl+A)
- 工具 → 批量转换 → 调整对比度
- 设置参数并执行
性能优化版(多线程处理)
from concurrent.futures import ThreadPoolExecutor, as_completed
from PIL import Image, ImageEnhance
import os
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
def process_image(args):
"""处理单张图片"""
input_path, output_dir, contrast_factor = args
try:
filename = os.path.basename(input_path)
img = Image.open(input_path)
enhancer = ImageEnhance.Contrast(img)
img_enhanced = enhancer.enhance(contrast_factor)
output_path = os.path.join(output_dir, f"contrast_{filename}")
img_enhanced.save(output_path, quality=95)
return f"✓ {filename}"
except Exception as e:
return f"✗ {filename}: {str(e)}"
def batch_adjust_contrast_multithread(input_dir, output_dir, contrast_factor=1.5, max_workers=4):
"""多线程批量处理"""
Path(output_dir).mkdir(parents=True, exist_ok=True)
extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
image_paths = [
os.path.join(input_dir, f)
for f in os.listdir(input_dir)
if f.lower().endswith(extensions)
]
# 准备参数
args_list = [(path, output_dir, contrast_factor) for path in image_paths]
# 多线程处理
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(process_image, args) for args in args_list]
for future in as_completed(futures):
result = future.result()
logging.info(result)
logging.info(f"处理完成!共处理 {len(image_paths)} 张图片")
# 使用示例
batch_adjust_contrast_multithread(
"input_images",
"output_images",
contrast_factor=1.5,
max_workers=8 # 根据CPU核心数调整
)
使用建议
-
对比度因子说明:
- 0:保持原样
- 0-2.0:增强对比度(推荐1.2-1.8)
- 0-1.0:降低对比度
-
选择合适的方法:
- 简单批量:使用Pillow脚本
- 需要自动优化:使用OpenCV的CLAHE
- 大量图片:使用多线程版本
- 图形界面:使用FastStone或Bridge
-
备份原始文件:处理前建议复制一份原图