Python 保存图像文件的快速方法

Har*_*sad 5 python image image-processing python-imaging-library

我有一个包含 10 000 张图像的文件夹,我在 for 循环中一张一张地迭代,每次处理后我都会将修改后的图像保存在文件中。执行的问题是,即使处理 500 个图像也需要很长时间,而且我看到 Windows 任务管理器中的 CPU 使用率高达 80%。

如何加速下面的代码?像将所有处理过的图像保存在内存中并一次性写入之类的东西吗?

    from PIL import Image
    from resizeimage import resizeimage
    for imgnm in range(0, samples):
        start = time.time()
        filename=filenames[imgnm]
        img = Image.open(os.path.join(imagedir,filename))
        img=resizeimage.resize_crop(img, [700, 700])
        (img.resize((700,700),Image.ANTIALIAS)).save(os.path.join(subdir,filename),quality=40)
        img.close()
Run Code Online (Sandbox Code Playgroud)

hom*_*omm 6

如何加速下面的代码?

  1. 使用最新的 Pillow 版本
  2. 使用 Pillow-SIMD 代替(直接替换至少具有 SSE4 的 CPU)
  3. 使用较便宜的过滤器来调整大小:Image.BICUBIC甚至Image.BILINEAR
  4. 进行一次调整大小和一次裁剪(调整大小之前),而不是同时使用resizeimageimg.resize
  5. 将图像保存为快速格式。不同的格式以不同的速度运行。PNG 最慢,而 JPEG 和 TIFF 最快。