简体   繁体   中英

Python: Create a 3d mask from 2d masks

I want to create a 3d mask from a 2d mask. Lets assume I have a 2d mask like:

mask2d = np.array([[ True,  True ,False],
 [ True , True, False],
 [ True , True ,False]])
mask3d = np.zeros((3,3,3),dtype=bool)

The desired output should look like:

mask3d = [[[ True  True False]
  [ True  True False]
  [ True  True False]]

 [[ True  True False]
  [ True  True False]
  [ True  True False]]

 [[ True  True False]
  [ True  True False]
  [ True  True False]]]

Now I want to create a 3d array mask with the 2d array mask in every z slice. It should work no matter how big the 3d array is in z direction How would i do this?

EDIT

Ok now I try to find out, which method is faster. I know I could to it with timepit, but I do not realyunderstand why in the first method he loops 10000 times and in the second 1000 times:

mask3d=np.zeros((3,3,3),dtype=bool)
def makemask(): 
    b = np.zeros(mask3d,dtype=bool)
    b[:]=mask2d

%timeit for x in range(100): np.repeat(mask[np.newaxis,:], 4, 0)
%timeit for x in range(100): makemask()

You can use np.repeat :

np.repeat([mask2d],3, axis=0)

Notice the [] around mask2d which makes mask2d 3D, otherwise the result will be still a 2D array.

You can do such multiplication with vanilla Python already:

>>> a=[[1,2,3],[4,5,6]]
>>> [a]*2
[[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]]

Or, if the question is about concatenating multiple masks (probably this was the question for real):

>>> b=[[10,11,12],[13,14,15]]
>>> [a,b]
[[[1,2,3],[4,5,6]],[[10,11,12],[13,14,15]]

(This works with bools too, just it is easier to follow with numbers)

Numpy dstack works well for this, d stands for depth, meaning arrays are stacked in the depth dimension (the 3rd): assuming you have a 2D mask of size (539, 779) and want a third dimension

print(mask.shape)  # result: (539, 779)
mask = np.dstack((mask, mask, mask))
print(mask.shape)  # result: (539, 779, 3)

If for any reason you want eg (539, 779, 5), just do mask = np.dstack((mask, mask, mask, mask, mask))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM