Python批次裁剪圖片

ZeroZeroSeven發表於2024-03-27

​ 前兩天想要把連續的不同幀的靜態圖片拼成一個GIF圖片,但是原來的圖片需要裁剪,而且存在很多張,幸好這麼多張的圖片裁剪的位置是一樣的,於是我便嘗試用Python優雅地批次裁剪這些圖片。

​ 首先介紹一下Python裁剪照片的原理。程式碼的輸入是圖片的地址和兩個點的座標,這兩個點的座標分別表示一個矩形的左上角頂點和右下角頂點,這個矩形就是你的裁剪區域。

​ 寫程式碼前,先引入一下所需要的庫。

from PIL import Image, ImageDraw, ImageFont

​ 那麼你一定會有個疑問,怎麼確定圖片矩形區域的頂點位置呢?下面貼出一個在原影像上繪製邊界框的程式碼。

def draw_bbox(image_path, bbox, output_path):
    """
    Draw bounding box on the image.

    Parameters:
        image_path (str): Path to the input image file.
        bbox (tuple): Bounding box coordinates (left, upper, right, lower).
        output_path (str): Path to save the image with bounding box.

    Returns:
        None
    """
    # Open image
    img = Image.open(image_path)

    # Draw bounding box
    draw = ImageDraw.Draw(img)
    draw.rectangle(bbox, outline="red", width=3)

    # Add text with coordinates
    font = ImageFont.truetype("arial.ttf", 20)
    draw.text((bbox[0], bbox[1]), f"{bbox}", fill="red", font=font)

    # Save image with bounding box
    img.save(output_path)

input_image_path = r"F:\Desktop\woman.jpg"
output_image_path = r"F:\Desktop\woman.jpg"
crop_box = (700, 550, 1850, 1000)  # Define crop box (left, upper, right, lower)
draw_bbox(input_image_path, crop_box, output_image_path)

​ crop_box(x1, y1, x2, y2),其中左上角頂點表示為(x1, y1),右下角頂點表示為(x2, y2)。但是你只能透過不斷摸索crop_box的取值,根據原影像上繪製的邊界框,逐漸確定你最後的裁剪區域。下面給出執行draw_bbox程式碼的視覺化例子。

​ 用draw_bbox拿到合適的crop_box以後,下面給出裁剪圖片的程式碼。

def crop_image(input_image_path, output_image_path, crop_box):
    """
    Crop an image using the specified crop box.

    Parameters:
        input_image_path (str): Path to the input image file.
        output_image_path (str): Path to save the cropped image.
        crop_box (tuple): Crop box coordinates (left, upper, right, lower).

    Returns:
        None
    """
    # Open image
    img = Image.open(input_image_path)

    # Crop image
    cropped_img = img.crop(crop_box)

    # Save cropped image
    cropped_img.save(output_image_path)

    print("Image cropped and saved successfully.")

​ 最後給出裁剪以後的視覺化例子。

​ 如果想要批次裁剪圖片的話,就在外面套一個迴圈就可以了。

相關文章