cython
1import numpy as np2
3
4def naive_convolve(f, g):5# f is an image and is indexed by (v, w)6# g is a filter kernel and is indexed by (s, t),7# it needs odd dimensions8# h is the output image and is indexed by (x, y),9# it is not cropped10if g.shape[0] % 2 != 1 or g.shape[1] % 2 != 1:11raise ValueError("Only odd dimensions on filter supported")12# smid and tmid are number of pixels between the center pixel13# and the edge, ie for a 5x5 filter they will be 2.14#15# The output size is calculated by adding smid, tmid to each16# side of the dimensions of the input image.17vmax = f.shape[0]18wmax = f.shape[1]19smax = g.shape[0]20tmax = g.shape[1]21smid = smax // 222tmid = tmax // 223xmax = vmax + 2 * smid24ymax = wmax + 2 * tmid25# Allocate result image.26h = np.zeros([xmax, ymax], dtype=f.dtype)27# Do convolution28for x in range(xmax):29for y in range(ymax):30# Calculate pixel value for h at (x,y). Sum one component31# for each pixel (s, t) of the filter g.32s_from = max(smid - x, -smid)33s_to = min((xmax - x) - smid, smid + 1)34t_from = max(tmid - y, -tmid)35t_to = min((ymax - y) - tmid, tmid + 1)36value = 037for s in range(s_from, s_to):38for t in range(t_from, t_to):39v = x - smid + s40w = y - tmid + t41value += g[smid - s, tmid - t] * f[v, w]42h[x, y] = value43return h44