且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

提高 Numpy 性能

更新时间:2023-02-27 11:32:44

scipy 中用于进行 2d 卷积的代码有点混乱且未优化.见 http://svn.scipy.org/svn/scipy/如果您想了解 scipy 的底层功能,请访问 trunk/scipy/signal/firfilter.c.

The code in scipy for doing 2d convolutions is a bit messy and unoptimized. See http://svn.scipy.org/svn/scipy/trunk/scipy/signal/firfilter.c if you want a glimpse into the low-level functioning of scipy.

如果您只想使用像您展示的那样一个小的、恒定的内核进行处理,这样的函数可能会起作用:

If all you want is to process with a small, constant kernel like the one you showed, a function like this might work:

def specialconvolve(a):
    # sorry, you must pad the input yourself
    rowconvol = a[1:-1,:] + a[:-2,:] + a[2:,:]
    colconvol = rowconvol[:,1:-1] + rowconvol[:,:-2] + rowconvol[:,2:] - 9*a[1:-1,1:-1]
    return colconvol

这个函数利用了上面建议的 DarenW 内核的可分离性,以及更优化的 numpy 算术例程.根据我的测量,它比 convolve2d 函数快 1000 多倍.

This function takes advantage of the separability of the kernel like DarenW suggested above, as well as taking advantage of the more optimized numpy arithmetic routines. It's over 1000 times faster than the convolve2d function by my measurements.