哪些实用脚本能简化图像处理?

wen 实用脚本 4

本文目录导读:

哪些实用脚本能简化图像处理?

  1. Python 脚本库(最通用、可定制性最强)
  2. Shell 命令行脚本(Linux/macOS,利用 ImageMagick)
  3. Node.js 脚本(适合Web开发者)
  4. 实用工具推荐(非脚本但可集成)
  5. 效率建议
  6. 注意事项

图像处理的实用脚本可以显著提高效率,尤其适合批量操作、格式转换或自动化重复任务,以下按不同使用场景推荐几类实用脚本,并提供具体示例(主要基于Python和Shell):

Python 脚本库(最通用、可定制性最强)

批量调整图片尺寸

from PIL import Image
import os
def resize_images(input_folder, output_folder, target_width=800):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    for filename in os.listdir(input_folder):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            img_path = os.path.join(input_folder, filename)
            with Image.open(img_path) as img:
                # 保持宽高比缩放
                ratio = target_width / img.width
                new_height = int(img.height * ratio)
                img_resized = img.resize((target_width, new_height), Image.Resampling.LANCZOS)
                img_resized.save(os.path.join(output_folder, filename))

特点:可添加水印、格式转换、自动重命名等功能。

去除图片背景(配合 rembg)

from rembg import remove
from PIL import Image
import os
input_path = 'input/photo.jpg'
output_path = 'output/photo_no_bg.png'
with open(input_path, 'rb') as i:
    input_data = i.read()
    output_data = remove(input_data)
    with open(output_path, 'wb') as o:
        o.write(output_data)

批量版:遍历文件夹处理所有图片(需预先安装 pip install rembg)。

智能裁剪(检测主体)

from PIL import Image
import numpy as np
def smart_crop(image_path, output_path, target_ratio=1.0):
    """基于边缘检测的居中裁剪"""
    img = Image.open(image_path)
    # 转为灰度并检测最显著区域(简化版)
    gray = img.convert('L')
    arr = np.array(gray)
    # 找到非白色/非黑色区域(需根据背景调整)
    mask = arr < 200  # 假设主体不是全白
    coords = np.where(mask)
    if len(coords[0]) == 0:
        return  # 无主体则跳过
    # 计算包围盒
    y_min, y_max = coords[0].min(), coords[0].max()
    x_min, x_max = coords[1].min(), coords[1].max()
    # 裁剪至目标宽高比
    crop_width = x_max - x_min
    crop_height = y_max - y_min
    # 此处省略等比缩放逻辑,实际需根据target_ratio调整
    cropped = img.crop((x_min, y_min, x_max, y_max))
    cropped.save(output_path)

Shell 命令行脚本(Linux/macOS,利用 ImageMagick)

批量转换格式(CR2→JPG)

#!/bin/bash
# 批量转换RAW文件为JPG
for file in *.CR2; do
    convert "$file" -resize 1920x1080 -quality 85 "${file%.CR2}.jpg"
done

添加水印覆盖

#!/bin/bash
# 在图片右下角添加半透明水印
for img in *.jpg; do
    composite -dissolve 30% -gravity southeast watermark.png "$img" "watermarked_$img"
done

创建缩略图目录

#!/bin/bash
mkdir -p thumbnails
find . -maxdepth 1 -type f \( -iname '*.jpg' -o -iname '*.png' \) | while read file; do
    convert "$file" -thumbnail 200x200^ -gravity center -extent 200x200 "thumbnails/${file##*/}"
done

Node.js 脚本(适合Web开发者)

Compress Images(配合 Sharp)

const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
async function compressImages(folder) {
    const files = fs.readdirSync(folder).filter(f => /\.(jpe?g|png)$/i.test(f));
    for (const file of files) {
        const inputPath = path.join(folder, file);
        const outputPath = path.join('compressed', file);
        await sharp(inputPath)
            .jpeg({ quality: 80 })  // 或 .png({ compressionLevel: 9 })
            .toFile(outputPath);
    }
}
compressImages('./images');

实用工具推荐(非脚本但可集成)

  • ImageMagick:命令行瑞士军刀,可处理复杂操作(如 convert -morph 创建过渡效果)
  • ExifTool:批量修改元数据(日期、GPS信息等)
  • OpenCV:视频帧提取、人脸检测、边缘检测(适合复杂视觉处理)

效率建议

  1. 优先使用成熟库:避免重复造轮子(如 PIL/Pillowrembgopencv-python
  2. 错误处理:添加 try-except 避免单文件错误中断整个批次
  3. 异步处理:使用 asyncio(Python)或 Promise.all(Node.js)提升I/O密集任务速度
  4. 监控进度:常用 tqdm(Python)或 progress(Node.js)添加进度条

注意事项

  • 版权:仅处理自己有权限的图片
  • 性能:对大量大图处理时,注意内存占用(使用 PIL.Image.open 的流式处理)
  • 备份:脚本可能覆盖原文件,建议先复制到临时目录测试

根据具体需求(如批量调整、格式转换、AI去背景),可以选择上述脚本或组合使用,需要更具体的场景(如电商图片优化、医学图像处理),可以进一步细化需求。

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