You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python合并带透明背景的底图与另一张图片

问题描述

需要将一张带透明背景的底图(图1)与另一张图片(图2)合并,把后者放入底图的空白区域,预期效果如图3所示。但尝试以下代码后未达到预期:

图1:底图
图2:待放入图片
图3:预期效果

尝试的代码
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

dim = (425, 425)

apple = mpimg.imread('image.png')
apple = cv2.resize(apple, dim)

banana = mpimg.imread('image2.png')
banana = cv2.resize(banana, dim)


_ = plt.imshow(apple)
_ = plt.show()

_ = plt.imshow(banana)
_ = plt.show()

list_images = [apple, banana]

def blend(list_images): # 均等混合图片

    equal_fraction = 1.0 / (len(list_images))

    output = np.zeros_like(list_images[0])

    for img in list_images:
        output = output + img * equal_fraction

    output = output.astype(np.uint8)
    _ = plt.imshow(output)
    return output


output = blend(list_images)

_ = plt.imshow(output)
解决思路与修正代码

当前代码是对两张图做均等像素混合,这和“将图2放入底图空白区”的需求不符。正确做法是利用底图的透明通道(Alpha通道)定位空白区域,再精准替换像素:

修正后的代码如下:

import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

dim = (425, 425)

# 读取带透明通道的底图并调整尺寸
base_img = mpimg.imread('image.png')
base_img = cv2.resize(base_img, dim)
# 分离RGB色彩通道和Alpha透明通道
base_rgb = base_img[..., :3]
alpha_channel = base_img[..., 3]

# 读取待放入图片并调整尺寸
insert_img = mpimg.imread('image2.png')
insert_img = cv2.resize(insert_img, dim)
# 若待放入图带Alpha通道,仅保留RGB部分
if insert_img.shape[-1] == 4:
    insert_img = insert_img[..., :3]

# 创建掩码:Alpha通道为0的区域就是需要替换的空白区
mask = alpha_channel == 0

# 将待放入图的像素替换到底图空白区域,保留底图原有内容
result = base_rgb.copy()
result[mask] = insert_img[mask]

# 显示最终效果
plt.imshow(result)
plt.show()

# 保存结果(可选)
mpimg.imsave('merged_result.png', result)
代码说明
  • 通过底图的Alpha通道精准定位空白区域,避免误替换底图的非透明部分;
  • 确保两张图尺寸一致,保证替换后画面对齐;
  • 仅在空白区域覆盖待放入图的像素,完全匹配预期效果。

内容的提问来源于stack exchange,提问作者Lucas Noleto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 13:03:24