kdog
kdog

Reputation: 3

Batch image manipulation with PIL?

I have just come across the pythons PIL library while working on a project, so very new to this.

My simple program imports one image from a directory, applies the desired manipulation with PIL, then saves it into a different folder.

My question - Can I batch import a directory with multiple images and run the desired manipulation for all images within that directory in PIL?

Upvotes: 0

Views: 3583

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

In general, when working with images which are often quite demanding on memory, it is not the best idea to batch load thousands of images into memory, then process them all, then write them all out as you create an enormous demand on your computer's RAM which can slow it down. That leads to code more like this:

#!/usr/bin/env python3

import glob
from PIL import Image

def ProcessOne(f):
   print(f'Opening {f}')
   im = Image.open(f)
   ... process ...
   ... process ...

if __name__ == '__main__':

   # Create a list of files to process
   files = [f for f in glob.glob("*.jpg")]

   for f in files:
       ProcessOne(f)

Also, if you are doing the same processing on lots of images, it is then generally a reasonable idea to use Python's multiprocessing module, because, on its own, Python will not use all those lovely CPU cores that you paid Intel so handsomely for and this is a serious consideration as CPUs continue to get fatter (more cores) rather than taller (more GHz). That leads to code more like this example which is hardly any more difficult to write or read:

#!/usr/bin/env python3

import glob
from multiprocessing import Pool
from PIL import Image

def ProcessOne(f):
    im = Image.open(f)
    ... process ...


if __name__ == '__main__':
    # Create a pool of processes to check files
    p = Pool()

    # Create a list of files to process
    files = [f for f in glob.glob("*.jpg")]

    print(f'Files to process: {len(files)}')

    # Map the list of files to check onto the Pool
    p.map(ProcessOne, files)

Note also that you can use ImageMagick to simply process hundreds of files and write the results into a different directory. So, say you wanted to normalise the brightness level of a whole directory full of JPEGs and write the modified files into a directory called OUTPUT, you could just do this in Terminal:

mkdir -p OUTPUT
magick mogrify -path OUTPUT -auto-level *.jpg

Upvotes: 6

Related Questions