Created
January 13, 2016 19:07
-
-
Save kashefy/00279f9edb3a56fd3d15 to your computer and use it in GitHub Desktop.
2d convolution using numpy
This file contains hidden or 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
''' | |
Created on Jul 13, 2015 | |
@author: kashefy | |
''' | |
import numpy as np | |
from scipy import signal | |
if __name__ == '__main__': | |
x = np.array([[1, 1, 1, 0, 0], | |
[0, 1, 1, 1, 0], | |
[0, 0, 1, 1, 1], | |
[0, 0, 1, 1, 0], | |
[0, 1, 1, 0, 0]], | |
dtype='float') | |
w_k = np.array([[1, 0, 1], | |
[0, 1, 0], | |
[1, 0, 1],], | |
dtype='float') | |
w_k = np.rot90(w_k, 2) | |
print x.shape, w_k.shape | |
f = signal.convolve2d(x, w_k, 'valid') | |
print f | |
weights = np.random.randn() | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I feel this is a much-optimized approach to the problem https://stackoverflow.com/questions/43086557/convolve2d-just-by-using-numpy
def filter(im, fil):
# Get the shape of the 4d array
view_shape = tuple(np.subtract(im.shape, fil.shape) + 1) + fil.shape
strd = np.lib.stride_tricks.as_strided
# Get the new view of the array as required
subM = strd(im, shape = view_shape, strides = im.strides * 2)
# for every i,j element in filter multiply with 2d array ( of subM
# and return thier sum
return np.einsum('ij,ijkl->kl',fil,subM.T).T
filter(x, np.rot90(w_k,2)