在numpy阵列外部切片

2024-04-25 07:25:26 发布

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

给定二维矩阵,例如:

A = array([[ 0,  1,  2,  3],
          [ 4,  5,  6,  7],
          [ 8,  9, 10, 11],
          [12, 13, 14, 15]])

如何选择给定元素周围的NxN窗口,以便在窗口超出原始数组时用任意(例如平均值)值填充窗口?在

示例:

^{pr2}$

会屈服的

array([[ 2.5,  2.5,  2.5],
       [ 2.5,    0,    1],
       [ 2.5,    4,    5]])

Tags: 元素示例矩阵数组array平均值屈服时用
3条回答

你可以pad你的数组。填充将使用所需的边界条件扩展数组(有关所有可能的选项,请参见mode参数):

>>> A = np.array([[ 0,  1,  2,  3],
                  [ 4,  5,  6,  7],
                  [ 8,  9, 10, 11],
                  [12, 13, 14, 15]])
>>> N = 5 # 5x5 windows
>>> B = np.pad(A, N//2, mode='reflect')
>>> B
array([[10,  9,  8,  9, 10, 11, 10,  9],
       [ 6,  5,  4,  5,  6,  7,  6,  5],
       [ 2,  1,  0,  1,  2,  3,  2,  1],
       [ 6,  5,  4,  5,  6,  7,  6,  5],
       [10,  9,  8,  9, 10, 11, 10,  9],
       [14, 13, 12, 13, 14, 15, 14, 13],
       [10,  9,  8,  9, 10, 11, 10,  9],
       [ 6,  5,  4,  5,  6,  7,  6,  5]])

如您所见,原始数组位于矩阵的中心,由2行2列(N//2 = 5//2 = 2,从lef/right和bottom/top)填充。填充元素被反射。在

对于这个新数组,您可以通过正常索引数组来访问所需的邻居窗口:

^{pr2}$

您可以选择其他填充方法,mean是选项之一。在

这里有一种使用^{}^{}-

Ap = np.lib.pad(A.astype(float),1, 'constant', constant_values=(np.nan,np.nan))
Acut = Ap[np.ix_(np.arange(N)+x,np.arange(N)+y)]
Acut[np.isnan(Acut)] = np.nanmean(Acut)

样本运行-

^{pr2}$

我想这不算太远:

def neighbors(arr, x, y, N):
    left = max(0, x - N)
    right = min(arr.shape[0], x + N)
    top = max(0, y - N)
    bottom = min(arr.shape[1], y + N)

    window = arr[left:right+1,top:bottom+1]
    fillval = window.mean()

    result = np.empty((2*N+1, 2*N+1))
    result[:] = fillval

    ll = N - x
    tt = N - y
    result[ll+left:ll+right+1,tt+top:tt+bottom+1] = window

    return result

相关问题 更多 >