Вот подход, который использует произвольные массивы, координаты и размеры окон.
def compute_indices(c, ws, length):
# default setting: % operations to accommodate odd/even window sizes
low, high = c - (ws//2), c + (ws//2) + ws%2
# correction for overlap with borders of array
if low<0:
low, high = 0, ws
elif high>length:
low, high = -ws, None
return low, high
def extract_block(arr, coords, window_size=(3,3)):
# extract array shapes and window sizes into single
# variables
len_r, len_c = arr.shape
wsr, wsc = window_size
# extract coords and correct for 0-indexing
r, c = coords
r0, c0 = r-1, c-1
row_low, row_high = compute_indices(r0, wsr, len_r)
col_low, col_high = compute_indices(c0, wsc, len_c)
return arr[row_low:row_high, col_low:col_high]
тестовые случаи:
a = np.arange(81).reshape(9,9)
extract_block(a, [1,1], (3,3))
array[[ 0 1 2]
[ 9 10 11]
[18 19 20]]
extract_block(a, [9,9], (3,3))
array([[60, 61, 62],
[69, 70, 71],
[78, 79, 80]])
extract_block(a, [5,2], (3,6))
array([[27, 28, 29, 30, 31, 32],
[36, 37, 38, 39, 40, 41],
[45, 46, 47, 48, 49, 50]])