Skip to content

Instantly share code, notes, and snippets.

@kashefy
Created January 13, 2016 19:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kashefy/00279f9edb3a56fd3d15 to your computer and use it in GitHub Desktop.
Save kashefy/00279f9edb3a56fd3d15 to your computer and use it in GitHub Desktop.
2d convolution using numpy
'''
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
@Multihuntr
Copy link

Hello random person, I am random person from the interwebs. This gist was the second result on Google for 'numpy 2D convolution' for me. I have a random person request; can you retitle your gist "2D Convolution with Scipy"?
Most people have numpy installed with python, but scipy is more specialised and requires deliberate installation.

@sherwoac
Copy link

sherwoac commented Feb 6, 2018

Agreed, I landed here hoping for numpy, not scipy.

@robertlugg
Copy link

I haven't evaluated, but you might consider this https://stackoverflow.com/a/42579291/2184122

@Foadsf
Copy link

Foadsf commented Aug 10, 2018

Hey guys, I'm also trying to implement the convolution of arbitrary shaped ndarrays in NumPy here you may wanna take a look.

@shubhMaheshwari
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment