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

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

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

相关推荐
啥都不懂的小小白31 分钟前
密码学入门:从古典加密到现代网络安全
安全·web安全·密码学
ml魔力信息2 小时前
活体检测与防伪技术的安全与隐私分析
大数据·人工智能·安全·隐私保护·生物识别·活体检测
hhhhhlt3 小时前
【代码大模型-后门安全】Backdoors in Neural Models of Source Code
人工智能·安全
乾博电子3 小时前
配电安全“隐形哨兵”上线!RCMX-ONE剩余电流监视器,守护每一度电的安心
安全·故障定位·在线绝缘监测仪·绝缘监测仪
智驱力人工智能3 小时前
工厂抽烟检测系统 智能化安全管控新方案 加油站吸烟检测技术 吸烟行为智能监测
人工智能·算法·安全·边缘计算·抽烟检测算法·工厂抽烟检测系统·吸烟监测
爱笑的眼睛114 小时前
HarmonyOS SaveButton深度解析:安全便捷的媒体资源保存方案
安全·华为·harmonyos·媒体
lypzcgf11 小时前
Coze源码分析-资源库-编辑数据库-后端源码-安全与错误处理
数据库·安全·系统架构·coze·coze源码分析·ai应用平台·agent平台
Ytadpole11 小时前
客户端加密 和 服务端加密:端到端安全的真正含义
安全·加解密
huohaiyu11 小时前
synchronized (Java)
java·开发语言·安全·synchronized
无锡布里渊13 小时前
分布式光纤声波振动传感:守护智慧城市燃气管网安全的 “神经末梢”
人工智能·安全·智慧城市