Skip to content

Instantly share code, notes, and snippets.

@kashefy kashefy/conv2d.py
Created Jan 13, 2016

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jan 23, 2018

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

This comment has been minimized.

Copy link

commented Feb 6, 2018

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

@robertlugg

This comment has been minimized.

Copy link

commented Feb 14, 2018

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

@Foadsf

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Aug 28, 2018

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
You can’t perform that action at this time.