【问题标题】:How to merge a transparent png image with another image using Scikit-image如何使用 Scikit-image 将透明 png 图像与另一个图像合并
【发布时间】:2021-02-04 06:00:18
【问题描述】:

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

【问题讨论】:

  • 为什么不用opencv,它更快
  • @ManojNirale 是吗?多少数量级?

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


【解决方案1】:

读取两张图片并使用公式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 通道作为掩码,如下所示

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)

【讨论】:

  • 问题是关于将 "transparent PNG" 与另一个图像合并,但您的答案使用了 2 个不支持透明度的 JPEG...
【解决方案2】:

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

如果我能做些什么来提高计算速度,请告诉我

【讨论】:

  • 请提供您要叠加的典型前景图像 - 以便我查看它是否具有二进制或连续透明度。
猜你喜欢
  • 2023-03-17
  • 2010-11-26
  • 2012-03-06
  • 2011-06-02
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多