Skip to content

Instantly share code, notes, and snippets.

@MITsVision
Last active August 19, 2020 17:25
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 MITsVision/179867d39d7e7dd267c77e518225eb9f to your computer and use it in GitHub Desktop.
Save MITsVision/179867d39d7e7dd267c77e518225eb9f to your computer and use it in GitHub Desktop.
import numpy as np
#pure python implementation of convolutions of 2d arrays
def convolve2D(a1,a2,s):
'''
Calculating convolution for 2d array
Asumming all inputs a1,a2 nd-arrays of square shape (n*n)
Return:
convolution of inputs, nd-array
Input:
a1: input image
a2: kernal
s: stride
'''
n1,m1 = a1.shape
n2,m2 = a2.shape
if(n1 != m1 ): raise ValueError("expect square matrix")
if(n2 != m2): raise ValueError("expect square matrix")
if(n2>n1): raise ValueError("expect kernel shape lower than input")
outputSize = int(((n1 - n2)/s) + 1)
convMatrix = np.zeros((outputSize,outputSize))
outrow = 0
for row in range(0,n1-n2+1,s):
outcol = 0
for col in range(0,m1-m2+1,s):
#print("here\n",a1[row:row+n2,col:col+m2,:])
conv = np.sum(a1[row:row+n2,col:col+m2] * a2)
convMatrix[outrow,outcol] = conv
outcol = outcol + 1
outrow = outrow + 1
return convMatrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment