从图像中截取目标

这篇文章详细讲解了如何使用Python的PIL库对图片进行区域裁剪,并保存处理后的图片。通过实例展示了如何调用crop_and_save_image函数进行操作。
摘要由CSDN通过智能技术生成
from PIL import Image

def crop_and_save_image(input_path, output_path, left_top, right_bottom):
    """
    从输入图像中截取目标区域,并保存为新的图像。
    参数:
    - input_path: 输入图像路径
    - output_path: 输出图像保存路径
    - left_top: 左上角点坐标 (x, y)
    - right_bottom: 右下角点坐标 (x, y)
    """
    try:
        # 打开JPEG文件
        with Image.open(input_path) as img:
            # 使用crop函数截取目标区域
            cropped_img = img.crop((left_top[0], left_top[1], right_bottom[0], right_bottom[1]))

            # 保存截取的图像
            cropped_img.save(output_path)
            print(f"截取的图像已保存到 {output_path}")

    except Exception as e:
        print(f"截取图像时发生错误: {str(e)}")

# 替换 'input_image.jpg' 和 'output_cropped_image.jpg' 为你的实际文件名
# 并设置左上和右下点坐标 (left, top, right, bottom)
crop_and_save_image('1.jpg', '11.jpg', (0, 200), (100, 300))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值