gpt4 book ai didi

python - numpy 数组用掩码求平均值

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:43 26 4
gpt4 key购买 nike

我希望在 bool 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

然后我基本上只是迭代原始数组,将每个窗口乘以内核,然后返回修改后的窗口的平均值。

似乎必须有一个过滤器或类似的东西可以达到相同的效果,但到目前为止我还没有找到。

编辑:位置是类似于窗口形式的元组

例如,如果我们要做最简单的版本,使用统一的单层掩模,我会寻找类似的东西:

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]])

最佳答案

事实证明 scipy 完全有一个函数可以做到这一点。 generic_filter 实际上以一种更稳定的方式做到了这一点,如 How to apply ndimage.generic_filter() 中所述。

示例:

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]])

关于python - numpy 数组用掩码求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23049119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com