杰瑞科技汇

Python图像裁剪怎么实现?

Of course! Cropping an image in Python is a common task, and there are several excellent libraries to do it. The most popular and user-friendly one is Pillow (a fork of PIL).

Python图像裁剪怎么实现?-图1
(图片来源网络,侵删)

I'll guide you through the process using Pillow, as it's the standard for image manipulation in Python. I'll also show you how to do it with OpenCV, which is another powerful library, especially for computer vision tasks.


Method 1: Using the Pillow Library (Recommended for most users)

Pillow is perfect for basic image manipulation tasks like cropping, resizing, and changing formats. It's very intuitive.

Step 1: Install Pillow

If you don't have it installed, open your terminal or command prompt and run:

pip install Pillow

Step 2: Understand the Crop Box

The crop() method in Pillow takes a 4-tuple (left, upper, right, lower) that defines the rectangle to be cropped.

Python图像裁剪怎么实现?-图2
(图片来源网络,侵删)

Important: The coordinates are based on the top-left corner of the image as (0, 0).

(0, 0) ------------------ (width, 0)
   |                      |
   |     CROP BOX         |
   |   (left, upper)      |
   |                      |
   |                      |
   |                      |
   |                      |
(0, height) ----------- (width, height)

Step 3: Write the Python Code

Let's create a simple script. For this example, let's assume you have an image named my_image.jpg in the same directory as your script.

from PIL import Image
try:
    # 1. Open the image file
    image = Image.open("my_image.jpg")
    # 2. Define the crop box (left, upper, right, lower)
    # Let's say we want to crop a 300x300 pixel square from the top-left corner.
    # The coordinates are (left, top, right, bottom).
    # Left=0, Top=0, Right=300, Bottom=300
    crop_box = (0, 0, 300, 300)
    # 3. Crop the image
    cropped_image = image.crop(crop_box)
    # 4. Display the original and cropped images (optional)
    # image.show()  # This will open the default image viewer
    # cropped_image.show()
    # 5. Save the cropped image
    cropped_image.save("cropped_image.jpg")
    print("Image cropped and saved successfully as 'cropped_image.jpg'")
except FileNotFoundError:
    print("Error: 'my_image.jpg' not found. Please make sure the image is in the correct directory.")
except Exception as e:
    print(f"An error occurred: {e}")

How to Crop from the Center?

A very common request is to crop a square from the center of the image. Here's how you can do it dynamically:

from PIL import Image
def crop_center(image, crop_width, crop_height):
    """
    Crops the center of an image.
    """
    img_width, img_height = image.size
    left = (img_width - crop_width) / 2
    top = (img_height - crop_height) / 2
    right = (img_width + crop_width) / 2
    bottom = (img_height + crop_height) / 2
    return image.crop((left, top, right, bottom))
# --- Example Usage ---
try:
    image = Image.open("my_image.jpg")
    # Let's crop a 400x400 square from the center
    # You can also make it responsive, e.g., crop to the smaller dimension
    size = min(image.size)
    center_cropped = crop_center(image, size, size)
    center_cropped.save("center_cropped_image.jpg")
    print("Center-cropped image saved as 'center_cropped_image.jpg'")
except FileNotFoundError:
    print("Error: 'my_image.jpg' not found.")

Method 2: Using the OpenCV Library

OpenCV is a powerful, open-source computer vision library. It's more complex than Pillow but offers more advanced features. It's a good choice if you're already working on a computer vision project.

Python图像裁剪怎么实现?-图3
(图片来源网络,侵删)

Step 1: Install OpenCV

pip install opencv-python

Step 2: Understand the Crop Slicing

In OpenCV, images are represented as NumPy arrays. Cropping is done using array slicing. The syntax is image[y:y+h, x:x+w], where:

  • (x, y) is the top-left corner of the crop box.
  • w is the width of the crop box.
  • h is the height of the crop box.

Step 3: Write the Python Code

import cv2
try:
    # 1. Read the image file
    # cv2 reads images in BGR format by default
    image = cv2.imread("my_image.jpg")
    if image is None:
        raise FileNotFoundError("Could not read the image. Check the file path.")
    # 2. Get image dimensions
    height, width, channels = image.shape
    # 3. Define the crop box using slicing
    # Syntax: image[y_start:y_end, x_start:x_end]
    # Let's crop a 300x300 square from the top-left corner.
    # y_start=0, y_end=300, x_start=0, x_end=300
    cropped_image = image[0:300, 0:300]
    # 4. Save the cropped image
    # cv2 saves images in BGR format. If you want to view it,
    # you might need to convert it to RGB.
    cv2.imwrite("cropped_image_cv2.jpg", cropped_image)
    print("Image cropped and saved successfully as 'cropped_image_cv2.jpg'")
except FileNotFoundError as e:
    print(e)
except Exception as e:
    print(f"An error occurred: {e}")

How to Crop from the Center with OpenCV?

Here is the dynamic center crop function for OpenCV:

import cv2
import numpy as np
def crop_center_opencv(image, crop_width, crop_height):
    """
    Crops the center of an image using OpenCV.
    """
    img_height, img_width = image.shape[:2]
    # Calculate the starting coordinates
    start_x = (img_width - crop_width) // 2
    start_y = (img_height - crop_height) // 2
    # Calculate the ending coordinates
    end_x = start_x + crop_width
    end_y = start_y + crop_height
    # Crop the image
    return image[start_y:end_y, start_x:end_x]
# --- Example Usage ---
try:
    image = cv2.imread("my_image.jpg")
    if image is None:
        raise FileNotFoundError("Could not read the image.")
    # Crop a square from the center based on the smaller dimension
    size = min(image.shape[0], image.shape[1])
    center_cropped = crop_center_opencv(image, size, size)
    cv2.imwrite("center_cropped_image_cv2.jpg", center_cropped)
    print("Center-cropped image saved as 'center_cropped_image_cv2.jpg'")
except FileNotFoundError as e:
    print(e)

Summary: Which One Should You Use?

Feature Pillow OpenCV
Ease of Use Excellent. Very intuitive, high-level API. Good. More complex, lower-level API.
Installation pip install Pillow pip install opencv-python
Crop Method image.crop((left, top, right, bottom)) image[y:y+h, x:x+w] (NumPy slicing)
Primary Use Case General image manipulation, web apps, simple scripts. Computer vision, video processing, machine learning.
Image Format Maintains original format (e.g., PNG, JPEG). Reads/writes as NumPy arrays (BGR by default).

Recommendation:

  • For simple cropping tasks, resizing, or any general image manipulation, use Pillow. It's simpler, more readable, and gets the job done perfectly.
  • If you are already working on a project involving OpenCV (e.g., face detection, object tracking), then stick with OpenCV for consistency. If you need to integrate cropping into a complex vision pipeline, OpenCV is the way to go.
分享:
扫描分享到社交APP
上一篇
下一篇