numpy将数组元素与另一个数组相乘

时间:2015-04-17 19:58:45

标签: python arrays numpy

我正在尝试编码多光谱图像。

每个像素的值都以33个通道编码。

我有两个numpy数组imagespectral_range

例如,一张图片有4 x 4像素:

image = np.array([[[1,2,4,3],[2,2,2,1],[1,2,3,2],[5,4,3,2]])

并且每个像素应该与图像所覆盖的光谱范围的33个值相关联:

spectral_range = np.array([0,0,0,0,0,0,0,1,23,99,166,86,54,12,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])

如何创建形状(width, height, 33)的np.array,其中每个像素的33个值是数组spectrum的33个值乘以数组image的各个值?

预期结果如下:

result = np.array([[[0,0,0,0,0,0,0,1,23,99,166,86,54,12,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,2,46,198,...etc.]]])

感谢您的帮助

1 个答案:

答案 0 :(得分:5)

您只需要向image添加一个额外的轴,然后将此数组与spectral_range相乘。额外的轴使得两个阵列可以相互播放:

>>> result = image[:, :, np.newaxis] * spectral_range
>>> result.shape
(4, 4, 33)
>>> result
array([[[  0,   0,   0,   0,   0,   0,   0,   1,  23,  99, 166,  86,  54,
          12,   1,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
           0,   0,   0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0,   0,   0,   2,  46, 198, 332, 172, 108,
          24,   2,   2,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
           0,   0,   0,   0,   0,   0,   0],
        ...