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

时间:2018-12-26 11:28:13

标签: python image-processing python-imaging-library scikit-image

这基本上是与此处发布的问题相同的问题:How to merge a transparent png image with another image using PIL,但与scikit-image而不是PIL一起使用。我的意思是将png粘贴在背景图片上,以保持其透明度。另外,如果实际上有一种方法可以实现,我想知道哪种方法更快(PIL或scikit-image)。谢谢。

2 个答案:

答案 0 :(得分:2)

读取两个图像并使用公式img1*alpha + img2*(1-alpha)

添加
import numpy as np
from matplotlib import pyplot as plt
from skimage import data

img1 = data.imread('Desert.jpg')
img2 = data.imread('Penguins.jpg')

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

plt.imshow(img3)

alpha merged image

另一种选择是如下使用两个图像的Alpha通道作为蒙版

import numpy as np
from matplotlib import pyplot as plt
from skimage import data

img1 = data.imread('img1.png')
img2 = data.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)

using alpha masks

答案 1 :(得分:1)

受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()

Image output

请让我知道我是否可以做一些事情来提高计算速度