实用脚本能自动给图片添加滤镜吗?

wen 实用脚本 1

本文目录导读:

实用脚本能自动给图片添加滤镜吗?

  1. 环境准备
  2. 自动添加滤镜脚本
  3. 进阶版本(支持更多滤镜和参数调整)
  4. 批量处理不同滤镜
  5. 使用说明
  6. 建议

是的,完全可以!我们可以用 Python 编写一个实用脚本,自动给图片添加各种滤镜效果,下面我提供一个基于 Pillow (PIL) 的通用脚本,支持多种滤镜,并且可以批量处理文件夹内的图片。

环境准备

首先安装必要的库:

pip install Pillow

自动添加滤镜脚本

import os
from PIL import Image, ImageFilter, ImageEnhance
from pathlib import Path
def auto_add_filter(input_path, output_path, filter_type='emboss', quality=85):
    """
    自动给图片添加滤镜
    参数:
        input_path: 输入图片路径或文件夹路径
        output_path: 输出路径
        filter_type: 滤镜类型 (emboss, blur, contour, sharpen, smooth, edge_enhance, 
                     grayscale, sepia, invert, brightness_boost, contrast_boost)
        quality: 输出图片质量 (1-100)
    """
    # 确定输入文件列表
    if os.path.isdir(input_path):
        # 支持常见图片格式
        extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
        files = [f for f in Path(input_path).iterdir() 
                if f.suffix.lower() in extensions]
    else:
        files = [Path(input_path)]
    # 确保输出目录存在
    output_dir = Path(output_path)
    output_dir.mkdir(parents=True, exist_ok=True)
    processed_count = 0
    for file_path in files:
        try:
            # 打开图片
            img = Image.open(file_path)
            # 根据滤镜类型应用效果
            filtered_img = apply_filter(img, filter_type)
            # 生成输出文件名
            stem = file_path.stem
            suffix = file_path.suffix.lower()
            output_file = output_dir / f"{stem}_{filter_type}{suffix}"
            # 保存处理后的图片
            if suffix in ('.jpg', '.jpeg'):
                filtered_img.save(output_file, 'JPEG', quality=quality)
            else:
                filtered_img.save(output_file)
            print(f"✓ 已处理: {file_path.name} -> {output_file.name}")
            processed_count += 1
        except Exception as e:
            print(f"✗ 处理失败: {file_path.name} - {str(e)}")
    print(f"\n处理完成!共处理 {processed_count} 张图片")
    return processed_count
def apply_filter(img, filter_type):
    """应用具体滤镜效果"""
    filter_type = filter_type.lower()
    if filter_type == 'emboss':
        return img.filter(ImageFilter.EMBOSS)
    elif filter_type == 'blur':
        return img.filter(ImageFilter.GaussianBlur(radius=5))
    elif filter_type == 'contour':
        return img.filter(ImageFilter.CONTOUR)
    elif filter_type == 'sharpen':
        return img.filter(ImageFilter.SHARPEN)
    elif filter_type == 'smooth':
        return img.filter(ImageFilter.SMOOTH)
    elif filter_type == 'edge_enhance':
        return img.filter(ImageFilter.EDGE_ENHANCE)
    elif filter_type == 'grayscale':
        return img.convert('L').convert('RGB')
    elif filter_type == 'sepia':
        return apply_sepia(img)
    elif filter_type == 'invert':
        return Image.eval(img, lambda x: 255 - x)
    elif filter_type == 'brightness_boost':
        enhancer = ImageEnhance.Brightness(img)
        return enhancer.enhance(1.5)
    elif filter_type == 'contrast_boost':
        enhancer = ImageEnhance.Contrast(img)
        return enhancer.enhance(1.5)
    elif filter_type == 'vintage':
        return apply_vintage_effect(img)
    else:
        print(f"未知滤镜类型: {filter_type},使用原图")
        return img
def apply_sepia(img):
    """应用复古褐色滤镜"""
    # 先转为灰度
    gray = img.convert('L')
    # 创建褐色效果
    width, height = gray.size
    sepia_img = Image.new('RGB', (width, height))
    pixels = gray.load()
    sepia_pixels = sepia_img.load()
    for y in range(height):
        for x in range(width):
            gray_val = pixels[x, y]
            # 褐色调色板
            r = min(int(gray_val * 1.2), 255)
            g = min(int(gray_val * 1.0), 255)
            b = min(int(gray_val * 0.8), 255)
            sepia_pixels[x, y] = (r, g, b)
    return sepia_img
def apply_vintage_effect(img):
    """应用复古效果(混合滤镜)"""
    # 先降低饱和度
    enhancer = ImageEnhance.Color(img)
    img = enhancer.enhance(0.5)
    # 增加对比度
    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(1.2)
    # 轻微模糊
    img = img.filter(ImageFilter.GaussianBlur(radius=1))
    # 添加褐色调
    return apply_sepia(img)
# 使用示例
if __name__ == "__main__":
    # 示例1:处理单张图片
    auto_add_filter(
        input_path="input.jpg",  # 输入图片路径
        output_path="output",    # 输出文件夹
        filter_type="sepia"      # 使用复古褐色滤镜
    )
    # 示例2:批量处理文件夹内所有图片
    auto_add_filter(
        input_path="photos/",     # 输入文件夹
        output_path="filtered/",  # 输出文件夹
        filter_type="emboss",     # 浮雕效果
        quality=90
    )
    # 可用的滤镜类型列表
    """
    1. emboss - 浮雕效果
    2. blur - 高斯模糊
    3. contour - 轮廓
    4. sharpen - 锐化
    5. smooth - 平滑
    6. edge_enhance - 边缘增强
    7. grayscale - 灰度
    8. sepia - 复古褐色
    9. invert - 颜色反转
    10. brightness_boost - 亮度增强
    11. contrast_boost - 对比度增强
    12. vintage - 复古综合效果
    """

进阶版本(支持更多滤镜和参数调整)

如果你想要更丰富的滤镜效果,可以使用更专业的库:

# 安装 OpenCV
pip install opencv-python
# 或者使用 scikit-image
pip install scikit-image

使用 OpenCV 的高级滤镜脚本:

import cv2
import numpy as np
from pathlib import Path
def opencv_auto_filter(input_path, output_path, filter_type='cartoon'):
    """使用 OpenCV 自动添加滤镜"""
    # 确定输入文件列表
    if Path(input_path).is_dir():
        extensions = ('.jpg', '.jpeg', '.png', '.bmp')
        files = [f for f in Path(input_path).iterdir() 
                if f.suffix.lower() in extensions]
    else:
        files = [Path(input_path)]
    output_dir = Path(output_path)
    output_dir.mkdir(parents=True, exist_ok=True)
    for file_path in files:
        # 读取图片
        img = cv2.imread(str(file_path))
        if img is None:
            print(f"无法读取: {file_path}")
            continue
        # 应用滤镜
        if filter_type == 'cartoon':
            result = cartoon_filter(img)
        elif filter_type == 'sketch':
            result = sketch_filter(img)
        elif filter_type == 'pencil':
            result = pencil_filter(img)
        elif filter_type == 'oil':
            result = oil_painting(img)
        else:
            result = img
        # 保存结果
        output_file = output_dir / f"{file_path.stem}_{filter_type}.jpg"
        cv2.imwrite(str(output_file), result)
        print(f"✓ 已处理: {file_path.name}")
def cartoon_filter(img):
    """卡通效果"""
    # 边缘检测
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.medianBlur(gray, 5)
    edges = cv2.adaptiveThreshold(gray, 255, 
                                  cv2.ADAPTIVE_THRESH_MEAN_C, 
                                  cv2.THRESH_BINARY, 9, 9)
    # 颜色量化
    color = cv2.bilateralFilter(img, 9, 300, 300)
    # 组合
    cartoon = cv2.bitwise_and(color, color, mask=edges)
    return cartoon
def sketch_filter(img):
    """素描效果"""
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    inv_gray = 255 - gray
    blur = cv2.GaussianBlur(inv_gray, (21, 21), 0)
    sketch = cv2.divide(gray, 255 - blur, scale=256)
    return cv2.cvtColor(sketch, cv2.COLOR_GRAY2BGR)
def pencil_filter(img):
    """铅笔效果"""
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    pencil = cv2.Canny(gray, 50, 150)
    return cv2.cvtColor(pencil, cv2.COLOR_GRAY2BGR)
def oil_painting(img):
    """油画效果"""
    oil = cv2.xphoto.oilPainting(img, 7, 1)
    return oil
# 使用示例
if __name__ == "__main__":
    opencv_auto_filter("photo.jpg", "output", "cartoon")
    opencv_auto_filter("photos/", "filtered", "sketch")

批量处理不同滤镜

如果你想要对同一批图片应用多个滤镜:

def batch_multi_filters(input_dir, output_dir, filters):
    """对文件夹内所有图片应用多个滤镜"""
    input_path = Path(input_dir)
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)
    for img_file in input_path.glob("*.[jJ][pP][gG]"):
        for filter_name in filters:
            auto_add_filter(
                str(img_file),
                str(output_path),
                filter_type=filter_name
            )
# 同时应用多种滤镜
batch_multi_filters("input/", "output/", 
                    ["emboss", "sepia", "grayscale", "vintage"])

使用说明

  1. 单张图片处理:直接指定图片路径
  2. 批量处理:指定文件夹路径,自动处理所有图片
  3. 保存位置:自动在原文件名后添加滤镜名称
  4. 自定义参数:可以调整 quality、radius 等参数

建议

  • 对于简单滤镜,使用 Pillow 即可
  • 需要卡通、素描等特殊效果时,使用 OpenCV
  • 处理大量图片时,可以添加多线程处理提升速度
  • 建议先在小样本上测试不同滤镜效果

这个脚本完全能满足日常的图片滤镜需求,你可以根据自己的喜好调整参数或添加新的滤镜类型。

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