2016-06-09 34 views
1

我有一个形状为(2560L, 1920L, 3L)的RGB图像img和形状为(2560L, 1920L)的另一个单通道图像mask。现在,我想制作形状为(2560L, 1920L, 3L)mask,即我想将此单个频道数据复制到所有三个频道中。在Numpy阵列中复制频道

我这样做如下。

np.array([[[j,j,j] for j in i] for i in mask]) 

有没有更快的方式使用numpy

回答

2

如果你绝对想拥有的掩码为(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) 

然而,一般来说,你可以直接使用这些broadcasts。举例来说,如果你想通过你的面具乘以你的形象:

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

所以你永远创建(n, m, 3)面膜:广播是通过操纵遮片阵列的进步上飞完成的,而不是创造一个更大的,多余的。大多数numpy的业务支持这种广播:二进制运算(如上),也indexing

>>> # 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 
+0

谢谢,帮助。第二个片段尤其如此。 :) –

3
np.repeat(mask.reshape(2560L, 1920L, 1L), 3, axis=2)