'(Python) extract centered nxn grid from larger mxm grid

For Python, there are plenty of posts about extracting every possible nxn grid from a larger grid, but if I only want the centered nxn grid from the overall mxm grid, I am running in circles to figure this out.

For example:

>>> c = np.random.randint(1,20,size=(9,9))
>>> a
array([[ 8,  9,  4,  1,  3, 10, 14, 13,  2],
       [ 7,  3,  1, 14,  4, 11, 19,  5, 14],
       [11,  1,  7,  1, 17, 17,  8,  8, 17],
       [13, 18, 16, 12, 10,  7, 19,  6,  8],
       [15,  2, 13, 15,  1,  1,  2,  5, 15],
       [18,  8,  7,  6,  8,  3, 13, 15, 12],
       [10, 18, 18,  2,  4,  6,  1,  8, 13],
       [ 5,  6,  6, 18,  4, 11,  5, 10, 19],
       [15, 14, 13,  6, 19, 17, 17, 16,  1]])

If I wanted to extract a 3x3 grid, I would center if over the middle value (here, 1), where the resultant would be:

>>> a[3:6,3:6]
array([[12, 10,  7],
       [15,  1,  1],
       [ 6,  8,  3]])

And if I wanted a 5x5 grid centered on the middle value (again, 1) from this larger 9x9 grid:

>>> a[2:7,2:7]
array([[ 7,  1, 17, 17,  8],
       [16, 12, 10,  7, 19],
       [13, 15,  1,  1,  2],
       [ 7,  6,  8,  3, 13],
       [18,  2,  4,  6,  1]])

The problem is, how would one programatically derive the values to extract the grid based on a given nxn size? In other words, for the 3x3 grid, how would one arrive at 3:6, and then 2:7 for the 5x5 grid? I should note, the nxn and mxm grids will always be odd-numbered so there is an actual center.



Solution 1:[1]

This will probably work with something like this:

def grid_func(a,required_size):  
    centre_index=a.shape[0]//2
    start_index=centre_index-required_size//2
    end_index=start_index + required_size
return a[start_index:end_index,start_index:end_index]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1