Python批量裁剪图片

前两天想要把连续的不同帧的静态图片拼成一个GIF图片,但是原来的图片需要裁剪,而且存在很多张,幸好这么多张的图片裁剪的位置是一样的,于是我便尝试用Python优雅地批量裁剪这些图片。

​ 首先介绍一下Python裁剪照片的原理。代码的输入是图片的地址和两个点的坐标,这两个点的坐标分别表示一个矩形的左上角顶点和右下角顶点,这个矩形就是你的裁剪区域。

​ 写代码前,先引入一下所需要的库。

python 复制代码
from PIL import Image, ImageDraw, ImageFont

​ 那么你一定会有个疑问,怎么确定图片矩形区域的顶点位置呢?下面贴出一个在原图像上绘制边界框的代码。

python 复制代码
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以后,下面给出裁剪图片的代码。

python 复制代码
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.")

​ 最后给出裁剪以后的可视化例子。

​ 如果想要批量裁剪图片的话,就在外面套一个循环就可以了。

相关推荐
数据知道36 分钟前
容器安全入门:Docker 逃逸原理与 5 个经典 CVE
安全·网络安全·docker·容器
JonLee20201 小时前
适配 Yii 3.0,php-casbin/yii-permission 3.0 正式发布
安全·php·rbac·yii·权限·casbin
极连AI3 小时前
极连AI平台解读、Codex5.6仅需0.01倍率,无需Token焦虑,极速响应
人工智能·gpt·chatgpt·aigc·ai编程·ai写作·gpu算力
MartinYeung53 小时前
[论文学习]PACT:溯源感知能力合约——面向智能体安全的参数级溯源
人工智能·学习·安全
栋***t3 小时前
2026年不止防作弊,麦塔在线培训系统培训与考试安全的体系化设计
网络·安全
Vince的修炼之路3 小时前
防 Prompt 注入安全技术深度分析
人工智能·安全
孪生质数-5 小时前
AI Agent 工程实践(一):大模型 API 接入示范
网络·人工智能·ai·chatgpt·github·claude·claudecode
MartinYeung56 小时前
[论文学习]AgentSafetyBench:大语言模型智能体安全评估基准深度分析
学习·安全·语言模型
tiger从容淡定是人生7 小时前
生态入口之战:GPT、Gemini、Copilot与DeepSeek的战略分野
图像处理·人工智能·chatgpt·copilot·软件构建
跨境生态圈8 小时前
2026跨境出海服务商深度测评:凌赟科技如何用“SEO+GEO双引擎”重构AI时代获客逻辑?
大数据·运维·人工智能·科技·chatgpt