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

文章目录

    • 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)

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

实现效果展示

放在图像右上角
Python 实现图像局部区域放大并粘贴在图像右下角/右上角_第1张图片
放在右下角
Python 实现图像局部区域放大并粘贴在图像右下角/右上角_第2张图片

你可能感兴趣的:(python,数学建模,matlab)