用mas求二维阵列中numpy元素的平均值

2024-04-20 07:50:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到一个二维数组中的numpy元素的平均值,该数组围绕一个选定的点,具有选定的邻域大小和形状。你知道吗

我举了个例子来解释我要做的事。由于形状问题,它还不能处理大多数输入。在我继续之前,有没有一个优雅或内置的方式来做这件事?你知道吗

import numpy as np
from skimage.morphology import disk

def get_sub_array_about_point(array, point, size):
    i1 = point[0]-(size-1)
    i2 = point[0]+size
    j1 = point[1]-(size-1)
    j2 = point[1]+size
    return array[i1:i2, j1:j2]

def get_neighborhood_mean(array, point, size, shape):

    sub_array = get_sub_array_about_point(test_array, point, size)
    """
    array([[10.1,  1.2,  1.3],
           [ 2.1, 20.2,  2.3],
           [ 3.1,  3.2,  3.3]])
    """

    masked_sub_array = np.ma.masked_where(mask==False, sub_array)
    masked_sub_array
    """
    masked_array(
      data=[[--, 1.2, --],
            [2.1, 20.2, 2.3],
            [--, 3.2, --]],
      mask=[[ True, False,  True],
            [False, False, False],
            [ True, False,  True]],
      fill_value=1e+20)
    """

    return masked_sub_array.mean()
    """
    5.8
    """

test_array = np.array([[0. , 0.1 , 0.2 , 0.3 ],
                       [1. , 10.1 , 1.2, 1.3 ],
                       [2. , 2.1, 20.2, 2.3 ],
                       [3. , 3.1 , 3.2, 3.3 ]])

mask = disk(1)
"""
array([[0, 1, 0],
       [1, 1, 1],
       [0, 1, 0]], dtype=uint8)
"""
get_neighborhood_mean(test_array, point=(2,2), size=2, shape=mask)

Tags: testimportnumpyfalsetruesizegetnp
1条回答
网友
1楼 · 发布于 2024-04-20 07:50:14

一种优雅的方法是使用2D convolution。如果对mask中的元素进行规格化(除以元素之和),卷积将得到一个2D数组,它是邻域的平均值。你知道吗

from scipy.signal import convolve2d

test_array = np.array([[0. , 0.1 , 0.2 , 0.3 ],
                       [1. , 10.1 , 1.2, 1.3 ],
                       [2. , 2.1, 20.2, 2.3 ],
                       [3. , 3.1 , 3.2, 3.3 ]])

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

# Normalize mask
mask = mask / float(np.sum(mask))

convolve2d(test_array, mask, mode='valid')
# array([[2.9, 6.6],
#        [7.5, 5.8]])

通过使用mode='valid',平均值只针对不需要填充的元素给出,在这些元素中,掩码可以容纳而不必延伸到数组的边缘之外。所以在上面的例子中,输出数组只针对test_array的中心4个元素。你知道吗

如果要获得所有元素的邻域平均值,包括在边上,可以通过设置mode='same'来使用零填充。你知道吗

convolve2d(test_array, mask, mode='same')
# array([[0.22, 2.08, 0.36, 0.36],
#        [2.62, 2.9 , 6.6 , 1.02],
#        [1.62, 7.5 , 5.8 , 5.42],
#        [1.62, 2.28, 5.96, 1.76]])

相关问题 更多 >