Home > Back-end >  How to Crop Multiple Images
How to Crop Multiple Images

Time:09-11

I'm working on a project to crop 3000 images. I have created 3000 images using an algorithm, and am trying to crop them. Currently, they are all sitting in a folder with names that follow the same format - "img1", "img2", "img3" etc. I have tried using online tools to crop all of these images but it isn't working. I'm looking for an approach, whether using a free software to crop all of them at once or using python to crop these images and store them in a separate folder.

CodePudding user response:

I have written a small code to do that for you.

pip install opencv-python

import cv2 as cv
import os

#First get the list of images in the folder
list_of_original_images = os.listdir("images") #Add the path to the folder

#Create a new directory to store the cropped images
os.mkdir("Cropped_Images")

#Iterate through the image_list
for image_path in list_of_original_images:
    image_array = cv.imread(image_path) # Here we load image using opencv
    height,width,channel = image_array.shape #Here we get the height,width and color channel
    cropped_image = image_array[0:height//2,0:width//2] # Using array slicing we cut some part of the image and save in a new variable

    # Write cropped image to Cropped Images folder
    cv.write(f"Cropped_Images/{image_path}",cropped_image)

CodePudding user response:

Using the Pillow library makes it quite easy:

from PIL import Image;

DirectoryPath = r"C:\Users\...\FolderWithImages";
Images = GetFiles(DirectoryPath);

for Img in Images:
    BaseImg = Image.open(Img);
    
    #The arguments to .crop is a rect (X,Y,Width,Height)
    CroppedImg = im.crop((0,0,500,500))
     
    CroppedImg.save("Path");

To get all files in a directory you can look here

  • Related