脚本如何批量调整图片颜色映射

wen 实用脚本 23

本文目录导读:

脚本如何批量调整图片颜色映射

  1. 使用Python + Pillow(轻量级)
  2. 使用Python + OpenCV(高级处理)
  3. 使用ImageMagick命令行(最快速批量处理)
  4. 使用Python + NumPy自定义颜色映射
  5. 使用ffmpeg处理视频帧(视频转图片批量处理)
  6. 安装依赖
  7. 使用建议

使用Python + Pillow(轻量级)

from PIL import Image, ImageEnhance
import os
import glob
def batch_adjust_color_mapping(input_dir, output_dir, **kwargs):
    """
    批量调整图片颜色映射
    :param input_dir: 输入目录
    :param output_dir: 输出目录
    :param kwargs: 调整参数
        - brightness: 亮度因子 (0.0-2.0)
        - contrast: 对比度因子 (0.0-2.0)
        - color: 色彩饱和度 (0.0-2.0)
        - sharpness: 锐度 (0.0-2.0)
    """
    os.makedirs(output_dir, exist_ok=True)
    for img_path in glob.glob(os.path.join(input_dir, "*.*")):
        try:
            # 支持常见格式
            if img_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):
                img = Image.open(img_path)
                # 应用各项调整
                if 'brightness' in kwargs:
                    enhancer = ImageEnhance.Brightness(img)
                    img = enhancer.enhance(kwargs['brightness'])
                if 'contrast' in kwargs:
                    enhancer = ImageEnhance.Contrast(img)
                    img = enhancer.enhance(kwargs['contrast'])
                if 'color' in kwargs:
                    enhancer = ImageEnhance.Color(img)
                    img = enhancer.enhance(kwargs['color'])
                if 'sharpness' in kwargs:
                    enhancer = ImageEnhance.Sharpness(img)
                    img = enhancer.enhance(kwargs['sharpness'])
                # 保存结果
                base_name = os.path.basename(img_path)
                output_path = os.path.join(output_dir, f"adjusted_{base_name}")
                img.save(output_path)
                print(f"已处理: {base_name}")
        except Exception as e:
            print(f"处理 {img_path} 时出错: {e}")
# 使用示例
if __name__ == "__main__":
    batch_adjust_color_mapping(
        "input_images",
        "output_images",
        brightness=1.2,    # 增加亮度
        contrast=1.1,      # 增加对比度
        color=1.3,         # 增加饱和度
        sharpness=0.9      # 略微降低锐度
    )

使用Python + OpenCV(高级处理)

import cv2
import numpy as np
import os
import glob
def advanced_color_adjustment(input_dir, output_dir):
    """
    高级颜色调整 - 包括直方图均衡化和颜色校正
    """
    os.makedirs(output_dir, exist_ok=True)
    for img_path in glob.glob(os.path.join(input_dir, "*.*")):
        try:
            if img_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
                img = cv2.imread(img_path)
                # 1. 颜色空间转换和调整
                hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
                h, s, v = cv2.split(hsv)
                # 调整饱和度和亮度
                s = np.clip(s * 1.2, 0, 255).astype(np.uint8)
                v = np.clip(v * 1.1, 0, 255).astype(np.uint8)
                # 合并并转换回BGR
                hsv_adjusted = cv2.merge([h, s, v])
                img_adjusted = cv2.cvtColor(hsv_adjusted, cv2.COLOR_HSV2BGR)
                # 2. 直方图均衡化(LAB颜色空间)
                lab = cv2.cvtColor(img_adjusted, cv2.COLOR_BGR2LAB)
                l, a, b = cv2.split(lab)
                clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
                l_equalized = clahe.apply(l)
                lab_equalized = cv2.merge([l_equalized, a, b])
                img_final = cv2.cvtColor(lab_equalized, cv2.COLOR_LAB2BGR)
                # 保存结果
                base_name = os.path.basename(img_path)
                output_path = os.path.join(output_dir, f"enhanced_{base_name}")
                cv2.imwrite(output_path, img_final)
                print(f"已处理: {base_name}")
        except Exception as e:
            print(f"处理 {img_path} 时出错: {e}")
# 使用示例
if __name__ == "__main__":
    advanced_color_adjustment("input_images", "output_images")

使用ImageMagick命令行(最快速批量处理)

#!/bin/bash
# 批量调整颜色映射 - ImageMagick版本
INPUT_DIR="input_images"
OUTPUT_DIR="output_images"
mkdir -p "$OUTPUT_DIR"
# 使用convert命令批量处理
for img in "$INPUT_DIR"/*.{jpg,jpeg,png,bmp,tiff}; do
    if [ -f "$img" ]; then
        filename=$(basename "$img")
        # 调整颜色:亮度+15%,对比度+20%,饱和度+10%
        convert "$img" \
            -brightness-contrast 15x20 \
            -modulate 100,110,100 \
            -sigmoidal-contrast 5,50% \
            "$OUTPUT_DIR/adjusted_$filename"
        echo "已处理: $filename"
    fi
done

使用Python + NumPy自定义颜色映射

import numpy as np
from PIL import Image
import os
import glob
def custom_lut_adjustment(input_dir, output_dir):
    """
    使用查找表(LUT)自定义颜色映射
    """
    def create_color_lut():
        """创建自定义颜色查找表"""
        lut = np.zeros((256, 3), dtype=np.uint8)
        # 示例:增强蓝色通道,降低红色通道
        for i in range(256):
            lut[i] = [
                int(i * 0.9),    # R通道:降低10%
                int(i * 1.0),    # G通道:保持不变
                int(i * 1.2)     # B通道:增加20%
            ]
        return lut
    os.makedirs(output_dir, exist_ok=True)
    lut = create_color_lut()
    for img_path in glob.glob(os.path.join(input_dir, "*.*")):
        try:
            if img_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
                img = Image.open(img_path).convert('RGB')
                img_array = np.array(img)
                # 应用LUT
                adjusted_array = np.zeros_like(img_array)
                for channel in range(3):
                    adjusted_array[:,:,channel] = lut[:,channel][img_array[:,:,channel]]
                # 保存结果
                adjusted_img = Image.fromarray(adjusted_array)
                base_name = os.path.basename(img_path)
                output_path = os.path.join(output_dir, f"lut_{base_name}")
                adjusted_img.save(output_path)
                print(f"已处理: {base_name}")
        except Exception as e:
            print(f"处理 {img_path} 时出错: {e}")
if __name__ == "__main__":
    custom_lut_adjustment("input_images", "output_images")

使用ffmpeg处理视频帧(视频转图片批量处理)

import subprocess
import os
import glob
def batch_video_frame_processing(input_video, output_dir):
    """
    从视频中提取帧并进行颜色调整
    """
    os.makedirs(output_dir, exist_ok=True)
    # 提取所有帧并应用颜色滤镜
    cmd = [
        'ffmpeg',
        '-i', input_video,
        '-vf', 'eq=brightness=0.1:contrast=1.2:saturation=1.3',
        '-q:v', '2',
        f'{output_dir}/frame_%05d.jpg'
    ]
    subprocess.run(cmd)
    print("视频帧处理完成")
# 批量处理多个视频
def batch_process_videos(video_dir, output_dir):
    for video in glob.glob(os.path.join(video_dir, "*.*")):
        if video.lower().endswith(('.mp4', '.avi', '.mov')):
            video_name = os.path.splitext(os.path.basename(video))[0]
            video_output = os.path.join(output_dir, video_name)
            batch_video_frame_processing(video, video_output)
if __name__ == "__main__":
    batch_process_videos("input_videos", "output_frames")

安装依赖

# Pillow安装
pip install Pillow
# OpenCV安装
pip install opencv-python
# ImageMagick安装
# macOS: brew install imagemagick
# Ubuntu: sudo apt-get install imagemagick
# Windows: 下载安装包
# FFmpeg安装
# macOS: brew install ffmpeg
# Ubuntu: sudo apt-get install ffmpeg
# Windows: 下载安装包

使用建议

  1. 小批量测试:先对几张图片测试参数效果
  2. 保留原图:输出到不同目录,避免覆盖
  3. 性能优化:大量图片时考虑多线程处理
  4. 格式统一:处理前统一图片格式和色彩空间
  5. 参数调整:根据实际需求调整各参数的数值

选择哪种方法取决于你的具体需求:Pillow适合简单调整,OpenCV适合高级处理,ImageMagick适合命令行批量操作。

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