Python:用3D布尔索引3D数组并返回相同大小的3D数组。。。雅致

Python:用3D布尔索引3D数组并返回相同大小的3D数组。。。雅致,python,arrays,numpy,3d,Python,Arrays,Numpy,3d,我有一个3D图像扫描(形状:335x306x306,总元素:31368060),我想用相同大小的3D布尔掩码对其进行掩码,以返回相同大小的掩码图像 当我简单地用掩码索引数组时,如下所示: masked_image = image_pix[mask] 我得到了一个1D图像像素值数组,其中遮罩的顺序为=1,按标准行主(C样式)顺序排列(如图所示)。由于屏蔽,它只有6953600个元素 那么,如果没有索引,我如何将这个1D数组重塑为3D数组呢?我意识到我可以使用遮罩本身的索引来用遮罩值迭代地填充3D

我有一个3D图像扫描(形状:
335x306x306
,总元素:
31368060
),我想用相同大小的3D布尔掩码对其进行掩码,以返回相同大小的掩码图像

当我简单地用掩码索引数组时,如下所示:

masked_image = image_pix[mask]
我得到了一个1D图像像素值数组,其中遮罩的顺序为=1,按标准行主(C样式)顺序排列(如图所示)。由于屏蔽,它只有6953600个元素

那么,如果没有索引,我如何将这个1D数组重塑为3D数组呢?我意识到我可以使用遮罩本身的索引来用遮罩值迭代地填充3D数组,但我希望有一种更优雅(且计算效率更高)的解决方案,它不依赖于for循环。

使用:

使用
[mask]
的“普通”索引删除所有屏蔽值,这样就不会出现garantuee,从而可以再次将其重塑为3D(因为它丢失了项目),因此这是不可能的


但是,
MaskedArray
s保持其形状:

>>> import numpy as np

>>> arr = np.random.randint(0, 10, 16).reshape(4, 4)

>>> marr = np.ma.array(arr, mask=arr>6)

>>> marr.shape
(4, 4)

>>> marr
masked_array(data =
 [[3 -- 0 1]
 [4 -- 6 --]
 [2 -- 6 0]
 [4 5 0 0]],
             mask =
 [[False  True False False]
 [False  True False  True]
 [False  True False False]
 [False False False False]],
       fill_value = 999999)

我只是想了一会儿,然后意识到我可以通过逻辑索引来实现这一点

masked_image = image_pix # define the masked image as the full image
masked_image[mask==0] = 0 # define the pixels where mask == 0 as 0

这很容易…

如果您需要未修改的
图像,您应该复制:
蒙版图像=图像\u pix.copy()
masked_image = image_pix # define the masked image as the full image
masked_image[mask==0] = 0 # define the pixels where mask == 0 as 0