numpy:将数组中的每个值替换为其相邻元素的均值 [英] Numpy: Replace every value in the array with the mean of its adjacent elements

查看:501
本文介绍了numpy:将数组中的每个值替换为其相邻元素的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ndarray,我想用其相邻元素的均值替换数组中的每个值.下面的代码可以完成这项工作,但是当我有700个都具有形状(7000,7000)的数组时,它的速度非常慢,所以我想知道是否有更好的方法可以做到这一点.谢谢!

I have an ndarray, and I want to replace every value in the array with the mean of its adjacent elements. The code below can do the job, but it is super slow when I have 700 arrays all with shape (7000, 7000) , so I wonder if there are better ways to do it. Thanks!

a = np.array(([1,2,3,4,5,6,7,8,9],[4,5,6,7,8,9,10,11,12],[3,4,5,6,7,8,9,10,11]))
row,col = a.shape
new_arr = np.ndarray(a.shape)
for x in xrange(row):
    for y in xrange(col):
        min_x = max(0, x-1)
        min_y = max(0, y-1)
        new_arr[x][y] = a[min_x:(x+2),min_y:(y+2)].mean()
print new_arr

推荐答案

好吧,这是 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

这篇关于numpy:将数组中的每个值替换为其相邻元素的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆