将Numpy阵列中的一个通道广播为三个通道

Abd*_*tir 8 python arrays numpy

我有一个RGB图像img,其是形状(2560L, 1920L, 3L)和另一单信道的图像mask,其是形状(2560L, 1920L).现在,我想制作这种mask形状,(2560L, 1920L, 3L)即我想将这个单通道数据复制到所有三个通道中.

我这样做如下.

np.array([[[j,j,j] for j in i] for i in mask])
Run Code Online (Sandbox Code Playgroud)

有没有更快的方法来使用numpy

Val*_*éry 10

np.repeat(mask.reshape(2560L, 1920L, 1L), 3, axis=2)
Run Code Online (Sandbox Code Playgroud)

  • 更简单:`np.repeat(mask[..., np.newaxis], 3, axis=2)`。 (5认同)

val*_*val 7

如果您绝对希望蒙版为(2560, 1920, 3),则可以简单地沿轴将其扩展(有多种方法可以做到,但是这很简单):

>>> mask = np.random.random_integers(0, 255, (15, 12))
>>> mask_3d = mask[:, :, None] * np.ones(3, dtype=int)[None, None, :]
>>> mask.shape
(15L, 12L)
>>> mask_3d.shape
(15L, 12L, 3L)
Run Code Online (Sandbox Code Playgroud)

但是,通常,您可以直接使用这些广播。例如,如果您想将图像乘以蒙版:

>>> img = np.random.random_integers(0, 255, (15, 12, 3))
>>> img.shape
(15L, 12L, 3L)
>>> converted = img * mask[:, :, None]
>>> converted.shape
(15L, 12L, 3L)
Run Code Online (Sandbox Code Playgroud)

所以,你永远不会创建(n, m, 3)面膜:广播是通过操纵遮片阵列的进步,而不是创建一个更大的,冗余的一个上飞完成。大多数numpy操作都支持这种广播:二进制操作(如上所述),但也可以建立索引

>>> # Take the lower part of the image
>>> mask = np.tri(15, 12, dtype=bool)
>>> # Apply mask to first channel
>>> one_channel = img[:, :, 0][mask]
>>> one_channel.shape
(114L,)
>>> # Apply mask to all channels
>>> pixels = img[mask]
>>> pixels.shape
(114L, 3L)
>>> np.all(pixels[:, 0] == one_channel)
True
Run Code Online (Sandbox Code Playgroud)


Abd*_*tir 7

尺寸可以沿最后一个轴展开,然后按如下方式平铺。

mask = np.random.randn(200, 150)
mask3d = np.tile(mask[:, :, None], [1, 1, 3])
Run Code Online (Sandbox Code Playgroud)

[1, 1, 3]在最后一个维度中将蒙版平铺 3 次。