本文目录导读:

- 使用Python + Pillow库
- 使用OpenCV + Python
- 使用ImageMagick命令行工具
- 使用Photoshop脚本(JavaScript)
- 使用GIMP批处理
- 完整的批处理脚本示例
- 使用建议
使用Python + Pillow库
from PIL import Image, ImageEnhance, ImageOps
import os
import glob
def batch_adjust_levels(input_dir, output_dir, black_point=0, white_point=255):
"""
批量调整色阶
black_point: 黑场 (0-255)
white_point: 白场 (0-255)
"""
# 创建输出目录
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 获取所有图片
for img_path in glob.glob(os.path.join(input_dir, "*.[jJ][pP][gG]")):
img = Image.open(img_path)
# 自动色阶调整
if black_point != 0 or white_point != 255:
img = ImageOps.autocontrast(img, cutoff=0)
img = ImageOps.equalize(img)
# 手动色阶调整
if black_point > 0 or white_point < 255:
img = img.point(lambda x: max(0, min(255,
(x - black_point) * 255 / (white_point - black_point))))
# 保存
output_path = os.path.join(output_dir, os.path.basename(img_path))
img.save(output_path)
# 使用示例
batch_adjust_levels("input_folder", "output_folder", black_point=20, white_point=235)
使用OpenCV + Python
import cv2
import numpy as np
import os
def batch_adjust_histogram(input_dir, output_dir):
"""使用直方图均衡化"""
for filename in os.listdir(input_dir):
if filename.endswith(('.jpg', '.png', '.jpeg')):
img_path = os.path.join(input_dir, filename)
img = cv2.imread(img_path)
# 转换为YUV色彩空间
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
# 对Y通道进行直方图均衡化
img_yuv[:,:,0] = cv2.equalizeHist(img_yuv[:,:,0])
# 转换回BGR
img_equalized = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)
# 保存
output_path = os.path.join(output_dir, filename)
cv2.imwrite(output_path, img_equalized)
使用ImageMagick命令行工具
# 批量自动色阶
for file in *.jpg; do
convert "$file" -auto-level "output/${file}"
done
# 批量手动调整色阶(黑点30,白点225)
for file in *.jpg; do
convert "$file" -level 10%,90% "output/${file}"
done
# 批量归一化
for file in *.jpg; do
convert "$file" -normalize "output/${file}"
done
使用Photoshop脚本(JavaScript)
// Photoshop 批量色阶调整脚本
var inputFolder = Folder.selectDialog("选择图片文件夹");
var outputFolder = Folder.selectDialog("选择输出文件夹");
var files = inputFolder.getFiles(/\.(jpg|jpeg|png|tif)$/i);
for (var i = 0; i < files.length; i++) {
var doc = app.open(files[i]);
// 创建色阶调整图层
var levelAdjust = doc.artLayers.add();
levelAdjust.kind = LayerKind.SOLIDFILL;
levelAdjust.adjustments.levels([0, 1.0, 255]); // [阴影, 中间调, 高光]
// 或使用自动色阶
// doc.autoLevels();
// 保存为JPEG
var saveFile = new File(outputFolder + "/" + files[i].name);
var jpegOptions = new JPEGSaveOptions();
jpegOptions.quality = 12;
doc.saveAs(saveFile, jpegOptions, true);
doc.close(SaveOptions.DONOTSAVECHANGES);
}
使用GIMP批处理
# GIMP Python脚本
from gimpfu import *
import os
def batch_levels_adjust(input_dir, output_dir):
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.jpg', '.png')):
img_path = os.path.join(input_dir, filename)
image = pdb.gimp_file_load(img_path, filename)
drawable = pdb.gimp_image_get_active_drawable(image)
# 自动色阶
pdb.gimp_levels_stretch(drawable)
# 或手动调整
# pdb.gimp_levels(drawable, HISTOGRAM_VALUE,
# low_input, high_input, gamma,
# low_output, high_output)
# 保存
output_path = os.path.join(output_dir, filename)
pdb.gimp_file_save(image, drawable, output_path, filename)
pdb.gimp_image_delete(image)
pdb.register("batch_levels_adjust", ...)
完整的批处理脚本示例
import argparse
import os
from PIL import Image, ImageOps
import concurrent.futures
class BatchLevelAdjuster:
def __init__(self, input_dir, output_dir):
self.input_dir = input_dir
self.output_dir = output_dir
os.makedirs(output_dir, exist_ok=True)
def adjust_levels(self, img_path, method='auto', **kwargs):
"""调整单张图片色阶"""
img = Image.open(img_path)
if method == 'auto':
# 自动色阶
img = ImageOps.autocontrast(img, cutoff=0.5)
elif method == 'equalize':
# 直方图均衡化
img = ImageOps.equalize(img)
elif method == 'manual':
# 手动调整
black = kwargs.get('black', 0)
white = kwargs.get('white', 255)
gamma = kwargs.get('gamma', 1.0)
# 实现色阶映射
def level_map(x):
if x <= black:
return 0
elif x >= white:
return 255
else:
return int(((x - black) / (white - black)) ** gamma * 255)
img = img.point(level_map)
return img
def process_batch(self, method='auto', **kwargs):
"""批量处理所有图片"""
files = [f for f in os.listdir(self.input_dir)
if f.lower().endswith(('.jpg', '.png', '.jpeg'))]
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
for file in files:
img_path = os.path.join(self.input_dir, file)
output_path = os.path.join(self.output_dir, file)
future = executor.submit(
self.process_single,
img_path, output_path, method, **kwargs
)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
try:
future.result()
print(f"完成: {future}")
except Exception as e:
print(f"错误: {e}")
def process_single(self, img_path, output_path, method, **kwargs):
"""处理单张图片"""
img = self.adjust_levels(img_path, method, **kwargs)
img.save(output_path)
# 使用示例
if __name__ == "__main__":
adjuster = BatchLevelAdjuster("input", "output")
# 自动色阶
adjuster.process_batch(method='auto')
# 或手动设置
# adjuster.process_batch(method='manual', black=20, white=235, gamma=1.2)
使用建议
- 小批量测试:先处理几张图片查看效果
- 备份原图:始终保留原始文件
- 调整参数:根据图片类型调整参数:
- 风景图:色阶调整范围大些
- 人像图:保持自然柔和
- 产品图:确保准确还原
这些脚本可以帮你快速批量处理大量图片的色阶问题。