Skip to content

Instantly share code, notes, and snippets.

@swayson
Last active November 14, 2016 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swayson/20357dc7ad07b7a3d3a0292396be00a6 to your computer and use it in GitHub Desktop.
Save swayson/20357dc7ad07b7a3d3a0292396be00a6 to your computer and use it in GitHub Desktop.
Rolling block Numpy using strided tricks and padding.
import numpy as np
from numpy.lib.stride_tricks import as_strided
def rolling_block(A, block=(3, 3)):
shape = (A.shape[0] - block[0] + 1, A.shape[1] - block[1] + 1) + block
strides = (A.strides[0], A.strides[1]) + A.strides
return as_strided(A, shape=shape, strides=strides)
X = np.random.randint(0, 200, (10, 10))
X = np.pad(X, pad_width=1, mode='constant')
for block in rolling_block(X, (3,3)):
print(block.sum())
def rolling_block2(A, block=(3, 3)):
shape = (A.shape[0] - block[0] + 1, A.shape[1] - block[1] + 1) + block
strides = (A.strides[0], A.strides[1]) + A.strides
me = 0
for blocks in as_strided(A, shape=shape, strides=strides):
for b in blocks:
mask = np.array([
[0,1,0],
[1,0,1],
[0,1,0]
])
me += (b * mask).sum() * b[1, 1]
return me
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment