This question already has answers here:
With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image?

(3个答案)


已关闭6年。




我有两个形状为numpy的数组(256、256、4)。我想将第四个256 x 256平面视为alpha级别,并导出已覆盖这些数组的图像。

代码示例:
import numpy as np
from skimage import io

fg = np.ndarray((256, 256, 4), dtype=np.uint8)
one_plane = np.random.standard_normal((256, 256)) * 100 + 128
fg[:,:,0:3] = np.tile(one_plane, 3).reshape((256, 256, 3), order='F')
fg[:, :, 3] = np.zeros((256, 256), dtype=np.uint8)
fg[0:128, 0:128, 3] = np.ones((128, 128), dtype=np.uint8) * 255
fg[128:256, 128:256, 3] = np.ones((128, 128), dtype=np.uint8) * 128

bg = np.ndarray((256, 256, 4), dtype=np.uint8)
bg[:,:,0:3] = np.random.standard_normal((256, 256, 3)) * 100 + 128
bg[:, :, 3] = np.ones((256, 256), dtype=np.uint8) * 255

io.imsave('test_fg.png', fg)
io.imsave('test_bg.png', bg)

这将创建两个图像,fg:

和bg:

:

我希望能够将fg覆盖到bg上。也就是说,最终图像的左上角应该是灰色的(因为fg的alpha为1),右下角是灰色和彩色杂色的混合,其他象限中是纯彩色的杂色。我正在寻找类似add函数的东西,该函数给了我一个新的np数组。

请注意,我认为这与this answer不同,后者使用matplotlib.pyplot.plt来覆盖图像和彩色 map 上的 fiddle 。我认为我不需要在这里摆弄色彩图,但也许答案是我愿意。

我想要该操作返回的新np.array的原因是,我想对许多图像进行迭代处理,这些图像按顺序覆盖。

最佳答案

Alpha blending通常使用Porter&Duff方程式完成:

其中src和dst对应于您的前景和背景图像,并且A和RGB像素值假定为浮点,范围为[0,1]。

对于您的特定示例:

src_rgb = fg[..., :3].astype(np.float32) / 255.0
src_a = fg[..., 3].astype(np.float32) / 255.0
dst_rgb = bg[..., :3].astype(np.float32) / 255.0
dst_a = bg[..., 3].astype(np.float32) / 255.0

out_a = src_a + dst_a*(1.0-src_a)
out_rgb = (src_rgb*src_a[..., None]
           + dst_rgb*dst_a[..., None]*(1.0-src_a[..., None])) / out_a[..., None]

out = np.zeros_like(bg)
out[..., :3] = out_rgb * 255
out[..., 3] = out_a * 255

输出:

关于python - 覆盖两个numpy数组,将第四个平面视为alpha级,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25182421/

10-14 13:30
查看更多