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

标签 python opencv python-imaging-library

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

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

enter image description here

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

enter image description here

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

一个使用 openCV“add”方法,另一个使用 PIL“blend”方法。

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 方法,第一张图像没问题,但我们失去了第二张图像每个方 block 的透明度。

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

有什么提示或提示吗?

最佳答案

我认为你想要一个简单的带有掩码的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/

相关文章:

python - 更改 PIL 图像的 alpha 时出错

python - RabbitMQ - Python/Pika 如何知道队列是否为空?

python - 使车牌图像变形为正面平行

python - 使用 Redis 与 memcached+db 作为 Django 的 session 系统的优缺点?

python - 如何在不增加OpenCV大小的情况下将视频分解为帧

OpenCV Haar 分类器 - 它是 SVM

python - 如何提取彩色边框内的图像区域?

python - 值错误 : images do not match when blending pictures in PIL

用于 GAE 的 Java 与 Python

python - 将一张图像与 Cloudinary 存储进行比较