In this simple exercise, a simple ConvFilter in Numpy is created
Created
August 23, 2019 10:51
-
-
Save NicolaBernini/4b5ffeaa472312c93adc1ee1c07683b9 to your computer and use it in GitHub Desktop.
ConvFilter Kernel
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
# Defines a WxHxC ConvFilter | |
# Conventional Internal Representation is C,H,W | |
class Conv: | |
# w, h = Kernel Spatial Domain | |
# in_c = Input Tensor Channels | |
# out_c = Output Tensor Channels | |
def __init__(self, w, h, in_c, out_c): | |
self.w = w | |
self.h = h | |
self.in_c = in_c | |
self.out_c = out_c | |
# Choose the preferred initialization: ones or random | |
self.filters = np.ones((out_c, in_c,h,w)) | |
#self.filters = np.random.randn(out_c, in_c,h,w) / 9 | |
# Image Convention is CxHxW | |
def apply(self, image): | |
if(self.in_c != image.shape[0]): | |
raise("Channel Size Mismatch") | |
out_h = image.shape[1] - 2*(self.h//2) | |
out_w = image.shape[2] - 2*(self.w//2) | |
res = np.zeros((self.out_c, out_h, out_w)) | |
# Spatial Loop | |
for _c in range(self.out_c): | |
for _h in range( out_h ): | |
for _w in range( out_w ): | |
res[_c, _h, _w] = np.sum(image[:, _h:(_h+self.h), _w:(_w+self.w)] * self.filters[_c,:,:,:] ) | |
return res |
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
conv1 = Conv(3,3,1,6) | |
test_image = np.ones((1, 10, 10)) | |
res = conv1.apply(test_image) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment