Cropping bulk images with the same dimensions in python script

For this week, I would like to share about cropping the bulk images with the same dimensions in python. This method is useful in some cases that image processing or some steps of computer vision projects. The following python script is to crop all images in a folder and save the result to another folder. I used Pillow image library to crop images.

Note: All images to be cropped must be the same dimensions.

First, import required libraries.

import os
import glob  # pip install glob2
from PIL import Image  # pip install Pillow
from pyfiglet import Figlet  # pip install pyfiglet

Program flow is to ask user for the bulk image directory path , desired output directory path and coordinates to be cropped. Then crop all images and save the result to output directory.

def main():
        getDirandFiletype()
        getCoordinate()
        for x in filenames:
            name = x.replace(img_dir, '')
            img = Image.open(str(x))
            region = img.crop((left, top,right, bottom))
            region.save(outpath + name)
        print(custom_fig.renderText('Done!'))

Then in getDirandFiletype() function, the user is asked for image path and output path and read all files in the path with the help of glob library. And also show dimension of each image to be cropped.

def getDirandFiletype():
        global img_dir, outpath, filenames

        print("Please enter Your Images Path.  eg:D:\Download\jaffedbase\n\n########################################")
        img_dir = input("\nWhat is your image directory path : ")
        outpath = input("\nWhat is your output path where to be saved : ")
        
        while(outpath == img_dir):
            print('\nEnter a different path with the image directory!!')
            outpath = input("\nWhat is your output path where to be saved : ")

        filetype = input("\nEnter file type (eg: png) : ")
        data_path = os.path.join(img_dir)
        # read all files in the path mentioned
        filenames = glob.glob(data_path + "/*." + filetype)
        processed = 0
        for file in filenames:
            img = Image.open(str(file))
            width, height = img.size
            print("\nDimension of source images : "+str(width),str(height))
            processed += 1
            if processed >= 1:
                break 

And in getCoordinate() function, the user is asked for the cropping area with left, top, right, bottom coordinates. Pillow image library is used for cropping.

def getCoordinate():
        global left, top, right, bottom, img
        left = int(input("\nEnter left coordinate : "))  
        top = int(input("Enter top coordinate : "))  
        right = int(input("Enter right coordinate : "))  
        bottom = int(input("Enter bottom coordinate : ")) 

That is all. The final code with error handling and beautiful text render with pyfliglet library is as follows.

import os
import glob  # pip install glob2
from PIL import Image  # pip install Pillow
from pyfiglet import Figlet  # pip install pyfiglet

try:
    custom_fig = Figlet(font='standard')
    def main():
        getDirandFiletype()
        getCoordinate()
        for x in filenames:
            name = x.replace(img_dir, '')
            img = Image.open(str(x))
            region = img.crop((left, top,right, bottom))
            region.save(outpath + name)
        print(custom_fig.renderText('Done!'))
        
    def getDirandFiletype():
        global img_dir, outpath, filenames

        print("Please enter Your Images Path.  eg:D:\Download\jaffedbase\n\n########################################")
        img_dir = input("\nWhat is your image directory path : ")
        outpath = input("\nWhat is your output path where to be saved : ")
        
        while(outpath == img_dir):
            print('\nEnter a different path with the image directory!!')
            outpath = input("\nWhat is your output path where to be saved : ")

        filetype = input("\nEnter file type (eg: png) : ")
        data_path = os.path.join(img_dir)
        # read all files in the path mentioned
        filenames = glob.glob(data_path + "/*." + filetype)
        processed = 0
        for file in filenames:
            img = Image.open(str(file))
            width, height = img.size
            print("\nDimension of source images : "+str(width),str(height))
            processed += 1
            if processed >= 1:
                break 
            
    def getCoordinate():
        global left, top, right, bottom, img
        left = int(input("\nEnter left coordinate : "))  # 50
        top = int(input("Enter top coordinate : "))  # 50
        right = int(input("Enter right coordinate : "))  # 190
        bottom = int(input("Enter bottom coordinate : "))  # 235
    
    
    main()
except SystemError:
    print("\nSorry Buddy. Your Coordinates are invalid. Plese Check Coordinates Again!")
except ValueError:
    print("\nPlease use Only Numbers for Coordinates!")

Images to be cropped are as follows.

The resulted images are as follows.

Hope you enjoyed about this.

By Asahi



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム