Last active
November 14, 2016 05:30
-
-
Save swayson/20357dc7ad07b7a3d3a0292396be00a6 to your computer and use it in GitHub Desktop.
Rolling block Numpy using strided tricks and padding.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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