gpt4 book ai didi

python - 使用 Python 重叠 2 个 RGBA 图像

转载 作者:行者123 更新时间:2023-12-02 16:16:30 25 4
gpt4 key购买 nike

我正在做一个图像分割项目。

我有 2 个 RGBA 图像。
第一个图像是要分割的图像:

enter image description here

第二个是包含具有不同透明度值的红色方 block 的图像:

enter image description here

我想叠加两张图片,但我做不到。我尝试了两种方法:

一种使用openCV“添加”方法,另一种使用PIL“混合”方法。

from PIL import Image as PImage

if __name__ == '__main__':

image_A = read_image(r"C:\Users\francois.bock\Desktop\013.jpg", rgb=True)

# Add alpha channel
image_A = np.concatenate((image_A, np.full((256, 256, 1), fill_value=255, dtype=np.uint8)), axis=2)

#Create image B
image_B = np.full((256, 256, 4), fill_value=[0, 0, 0, 0], dtype=np.uint8)
for i in range(0, 20):
for j in range(0, 20):
image_B[i, j] = [255, 0, 0, 100]

for i in range(50, 70):
for j in range(50, 70):
image_B[i, j] = [255, 0, 0, 127]

for i in range(50, 70):
for j in range(0, 20):
image_B[i, j] = [255, 0, 0, 255]

image_A_convert = PImage.fromarray(image_A)
image_B_convert = PImage.fromarray(image_B)

# Test with blend
img_add = PImage.blend(image_A_convert, image_B_convert, 0.0)
img_add.save("testrgba.png", "PNG")

# Test with open CV
img_add = cv2.add(image_A,image_B)
img_add = PImage.fromarray(img_add)
img_add.save("testrgba.png", "PNG")

混合的结果:

enter image description here

简历打开的结果

enter image description here

正如我们所看到的,它效果不佳。

使用混合方法,第一张图像变得太淡了。
使用 openCV 方法,第一张图像还可以,但我们失去了第二张图像每个正方形的透明度。

我想保留相同的第一张图像,但透明度特定于第二张图像的每个正方形。

任何提示或提示?

最佳答案

我想你想要一个简单的 paste()带面具:

#!/usr/bin/env python3

from PIL import Image

# Open input images, background and overlay
image = Image.open('bg.png')
overlay = Image.open('overlay.png')

# Paste overlay onto background using overlay alpha as mask
image.paste(overlay, mask=overlay)

# Save
image.save('result.png')

enter image description here

关于python - 使用 Python 重叠 2 个 RGBA 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61057032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com