Two Minds (GPT-4 and me), One Script: Our Brief Python Adventure for image croping

  • Aktualisiert
  • Veröffentlicht in Uncategorized
  • 3 Minuten zum Lesen

I’m thrilled that GPT-4 and I were able to write a Python script within 4 minutes that cuts out an area from all the images in a directory and saves the new image.

Task

In the directory under the path in the variable „path“ are JPEG files that I created with Bing. On the left-bottom of the images is the Bing logo, which I want to remove by removing a rectangle of the image in full width and a height of 100 pixels at the bottom.
I want a Python script to do this for each image and save the cropped image under the same filename with „_new“ appended to it. I created this script below using GPT-4 as described in the following and below you see one of the mentioned images.

My prompt

python, script to crop jpg images

in the variable path is the path to a folder on local drive wirh jpg image files

n_pixel = 20 is a variable

1. open each jpg in the folder

2. crop the image such that its heigt is reduced by n_pixel . a rectange with height n_pixel is cut on the lowest position of the image. the cutted are is from all the left to all the right.

3. save the new image as the old file name with _new attache

My exact prompt including my typos

You can help GPT-4 by avoiding spelling errors. They were in my prompt, but of course I don’t advise making them.

It helps to give some context, such as a brief statement of the desired goal and then indicate the steps in which the task will be solved.

This prompt is not perfect but it was sufficient to reach my goal.

Response

Sure, here’s a Python script that does exactly that:

import os
from PIL import Image

# Set the directory and the number of pixels to crop
directory = os.environ['PATH']
n_pixels = 20

# Loop through each file in the directory
for filename in os.listdir(directory):
    if filename.endswith(".jpg"):
        # Open the image file
        img = Image.open(os.path.join(directory, filename))
        width, height = img.size

        # Crop the image
        img_cropped = img.crop((0, 0, width, height - n_pixels))

        # Save the cropped image
        img_cropped.save(os.path.join(directory, filename.split(".")[0] + "_new.jpg"))

In this script, we’re opening each .jpg file in the specified directory, cropping 20 pixels off the bottom of the image, and then saving the cropped image back to the file system with a new filename that is the old filename with „_new“ appended before the file extension.

Please replace os.environ['PATH'] with the actual path of your directory containing the images.

Result

Well done, little AI…

Schreibe einen Kommentar