[Python] Cropping Images with Pillow: The crop Method and Coordinate Rules

When you want to extract only a specific part of an image or remove an unnecessary background (cropping), use the crop() method.

The most important part of this method is how to define the four coordinates (tuple) that specify the cropping area. Here, I will explain the correct rules for specifying coordinates and provide implementation code.

目次

Executable Sample Code

The following code is a script that specifies a part of an image, crops it, and saves it as a new image file.

from PIL import Image
import os

def crop_image_demo():
    input_filename = "pillow_sample.jpg"
    output_filename = "pillow_crop.jpg"

    # Create image for verification (if file doesn't exist)
    if not os.path.exists(input_filename):
        create_test_image(input_filename)

    try:
        with Image.open(input_filename) as img:
            print(f"Original Size: {img.size}")

            # Specify cropping area (left, upper, right, lower)
            # Example: From top-left (400, 500) to bottom-right (525, 625)
            crop_area = (400, 500, 525, 625)

            # Execute image cropping
            # The crop method returns a cropped new Image object
            # *The original image (img) is not modified
            cropped_img = img.crop(crop_area)

            # Save
            cropped_img.save(output_filename)
            print(f"Cropped image saved: {output_filename}")
            print(f"Cropped Size: {cropped_img.size}")

    except Exception as e:
        print(f"Error occurred: {e}")

def create_test_image(filename):
    """Create a larger image for verification (800x800)"""
    img = Image.new("RGB", (800, 800), color=(200, 200, 200))
    # It is possible to draw markers near the center, but kept simple with a single color here
    img.save(filename)
    print(f">> Created test image: {filename}")

if __name__ == "__main__":
    crop_image_demo()

Explanation: How to Specify the Cropping Area (Box)

You pass the following four values as a tuple (left, upper, right, lower) to the argument of the crop() method.

# (x-coordinate of left edge, y-coordinate of top edge, x-coordinate of right edge, y-coordinate of bottom edge)
box = (400, 500, 525, 625)
image.crop(box)

Coordinate Rules (Important)

In Python’s Pillow, the coordinate system starts with (0, 0) at the top-left of the image.

  • left (400): X-coordinate of the cropping start position
  • upper (500): Y-coordinate of the cropping start position
  • right (525): X-coordinate of the cropping end position (Not width)
  • lower (625): Y-coordinate of the cropping end position (Not height)

In other words, the size (width and height) of the cropped image is calculated as follows:

  • Width = right – left = 525 – 400 = 125px
  • Height = lower – upper = 625 – 500 = 125px

Please note that you specify the “coordinates of the bottom-right corner”, not the “width and height.”

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次