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.")

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

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

相关推荐
极小狐23 分钟前
极狐GitLab 项目功能和权限解读
运维·git·安全·gitlab·极狐gitlab
国科安芯2 小时前
面向高性能运动控制的MCU:架构创新、算法优化与应用分析
单片机·嵌入式硬件·安全·架构·机器人·汽车·risc-v
SLY司赖3 小时前
大模型应用开发之LLM入门
语言模型·chatgpt·llm
迷路的小绅士4 小时前
常见网络安全攻击类型深度剖析(四):跨站脚本攻击(XSS)——分类、漏洞利用与前端安全防护
前端·安全·web安全
自由鬼4 小时前
开源漏洞扫描器:OpenVAS
运维·服务器·安全·网络安全·开源·漏洞管理
Python_金钱豹4 小时前
Text2SQL零代码实战!RAGFlow 实现自然语言转 SQL 的终极指南
前端·数据库·sql·安全·ui·langchain·机器人
广东航连科技5 小时前
银行网点款箱交接权限认证开锁与密钥时效双重监控
物联网·安全·银行·精细化管理·锁控·智能锁·款箱
迷路的小绅士5 小时前
网络安全概述:定义、重要性与发展历程
网络·安全·web安全
胡八一8 小时前
如何在 Dialog 中安全初始化 ECharts 并自动监听容器大小变化
前端·安全·echarts
virelin_Y.lin10 小时前
系统与网络安全------弹性交换网络(2)
网络·安全·web安全·链路聚合·lacp·eth-trunk