Hari Prasad
Hari Prasad

Reputation: 1901

Fast way to save Image Files Python

I have a folder of 10 000 images and I am iterating one by one in a for loop and every time after processing I am saving the modified image in a file. Problem with the execution is it is taking long time to process even 500 images and I see CPU Usage in Windows Task Manager are going up to 80%.

How to speed up below code? Anything like save all processed image in memory and write it at single shot?

    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()

Upvotes: 5

Views: 12737

Answers (1)

homm
homm

Reputation: 2262

How to speed up below code?

  1. Use latest Pillow version
  2. Use Pillow-SIMD instead (drop-in replacement for CPUs with at least SSE4)
  3. Use the less expensive filter for resizing: Image.BICUBIC or even Image.BILINEAR
  4. Do one resize and one crop (before resize) instead of using both resizeimage and img.resize.
  5. Save images to the fast format. Different formats operate at a different speed. PNG in the slowest one, while JPEG and TIFF are the fastest.

Upvotes: 6

Related Questions