简体   繁体   English

用掩码平均的numpy数组

[英]numpy array averaging with mask

I'm looking to do some basic clustering on a boolean numpy array and I'm basically just trying to do 2d averaging with a mask, but I feel like there must be a better solution than what I've got, since it's slow and inelegant: 我正在寻找在布尔numpy数组上进行一些基本聚类的方法,而我基本上只是在尝试使用蒙版进行2d平均,但是我觉得必须有比我现有方法更好的解决方案,因为它速度慢且不雅:

def grab_window(location, array, window=(3,3)):
    minimums = [min(0, i-a) for i, a in zip(location, window)]
    maximums = [(i + a) for i, a in zip(location, window)]
    answer = array
    for i, _ in enumerate(location):
        answer = answer[slice(minimums[i],maximums[i])]
    return answer

And then I basically just iterate through the original array, multiplying each window by a kernel, and returning the mean of the modified window. 然后,我基本上只是遍历原始数组,将每个窗口乘以一个内核,然后返回修改后的窗口的均值。

It seems like there must be a filter or something similar that would have the same effect, but I haven't been able to find one thus far. 似乎必须有一个具有相同效果的过滤器或类似的东西,但是到目前为止我还没有找到一个。

edit: location is a tuple of a form similar to window. 编辑:位置是类似于窗口形式的tuple

For instance, if we were to do the simplest version of this, with a uniform 1-ply mask I would be looking for something along these lines: 例如,如果我们要做的是最简单的版本,使用统一的1层蒙版,我会按照以下思路寻找东西:

import numpy as np
test = np.arange(0,24).reshape(6, 4)
footprint = [
[1,1,1],
[1,0,1],
[1,1,1]
]
some_function(test, footprint)
array([[ 1,  2,  3,  4],
   [ 4,  5,  6,  6],
   [ 8,  9, 10, 10],
   [12, 13, 14, 14],
   [16, 17, 18, 18],
   [18, 19, 20, 21]])

Turns out scipy totally has a function that already does this. 原来scipy完全有一个已经做到这一点的功能。 generic_filter actually does exactly this in a much more stable way as mentioned in How to apply ndimage.generic_filter() 正如如何应用ndimage.generic_filter()中所述, generic_filter实际上以一种更加稳定的方式精确地做到了这一点。

Example: 例:

def some_avg(values):
    return values.mean()

footprint = np.array([
    [1,1,1],
    [1,0,1],
    [1,1,1]
])

test = test = np.arange(0,24).reshape(6, 4)

scipy.ndimage.filters.generic_filter(test, some_avg, footprint=footprint)

array([[ 1,  2,  3,  4],
   [ 4,  5,  6,  6],
   [ 8,  9, 10, 10],
   [12, 13, 14, 14],
   [16, 17, 18, 18],
   [18, 19, 20, 21]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM