scipy - Extract blocks or patches from NumPy Array -


i have 2-d numpy array follows:

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

i want extract patches of 2 2 sizes out repeating elements.

the answer should same. can 3-d array or list same order of elements below:

[[[1,5],  [2,6]],      [[3,7],  [4,8]],   [[9,13],  [10,14]],   [[11,15],  [12,16]]] 

how can easily?

in real problem size of (36, 72). can not 1 one. want programmatic way of doing it.

here's rather cryptic numpy one-liner generate 3-d array, called result1 here:

in [60]: x out[60]:  array([[2, 1, 2, 2, 0, 2, 2, 1, 3, 2],        [3, 1, 2, 1, 0, 1, 2, 3, 1, 0],        [2, 0, 3, 1, 3, 2, 1, 0, 0, 0],        [0, 1, 3, 3, 2, 0, 3, 2, 0, 3],        [0, 1, 0, 3, 1, 3, 0, 0, 0, 2],        [1, 1, 2, 2, 3, 2, 1, 0, 0, 3],        [2, 1, 0, 3, 2, 2, 2, 2, 1, 2],        [0, 3, 3, 3, 1, 0, 2, 0, 2, 1]])  in [61]: result1 = x.reshape(x.shape[0]/2, 2, x.shape[1]/2, 2).swapaxes(1, 2).reshape(-1, 2, 2) 

result1 1-d array of 2-d arrays:

in [68]: result1.shape out[68]: (20, 2, 2)  in [69]: result1[0] out[69]:  array([[2, 1],        [3, 1]])  in [70]: result1[1] out[70]:  array([[2, 2],        [2, 1]])  in [71]: result1[5] out[71]:  array([[2, 0],        [0, 1]])  in [72]: result1[-1] out[72]:  array([[1, 2],        [2, 1]]) 

(sorry, don't have time @ moment give detailed breakdown of how works. maybe later...)

here's less cryptic version uses nested list comprehension. in case, result2 python list of 2-d numpy arrays:

in [73]: result2 = [x[2*j:2*j+2, 2*k:2*k+2] j in range(x.shape[0]/2) k in range(x.shape[1]/2)]  in [74]: result2[5] out[74]:  array([[2, 0],        [0, 1]])  in [75]: result2[-1] out[75]:  array([[1, 2],        [2, 1]]) 

Comments