Python替换图片的指定区域

Python替换图片的指定区域
要在Python中替换图片的指定区域,可以使用Pillow库。以下是一个简单的例子,展示如何替换图片的一个区域:

from PIL import Image

def replace_image_region(src_path, dest_path, region, replacement_image):
# 加载原始图片和替换区域的图片
image = Image.open(src_path)
replacement = Image.open(replacement_image).convert(image.mode)

# 获取替换区域的大小
region_width, region_height = region[2] - region[0], region[3] - region[1]

# 调整替换图片的大小以匹配替换区域
replacement = replacement.resize((region_width, region_height))

# 通过掩码获取替换区域
mask = Image.new("L", (region_width, region_height), 255)
region_image = image.crop(region)

# 应用掩码和替换图片
region_image.paste(replacement, (0, 0), mask)

# 粘贴图片区域回原图
image.paste(region_image, region)

# 保存新图片
image.save(dest_path)

使用示例

src_img_path = ‘source.jpg’ # 原始图片路径
dest_img_path = ‘destination.jpg’ # 替换后保存的图片路径
replacement_img_path = ‘replacement.png’ # 替换区域的图片路径
region = (100, 100, 300, 300) # 替换的区域坐标 (左, 上, 右, 下)

replace_image_region(src_img_path, dest_img_path, region, replacement_img_path)

  • 24
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值