Skip to main content
 首页 » 编程设计

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

2025年05月04日72傻小

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

每个像素的值都在 33 个 channel 中编码。

我有两个 numpy 数组 image 和 spectral_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.]]]) 

感谢帮助

请您参考如下方法:

您只需向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], 
        ...