Numpy 2D空间蒙版将从2D阵列填充特定值以形成3D结构

时间:2020-11-30 21:21:17

I'm quite new to programming in general, but I could not figure this problem out until now.

我对一般的编程很新,但直到现在我都无法解决这个问题。

I've got a two-dimensional numpy array mask, lets say mask.shape is (3800,3500)which is filled with 0s and 1s representing a spatial resolution of a 2D image, where a 1 represents a visible pixel and 0 represents background.
I've got a second two-dimensional array data of data.shape is (909,x) where x is exactly the amount of 1s in the first array. I now want to replace each 1 in the first array with a vector of length 909 from the second array. Resulting in a final 3D array of shape(3800,3500,909) which is basically a 2D x by y image where select pixels have a spectrum of 909 values in z direction.

我有一个二维numpy数组掩码,让我们说mask.shape是(3800,3500),填充0和1表示2D图像的空间分辨率,其中1代表可见像素,0代表背景。我有data.shape的第二个二维数组数据是(909,x),其中x恰好是第一个数组中的1的数量。我现在想要用第二个数组中的长度为909的向量替换第一个数组中的每个1。产生最终的3D形状阵列(3800,3500,909),其基本上是2D x x y图像,其中选择的像素在z方向上具有909个值的光谱。

I tried

mask_vector = mask.flatten
ones = np.ones((909,1))
mask_909 = mask_vector.dot(ones) #results in a 13300000 by 909 2d array
count = 0
for i in mask_vector:
    if i == 1:
        mask_909[i,:] = data[:,count]
        count += 1

result = mask_909.reshape((3800,3500,909))

This results in a viable 3D array giving a 2D picture when doing plt.imshow(result.mean(axis=2)) But the values are still only 1s and 0s not the wanted spectral data in z direction. I also tried using np.where but broadcasting fails as the two 2D arrays have clearly different shapes.
Has anybody got a solution? I am sure that there must be an easy way...

这样可以生成一个可行的3D阵列,在进行plt.imshow(result.mean(axis = 2))时给出2D图像。但是这些值仍然只是1和0而不是z方向上所需的光谱数据。我也尝试过使用np.where但广播失败,因为两个2D阵列的形状明显不同。有人有解决方案吗?我相信必须有一个简单的方法......

1 个解决方案

#1


0  

Basically, you simply need to use np.where to locate the 1s in your mask array. Then initialize your result array to zero and replace the third dimension with your data using the outputs of np.where:

基本上,您只需要使用np.where来定位掩码数组中的1。然后将结果数组初始化为零,并使用np.where的输出将第三个维度替换为您的数据:

import numpy as np

m, n, k = 380, 350, 91
mask = np.round(np.random.rand(m, n))
x = np.sum(mask == 1)
data = np.random.rand(k, x)

result = np.zeros((m, n, k))
row, col = np.where(mask == 1)
result[row,col] = data.transpose()

#1


0  

Basically, you simply need to use np.where to locate the 1s in your mask array. Then initialize your result array to zero and replace the third dimension with your data using the outputs of np.where:

基本上,您只需要使用np.where来定位掩码数组中的1。然后将结果数组初始化为零,并使用np.where的输出将第三个维度替换为您的数据:

import numpy as np

m, n, k = 380, 350, 91
mask = np.round(np.random.rand(m, n))
x = np.sum(mask == 1)
data = np.random.rand(k, x)

result = np.zeros((m, n, k))
row, col = np.where(mask == 1)
result[row,col] = data.transpose()