Home > Software design >  Numpy concatenate behaviour. How to concatenate example correctly
Numpy concatenate behaviour. How to concatenate example correctly

Time:11-08

I have following multi-dimensional array:

windows = array([[[[[[0., 0.],
           [1., 0.]],

          [[0., 0.],
           [1., 0.]],

          [[0., 0.],
           [1., 0.]]],


         [[[0., 1.],
           [0., 0.]],

          [[0., 1.],
           [0., 0.]],

          [[1., 0.],
           [0., 0.]]],


         [[[1., 0.],
           [0., 0.]],

          [[0., 1.],
           [0., 0.]],

          [[0., 1.],
           [0., 0.]]]]]])
print(windows.shape)
(1, 1, 3, 3, 2, 2) # (n, d, a, b, c, c) w = a * (c*c), h = b * (c*c)

I want to get next resulting array:

mask = array([[
        [[0., 0., 0., 0., 0., 0.],
         [1., 0., 1., 0., 1., 0.],
         [0., 1., 0., 1., 1., 0.],
         [0., 0., 0., 0., 0., 0.],
         [1., 0., 0., 1., 0., 1.],
         [0., 0., 0., 0., 0., 0.]] 
]], dtype=np.float32)
print(mask.shape)
(1, 1, 6, 6) # (n, d, w, h)

Basically, I want to squeeze last 4 dimensions into 2-d matrix so the final shape become (n, d, w, h), in this case (1, 1, 6, 6).

I tried np.concatenate(windows, axis = 2), but it didnt concatenate along 2nd dimension and reduced for some reason first(although I set axis = 2) 'n' dimension.

Additional information:
windows is a result of following code snippet

windows = np.lib.stride_tricks.sliding_window_view(arr, (c, c), axis (-2,-1), writeable = True) # arr.shape == mask.shape
windows = windows[:, :, ::c, ::c] # these are non-overlapping windows of arr with size (c,c)
windows = ... # some modifications of windows

Now I want to build from these windows array with shape of arr.shape, this array called mask in example above. Simple reshape doesn't work because it returns elements in wrong order.

CodePudding user response:

IIUC, you want to merge dimensions 2 4 and 3 5, an easy way would be to swapaxes 4 and 5 (or -3 and -2), and reshape to (1,1,6,6):

windows.swapaxes(-2,-3).reshape(1,1,6,6)

output:

array([[[[0., 0., 0., 0., 0., 0.],
         [1., 0., 1., 0., 1., 0.],
         [0., 1., 0., 1., 1., 0.],
         [0., 0., 0., 0., 0., 0.],
         [1., 0., 0., 1., 0., 1.],
         [0., 0., 0., 0., 0., 0.]]]])
  • Related