http://docs.cython.org/en/latest/src/tutorial/numpy.html
Cython与NumPy的工作
注意
Cython 0.16引入了类型化的内存视图,作为此处描述的NumPy集成的继承者。它们比下面的缓冲区语法更易于使用,开销较小,并且可以在不需要GIL的情况下进行传递。应优先使用此页面中显示的语法。有关NumPy用户的信息,请参见Cython。
您可以从Cython中使用NumPy,与在常规Python中完全一样,但是这样做会丢失潜在的高速度,因为Cython支持快速访问NumPy数组。让我们用一个简单的例子看看它是如何工作的。
下面的代码使用滤镜对图像进行2D离散卷积(我敢肯定,您可以做得更好!让它用于演示)。它既是有效的Python,又是有效的Cython代码。convolve_py.py
对于Python版本和convolve1.pyx
Cython版本,我都将其称为 – Cython使用“ .pyx”作为其文件后缀。
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