Crop and save images in a directory using Python

As a CFD engineer, I usually end up having 100+ images in a particular directory which needs to be cropped. I have this handy script to do that. In this, I use the Pillow library.

If you don’t have pillow installed, type the following in your terminal to install it.

python -m pip install Pillow

for more information follow this link

The script is as follows. I am using the os.listdir method from the os module to get the list of files and also make use of the os.path.join method, to make the script work in all operating systems.

from PIL import Image
import os

#Dimensions of the box that crops the image
left=10
right=100
top=10
bottom=100

#Input folder
folder = os.getcwd()        #Here I assume the script and all the images are in the same directory
files= os.listdir(folder)

for file in files:
    if file.endswith(".png"):
        image_original=Image.open(os.path.join(folder,file))
        cropped=image_original.crop((left,top,right,bottom))
        cropped.save(os.path.join(folder,"cropped",file.replace(".png","_cropped.png")))