且构网

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

numpy:将数组中的每个值替换为其相邻元素的均值

更新时间:2023-09-03 08:39:04

好吧,这是 smoothing operation in image processing ,可以通过2D卷积实现.您在近边界元素上的工作有所不同.因此,如果为了精确而放宽边界元素,则可以使用

Well, that's a smoothing operation in image processing, which can be achieved with 2D convolution. You are working a bit differently on the near-boundary elements. So, if the boundary elements are let off for precision, you can use scipy's convolve2d like so -

from scipy.signal import convolve2d as conv2

out = (conv2(a,np.ones((3,3)),'same')/9.0

此特定操作是OpenCV模块内置的,如 cv2.blur 并非常有效.该名称基本上描述了模糊代表图像的输入数组的操作.我认为效率来自以下事实:内部完全在C中实现了性能,并使用了薄的Python包装程序来处理NumPy数组.

This specific operation is a built-in in OpenCV module as cv2.blur and is very efficient at it. The name basically describes its operation of blurring the input arrays representing images. I believe the efficiency comes from the fact that internally its implemented entirely in C for performance with a thin Python wrapper to handle NumPy arrays.

因此,可以使用它来替代计算输出,就像这样-

So, the output could be alternatively calculated with it, like so -

import cv2 # Import OpenCV module

out = cv2.blur(a.astype(float),(3,3))

这里是对相当大的图像/阵列的计时的快速展示-

Here's a quick show-down on timings on a decently big image/array -

In [93]: a = np.random.randint(0,255,(5000,5000)) # Input array

In [94]: %timeit conv2(a,np.ones((3,3)),'same')/9.0
1 loops, best of 3: 2.74 s per loop

In [95]: %timeit cv2.blur(a.astype(float),(3,3))
1 loops, best of 3: 627 ms per loop