将给定点上的3x3数组求和到另一个保持边界的矩阵

时间:2018-10-16 07:58:16

标签: python numpy

假设我有这个二维数组A:

[[0,0,0,0],
 [0,0,0,0],
 [0,0,0,0],
 [0,0,0,4]]

我想对B求和:

[[1,2,3]
 [4,5,6]
 [7,8,9]]

以A [0] [0]为中心,因此结果为:

array_sum(A,B,0,0) =
[[5,6,0,4],
 [8,9,0,0],
 [0,0,0,0],
 [2,0,0,5]]

我当时想我应该做一个比较它是否在边界上的函数,然后为此调整索引:

def array_sum(A,B,i,f):
   ...
   if i == 0 and j == 0:
      A[-1][-1] = A[-1][-1]+B[0][0]
      ...

   else:
      A[i-1][j-1] = A[i][j]+B[0][0]
      A[i][j] = A[i][j]+B[1][1]
      A[i+1][j+1] = A[i][j]+B[2][2]
      ...

但是我不知道是否有更好的方法,我正在阅读有关广播或为此使用卷积的方法,但是我不确定是否有更好的方法。

2 个答案:

答案 0 :(得分:1)

假设B.shape都是奇数,则可以使用np.indices,操纵它们以指向所需的位置,然后使用np.add.at

def array_sum(A, B, loc = (0, 0)):
    A_ = A.copy()
    ix = np.indices(B.shape)
    new_loc = np.array(loc) - np.array(B.shape) // 2
    new_ix = np.mod(ix + new_loc[:, None, None], 
                    np.array(A.shape)[:, None, None])
    np.add.at(A_, tuple(new_ix), B)
    return A_

测试:

array_sum(A, B)
Out:
array([[ 5.,  6.,  0.,  4.],
       [ 8.,  9.,  0.,  7.],
       [ 0.,  0.,  0.,  0.],
       [ 2.,  3.,  0.,  5.]])

答案 1 :(得分:0)

通常,拇指切片索引比奇特的索引要快(〜2倍)。即使对于OP中的小示例,这似乎也是正确的。缺点:代码稍微复杂一些。

import numpy as np
from numpy import s_ as _
from itertools import product, starmap

def wrapsl1d(N, n, c):
    # check in 1D whether a patch of size n centered at c in a vector
    # of length N fits or has to be wrapped around
    # return appropriate slice objects for both vector and patch
    assert n <= N
    l = (c - n//2) % N
    h = l + n
    # return list of pairs (index into A, index into patch)
    # 2 pairs if we wrap around, otherwise 1 pair
    return [_[l:h, :]] if h <= N else [_[l:, :N-l], _[:h-N, n+N-h:]]

def use_slices(A, patch, center=(0, 0)):
    slAptch = product(*map(wrapsl1d, A.shape, patch.shape, center))
    # the product now has elements [(idx0A, idx0ptch), (idx1A, idx1ptch)]
    # transpose them:
    slAptch = starmap(zip, slAptch)
    out = A.copy()
    for sa, sp in slAptch:
        out[sa] += patch[sp]
    return out