Home > Enterprise >  Split 4x4x3 matrix into 4 individual 2x2x3 matrixes
Split 4x4x3 matrix into 4 individual 2x2x3 matrixes

Time:02-28

I want to split a 3d matrix into smaller matrixes of equal size. In this case a 4x4x3 matrix into 4 individual matrices of 2x2x3. I am trying this:

import numpy as np
from skimage.util.shape import view_as_windows

#create 4x4
data = np.array([[1,2,3,4], 
                  [5,6,7,8], 
                  [9,10,11,12], 
                  [13,14,15,16]])

#make 3 dimensional
stacked = np.dstack([data, data, data])

#split it
windows = view_as_windows(stacked, (2,2,3))

but windows.shape returns (3, 3, 1, 2, 2, 3) when I am expecting something more like (4, 2, 2, 3), or even a list of matrices which has length 4 and is (2,2,3) I don't need to use skimage to do this, numpy are else is fine.

If this were a 2d problem with data and input (4,4) I would expect the output to be 4 matrixes:

[[1,2,
  5,6]]

[[3,4,
  7,8]]

[[9,10,
  13,14]]

[[11,12,
  15,16]]

CodePudding user response:

view_as_windows returns overlapping window views into the same array. Your array has 3x3 such windows, starting at (row, col) coordinates (0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), and (2, 2). You seem to want nonoverlapping windows, which scikit-image calls view_as_blocks:

import numpy as np
from skimage.util import view_as_blocks

matrix = np.random.random((4, 4, 3))
blocked = view_as_blocks(matrix, (2, 2, 3))
print(blocked.shape)

This will print:

(2, 2, 1, 2, 2, 3)

Your four (2, 2, 3) matrices are at coordinates (0, 0, 0), (0, 1, 0), (1, 0, 0), and (1, 1, 0) in the above array. There is still a dimension for the blocking along the final axis, even though there is only a single block in that axis.

You can get a linear array of just the four with:

linearized = blocked.reshape((4, 2, 2, 3))
  • Related