Как поместить обрезанное изображение в папку исходного изображения с помощью Python

Чтобы поместить обрезанное изображение в папку с именем исходного изображения с помощью Python, вы можете использовать различные методы. Вот несколько подходов:

Способ 1: использование модуля os

import os
from PIL import Image
def put_cropped_image(image_path, crop_box):
    # Load the original image
    original_image = Image.open(image_path)

    # Perform cropping
    cropped_image = original_image.crop(crop_box)

    # Extract the folder path and image name
    folder_path, image_name = os.path.split(image_path)

    # Create a new folder with the image name if it doesn't exist
    folder_name = os.path.splitext(image_name)[0]
    folder_path = os.path.join(folder_path, folder_name)
    os.makedirs(folder_path, exist_ok=True)

    # Save the cropped image in the folder
    cropped_image.save(os.path.join(folder_path, image_name))
# Example usage
image_path = "path/to/original_image.jpg"
crop_box = (x1, y1, x2, y2)  # Specify the crop box coordinates
put_cropped_image(image_path, crop_box)

Метод 2. Использование модуля Shutil

import os
import shutil
from PIL import Image
def put_cropped_image(image_path, crop_box):
    # Load the original image
    original_image = Image.open(image_path)

    # Perform cropping
    cropped_image = original_image.crop(crop_box)

    # Extract the folder path and image name
    folder_path, image_name = os.path.split(image_path)

    # Create a new folder with the image name if it doesn't exist
    folder_name = os.path.splitext(image_name)[0]
    folder_path = os.path.join(folder_path, folder_name)
    os.makedirs(folder_path, exist_ok=True)

    # Save the cropped image in the folder
    cropped_image_path = os.path.join(folder_path, image_name)
    cropped_image.save(cropped_image_path)

    # Move the original image to the folder
    shutil.move(image_path, cropped_image_path)
# Example usage
image_path = "path/to/original_image.jpg"
crop_box = (x1, y1, x2, y2)  # Specify the crop box coordinates
put_cropped_image(image_path, crop_box)