In [1]:
import numpy as np
def conv(f, h):
f, h = np.asarray(f), np.asarray(h,float)
if len(f.shape) == 1: f = f[np.newaxis,:]
if len(h.shape) == 1: h = h[np.newaxis,:]
if f.size < h.size:
f, h = h, f
g = np.zeros(np.array(f.shape) + np.array(h.shape) - 1)
if f.ndim == 2:
H,W = f.shape
for (r,c) in np.transpose(np.nonzero(h)):
g[r:r+H, c:c+W] += f * h[r,c]
if f.ndim == 3:
D,H,W = f.shape
for (d,r,c) in np.transpose(np.nonzero(h)):
g[d:d+D, r:r+H, c:c+W] += f * h[d,r,c]
return g
In [1]:
testing = (__name__ == "__main__")
if testing:
! jupyter nbconvert --to python conv.ipynb
import numpy as np
import sys,os
ia898path = os.path.abspath('../../')
if ia898path not in sys.path:
sys.path.append(ia898path)
import ia898.src as ia
In [2]:
if testing:
f = np.zeros((5,5))
f[2,2] = 1
print('f:\n', f)
h = np.array([[1,2,3],
[4,5,6]])
print('h=\n',h)
a1 = ia.conv(f,h)
print('a1.dtype',a1.dtype)
print('a1=f*h:\n',a1)
a2 = ia.conv(h,f)
print('a2=h*f:\n',a2)
In [3]:
if testing:
f = np.array([[1,0,0,0],
[0,0,0,0]])
print(f)
h = np.array([1,2,3])
print(h)
a = ia.conv(f,h)
print(a)
In [4]:
if testing:
f = np.array([[1,0,0,0,0,0],
[0,0,0,0,0,0]])
print(f)
h = np.array([1,2,3,4])
print(h)
a = ia.conv(f,h)
print(a)
In [5]:
if testing:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
f = mpimg.imread('../data/cameraman.tif')
h = np.array([[ 1, 2, 1],
[ 0, 0, 0],
[-1,-2,-1]])
g = ia.conv(f,h)
gn = ia.normalize(g, [0,255])
ia.adshow(f,title='input')
ia.adshow(gn,title='filtered')
In [6]:
if testing:
print('testing conv')
print(repr(ia.conv(np.array([[1,0,1,0],[0,0,0,0]]), np.array([1,2,3]))) == repr(np.array(
[[1., 2., 4., 2., 3., 0.],
[0., 0., 0., 0., 0., 0.]])))
In [ ]: