如果您绝对希望掩码为(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