批量调整图片饱和度的脚本

wen 实用脚本 3

本文目录导读:

批量调整图片饱和度的脚本

  1. 使用说明
  2. 进阶版本(带命令行参数)
  3. 注意事项
import os
from PIL import Image, ImageEnhance
def batch_adjust_saturation(input_dir, output_dir, saturation_factor=1.5):
    """
    批量调整图片饱和度
    参数:
        input_dir (str): 输入图片文件夹路径
        output_dir (str): 输出图片文件夹路径
        saturation_factor (float): 饱和度调整因子
            1.0 = 原始饱和度
            < 1.0 = 降低饱和度 (0.0 = 灰度)
            > 1.0 = 增加饱和度
    """
    # 确保输出文件夹存在
    os.makedirs(output_dir, exist_ok=True)
    # 支持的图片格式
    supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
    # 遍历输入文件夹
    for filename in os.listdir(input_dir):
        if filename.lower().endswith(supported_formats):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            try:
                # 打开图片
                img = Image.open(input_path)
                # 转换为RGB模式(如果是RGBA,保留alpha通道)
                if img.mode == 'RGBA':
                    # 分离通道
                    r, g, b, a = img.split()
                    rgb_img = Image.merge('RGB', (r, g, b))
                    # 调整饱和度
                    enhancer = ImageEnhance.Color(rgb_img)
                    enhanced_rgb = enhancer.enhance(saturation_factor)
                    # 重新合并alpha通道
                    enhanced_img = Image.merge('RGBA', (*enhanced_rgb.split(), a))
                else:
                    # 转为RGB(处理灰度图等情况)
                    if img.mode != 'RGB':
                        img = img.convert('RGB')
                    enhancer = ImageEnhance.Color(img)
                    enhanced_img = enhancer.enhance(saturation_factor)
                # 保存图片
                enhanced_img.save(output_path)
                print(f"已处理: {filename}")
            except Exception as e:
                print(f"处理失败 {filename}: {str(e)}")
if __name__ == "__main__":
    # 使用示例
    input_folder = "input_images"    # 输入文件夹
    output_folder = "output_images"  # 输出文件夹
    # 设置饱和度调整因子
    # 1.5 = 增加50%饱和度
    # 0.5 = 降低50%饱和度
    # 0.0 = 完全去色(灰度)
    saturation_adjustment = 1.5
    batch_adjust_saturation(input_folder, output_folder, saturation_adjustment)
    print("处理完成!")

使用说明

安装依赖

pip install Pillow

目录结构

项目文件夹/
├── input_images/      # 存放待处理的图片
├── output_images/     # 处理后图片输出位置(自动创建)
└── script.py          # 上述脚本

调整参数

修改 saturation_adjustment 变量的值:

  • 0 = 保持原饱和度
  • 5 = 增加 50%(更鲜艳)
  • 0 = 增加 100%(双倍饱和)
  • 5 = 减少 50%(更柔和)
  • 0 = 完全去色(黑白)

运行脚本

python script.py

进阶版本(带命令行参数)

import os
import argparse
from PIL import Image, ImageEnhance
def adjust_saturation(input_dir, output_dir, factor, overwrite=False):
    os.makedirs(output_dir, exist_ok=True)
    supported = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
    processed = 0
    failed = 0
    for filename in os.listdir(input_dir):
        if not filename.lower().endswith(supported):
            continue
        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, filename)
        if os.path.exists(output_path) and not overwrite:
            print(f"跳过已存在: {filename}")
            continue
        try:
            img = Image.open(input_path)
            # 处理带透明通道的图片
            if img.mode == 'RGBA':
                rgb = img.convert('RGB')
                enhancer = ImageEnhance.Color(rgb)
                enhanced_rgb = enhancer.enhance(factor)
                # 重新添加alpha通道
                r, g, b = enhanced_rgb.split()
                _, _, _, a = img.split()
                result = Image.merge('RGBA', (r, g, b, a))
            else:
                if img.mode != 'RGB':
                    img = img.convert('RGB')
                enhancer = ImageEnhance.Color(img)
                result = enhancer.enhance(factor)
            result.save(output_path)
            processed += 1
            print(f"✓ {filename}")
        except Exception as e:
            failed += 1
            print(f"✗ {filename}: {e}")
    print(f"\n完成!处理 {processed} 个文件,失败 {failed} 个")
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="批量调整图片饱和度")
    parser.add_argument("input_dir", help="输入图片文件夹路径")
    parser.add_argument("-o", "--output", default="output", help="输出文件夹路径(默认: output)")
    parser.add_argument("-f", "--factor", type=float, default=1.5, 
                        help="饱和度调整因子(默认: 1.5,范围: 0.0-3.0)")
    parser.add_argument("--overwrite", action="store_true", 
                        help="覆盖已存在的文件")
    args = parser.parse_args()
    # 验证参数
    if args.factor < 0:
        print("错误:饱和度因子不能为负数")
        exit(1)
    adjust_saturation(args.input_dir, args.output, args.factor, args.overwrite)

进阶版本使用方法

# 基本用法
python script.py input_images -o output_images -f 1.5
# 降低饱和度至50%
python script.py input_images -f 0.5
# 制作黑白效果
python script.py input_images -f 0.0
# 覆盖已存在的文件
python script.py input_images -f 2.0 --overwrite

注意事项

  1. 脚本会保留原始文件,不会修改输入文件夹内的图片
  2. 支持的格式:JPG, PNG, BMP, TIFF, WebP
  3. 带透明通道的PNG图片会保留透明度
  4. 调整因子过大(如>3.0)可能会导致色彩失真

抱歉,评论功能暂时关闭!