M1, N1 = padded.shape
rowlen = N1 - R + 1
collen = M1 - R + 1
idx1 = np.arange(R)[:, (None)] * N1 + np.arange(R)
idx2 = np.arange(collen)[:, (None)] * N1 + np.arange(rowlen)
all_idx = idx1.ravel()[(None), (None), :] + idx2[:, :, (None)]
out = padded.ravel()[all_idx]
Generalize stacking of array elements' neighbors into 3-D array