summaryrefslogtreecommitdiff
path: root/docs/examples/tutorial/numpy/convolve_py.py
diff options
context:
space:
mode:
authorscoder <stefan_ml@behnel.de>2018-06-16 09:04:48 +0200
committerGitHub <noreply@github.com>2018-06-16 09:04:48 +0200
commitf3f8727f3b3d1d7065a48c0294cb2f14b8a23587 (patch)
treeb8b8d986ec8b5b8c6e30d126993f594173eff858 /docs/examples/tutorial/numpy/convolve_py.py
parentf49e4461bbc3221a830c56f925b480c9c0a94ac5 (diff)
parent422151fc6a4a23e76119adb0079496ab109495e3 (diff)
downloadcython-f3f8727f3b3d1d7065a48c0294cb2f14b8a23587.tar.gz
Merge pull request #2349 from gabrieldemarmiesse/test_working_with_numpy_1
Adding tests for "working with numpy" part 1
Diffstat (limited to 'docs/examples/tutorial/numpy/convolve_py.py')
-rw-r--r--docs/examples/tutorial/numpy/convolve_py.py44
1 files changed, 44 insertions, 0 deletions
diff --git a/docs/examples/tutorial/numpy/convolve_py.py b/docs/examples/tutorial/numpy/convolve_py.py
new file mode 100644
index 000000000..547bae755
--- /dev/null
+++ b/docs/examples/tutorial/numpy/convolve_py.py
@@ -0,0 +1,44 @@
+from __future__ import division
+import numpy as np
+
+
+def naive_convolve(f, g):
+ # f is an image and is indexed by (v, w)
+ # g is a filter kernel and is indexed by (s, t),
+ # it needs odd dimensions
+ # h is the output image and is indexed by (x, y),
+ # it is not cropped
+ if g.shape[0] % 2 != 1 or g.shape[1] % 2 != 1:
+ raise ValueError("Only odd dimensions on filter supported")
+ # smid and tmid are number of pixels between the center pixel
+ # and the edge, ie for a 5x5 filter they will be 2.
+ #
+ # The output size is calculated by adding smid, tmid to each
+ # side of the dimensions of the input image.
+ vmax = f.shape[0]
+ wmax = f.shape[1]
+ smax = g.shape[0]
+ tmax = g.shape[1]
+ smid = smax // 2
+ tmid = tmax // 2
+ xmax = vmax + 2 * smid
+ ymax = wmax + 2 * tmid
+ # Allocate result image.
+ h = np.zeros([xmax, ymax], dtype=f.dtype)
+ # Do convolution
+ for x in range(xmax):
+ for y in range(ymax):
+ # Calculate pixel value for h at (x,y). Sum one component
+ # for each pixel (s, t) of the filter g.
+ s_from = max(smid - x, -smid)
+ s_to = min((xmax - x) - smid, smid + 1)
+ t_from = max(tmid - y, -tmid)
+ t_to = min((ymax - y) - tmid, tmid + 1)
+ value = 0
+ for s in range(s_from, s_to):
+ for t in range(t_from, t_to):
+ v = x - smid + s
+ w = y - tmid + t
+ value += g[smid - s, tmid - t] * f[v, w]
+ h[x, y] = value
+ return h