Python 实现图像局部区域放大并粘贴在图像右下角/右上角

Python源代码

from PIL import Image, ImageDraw


def enlarge_and_highlight_region(image_path, x, y, width, height, scale_factor, mode='right_down'):
    # 打开原始图像
    original_image = Image.open(image_path)

    # 放大指定区域
    enlarged_region = original_image.crop((x, y, x + width, y + height))
    enlarged_width = width * scale_factor
    enlarged_height = height * scale_factor
    enlarged_region = enlarged_region.resize((int(enlarged_width), int(enlarged_height)))

    # 在原图的右下角绘制放大的区域
    output_image = original_image.copy()
    if mode == 'right_up':
        paste_xy = (original_image.width - int(enlarged_width), 0)
    else:
        paste_xy = (original_image.width - int(enlarged_width), original_image.height - int(enlarged_height))
    output_image.paste(enlarged_region, paste_xy)

    # 绘制原始图像的矩形框
    border_width = 3
    draw = ImageDraw.Draw(output_image)
    draw.rectangle((x, y, x + width, y + height), outline='green', width=border_width)

    # 绘制放大区域的矩形框
    draw = ImageDraw.Draw(output_image)
    if mode == 'right_up':
        right_y = enlarged_height
    else:
        right_y = output_image.height
    draw.rectangle((paste_xy[0], paste_xy[1],
                    output_image.width, right_y), outline='green', width=border_width)

    # 显示输出图像
    output_image.save('test.png')
    output_image.show()


if __name__ == '__main__':
    image_path = 'origin.jpg'
    x = 100  # 矩形区域的左上角 x 坐标
    y = 200  # 矩形区域的左上角 y 坐标
    width = 80  # 矩形区域的宽度
    height = 80  # 矩形区域的高度
    scale_factor = 3  # 放大倍数
    # right_up 表示放大区域放置在右上角, right_down 表示放大区域放置在右下角
    mode = 'right_up'

    enlarge_and_highlight_region(image_path, x, y, width, height, scale_factor, mode)

通过更改图像路径与相关参数设置,调用函数,即可实现

实现效果展示

放在图像右上角
在这里插入图片描述
放在右下角
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值