0

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()
Liwellyen
  • 433
  • 1
  • 6
  • 19

3 Answers3

2

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.

TYZ
  • 8,466
  • 5
  • 29
  • 60
0

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)

tevemadar
  • 12,389
  • 3
  • 21
  • 49
0

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 e.g. (539, 779, 5), just do mask = np.dstack((mask, mask, mask, mask, mask))

Steven
  • 99
  • 5