How (in python3) can I extract several n-by-m block from a M-by-N array centering in each element?
for example, In a 9-by-9 matrix, and using a 3-by-3 block, I need to extract the block at each position of the matrix. The challenge here (for me) is because of the I,J element inside of his respective block change of position.
here an image where I show the 9 blocks (for 9 positions) of a 9-by-9 matrix (of course there are 81 blocks to extract)
The code below works perfectly (ONLY) for the corners. Here the size of the block (Wsize-by-Wsize) is a odd number in order to locate the index (Eindex[0],Eindex1) in the middle.
def windowing(array,Wsize,Eindex):
'''
Extract an sub-array of array for the element located in the index 'Eindex'.
Wsize-by-Wsize is the shape of the window
'''
block=np.zeros(tuple(Wsize))
k0 = int((Wsize[0]-1)/2)
k1 = int((Wsize[1]-1)/2)
s0 = Wsize[0]
s1 = Wsize[1]
I = array.shape[0]-1 # las index in i-direction
J = array.shape[1]-1 # las index in i-direction
if (Eindex[0]==0) and (Eindex[1]==0):
block=array[0:Eindex[0]+s0,0:Eindex[1]+s1]
return block
elif (Eindex[0]==I) and (Eindex[1]==0):
block=array[-s0:,0:Eindex[1]+s1]
return block
elif (Eindex[0]==0) and (Eindex[1]==J):
block=array[0:Eindex[0]+s0,-s1:]
return block
elif (Eindex[0]==I) and (Eindex[1]==J):
block=array[-s0:,-s1:]
return block
for example check:
x = np.arange(81).reshape(9,9)
print(windowing(x,[3,3],[0,0]))
print(windowing(x,[3,3],[8,8))
print(windowing(x,[3,3],[8,0]))
print(windowing(x,[3,3],[0,8]))
