简体   繁体   English

如何使用 Scikit-image 将透明 png 图像与另一个图像合并

[英]How to merge a transparent png image with another image using Scikit-image

This is basically the same question that was posted here: How to merge a transparent png image with another image using PIL but using with scikit-image instead of PIL.这基本上与此处发布的问题相同: 如何使用 PIL 将透明 png 图像与另一个图像合并,但使用 scikit-image 而不是 PIL。 I mean to paste the png keeping its transparency on top of a background image.我的意思是将 png 粘贴在背景图像的顶部,并保持其透明度。 Also, if there is actually a way of doing it, I would like to know which one is faster (PIL or scikit-image).另外,如果真的有办法做到这一点,我想知道哪个更快(PIL 或 scikit-image)。 Thanks.谢谢。

Read the two images and add using the formula img1*alpha + img2*(1-alpha)读取两个图像并使用公式img1*alpha + img2*(1-alpha)相加

import numpy as np
from matplotlib import pyplot as plt
import skimage.io

img1 = skimage.io.imread('Desert.jpg')
img2 = skimage.io.imread('Penguins.jpg')

img3 = np.ubyte(0.7*img1 + 0.3*img2)

plt.imshow(img3)

alpha 合并图像

Another option could be to use the alpha channel of two images as masks as below另一种选择是使用两个图像的 alpha 通道作为掩码,如下所示

import numpy as np
from matplotlib import pyplot as plt
import skimage.io

img1 = skimage.io.imread('img1.png')
img2 = skimage.io.imread('img2.png')

mask1 = img1.copy()
mask2 = img2.copy()

mask1[:,:,0] = mask1[:,:,3]
mask1[:,:,1] = mask1[:,:,3]
mask1[:,:,2] = mask1[:,:,3]

mask2[:,:,0] = mask2[:,:,3]
mask2[:,:,1] = mask2[:,:,3]
mask2[:,:,2] = mask2[:,:,3]

img3 = np.bitwise_or(np.bitwise_and(img1, mask1),np.bitwise_and(img2, mask2)) ;
plt.subplot(2,2,1)
plt.imshow(img1)
plt.subplot(2,2,2)
plt.imshow(img2)
plt.subplot(2,2,3)
plt.imshow(img3)

使用 alpha 蒙版

Inspired by user8190410's answer, I built my own function to do it:受到 user8190410 的回答的启发,我构建了自己的函数来做到这一点:

from skimage import data
import numpy as np

x, y = 100, 100
background = data.imread('background.jpg') / 255.
image = data.imread('image.png') / 255.

background_height, background_width, background_depth = background.shape
image_height, image_width, image_depth = image.shape

template = np.zeros((background_height, background_width, image_depth))
template[y : y + image_height, x : x + image_width, :] = image

mask = np.stack([template[:,:,3] for _ in range(3)], axis = 2)
inv_mask = 1. - mask
result = background[:,:,:3] * inv_mask + template[:,:,:3] * mask
plt.figure(figsize = (15, 15))
plt.subplot(1, 3, 2)
plt.imshow(image)
plt.subplot(1, 3, 1)
plt.imshow(background)
plt.subplot(1, 3, 3)
plt.imshow(result)
plt.tight_layout()
plt.show()

图像输出

Please let me know if I can do something to improve computation speed请让我知道我是否可以做些什么来提高计算速度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM