ITPub博客

首页 > 应用开发 > Python > python编写并行化图像处理脚本。

python编写并行化图像处理脚本。

原创 Python 作者:tiannuo 时间:2026-05-08 17:38:05 0 删除 编辑

使用 concurrent.futures 并行处理图片

import os

from concurrent.futures import ProcessPoolExecutor, as_completed

from PIL import Image, ImageFilter


# 输入输出目录

INPUT_DIR = "input_images"

OUTPUT_DIR = "output_images"


os.makedirs(OUTPUT_DIR, exist_ok=True)


# 图像处理函数

def process_image(file_path):

    try:

        img = Image.open(file_path)


        # 示例操作: 转灰度 + 模糊滤镜 + 缩放

        img = img.convert("L")  # 灰度

        img = img.filter(ImageFilter.GaussianBlur(2))  # 模糊

        img = img.resize((img.width // 2, img.height // 2))  # 缩小一半


        # 保存处理后的图片

        base_name = os.path.basename(file_path)

        save_path = os.path.join(OUTPUT_DIR, base_name)

        img.save(save_path)


        return f"处理完成: {base_name}"

    except Exception as e:

        return f"处理失败: {file_path}, 错误: {e}"


def main():

    # 获取所有图片文件

    image_files = [

        os.path.join(INPUT_DIR, f)

        for f in os.listdir(INPUT_DIR)

        if f.lower().endswith((".png", ".jpg", ".jpeg", ".bmp"))

    ]


    print(f"发现 {len(image_files)} 张图片,开始并行处理...")


    # 使用多进程并行处理

    with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor:

        # 提交所有任务

        futures = [executor.submit(process_image, f) for f in image_files]


        # 输出处理结果

        for future in as_completed(futures):

            print(future.result())


    print("所有图片处理完成!")


if __name__ == "__main__":

    main()

说明

并行化

使用 ProcessPoolExecutor 利用多核 CPU 并行处理图片

如果处理 I/O 密集型操作,也可以换成 ThreadPoolExecutor

可扩展图像操作

可以在 process_image 函数中加入:

OpenCV 图像处理(Canny, Threshold, Morphology…)

水印叠加

图像增强

格式转换

自动发现图片

支持 .png, .jpg, .jpeg, .bmp 等常见格式

可按需扩展

保存到输出目录

输出目录自动创建

原文件名保持不变

异常处理

防止单张图片出错影响其他图片处理


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70050070/viewspace-3117349/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2026-05-08

  • 博文量
    74
  • 访问量
    66697