如何在Python / NumPy中从数组的中心点添加不同的数组

时间:2014-09-02 23:37:48

标签: python arrays numpy

来自" Adding different sized/shaped displaced NumPy matrices",我想扩展代码,以便我可以在中心添加

import numpy as np

#two 3d arrays, of different size.

# b1 is variable in size, for the purposes of illustration, lets make it 5x5x5
b1 = np.zeros((5,5,5), dtype=np.int)

# b2 is a fixed size matrix in practice of 10x10x10, but for purposes of illustration,
# its 3x3x3
b2 = np.ones((3,3,3), dtype=np.int)

# want to add b1 to b2, but at a specific location.
# Here, for the purposes of illustration I use the location 2x2x2 in b1 so that the      added values fit in the
# lower back corner of b1.

pos_v, pos_h, pos_z = 2, 2, 2  # the 3d coordinates. I want b2 to be centered at 3,3,3 in b1, so this is a bit of a hack to make it fit

v_range1 = slice(max(0, pos_v), max(min(pos_v + b2.shape[0], b1.shape[0]), 0))
h_range1 = slice(max(0, pos_h), max(min(pos_h + b2.shape[1], b1.shape[1]), 0))
z_range1 = slice(max(0, pos_z), max(min(pos_z + b2.shape[2], b1.shape[2]), 0))

v_range2 = slice(max(0, -pos_v), min(-pos_v + b1.shape[0], b2.shape[0]))
h_range2 = slice(max(0, -pos_h), min(-pos_h + b1.shape[1], b2.shape[1]))
z_range2 = slice(max(0, -pos_z), min(-pos_z + b1.shape[2], b2.shape[2]))

b1[v_range1, h_range1, z_range1] += b2[v_range2, h_range2, z_range2]

这给出了b1的结果

>> b1
array([[[0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]],

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

   [[0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 1]],

   [[0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 1]],

   [[0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 1]]])

但理想情况下,我想进行加法,使b2的中心(3x3x3矩阵)位于实际目标3,3,3的中心。而不是2,2,2的矩阵的角落。这个例子的结果是一样的(因为我人为地移动了目标,即3,3,3到2,2,2,所以它会到达相同的位置),但是在实际的代码中我使用它(其中)矩阵中的数据没有与矩阵轴对齐,它是倾斜的,如果我做了类似的黑客攻击,结果将会大不相同。

在实践中,我的" b1"矩阵将是可变大小,但远大于5x5x5," b2"将是10x10x10或更大。我在目标矩阵(b1)中有精确的位置坐标,这是我想要从b2标记数据中心的中心(基本上我正在处理3d体积图像数据,我想放一个在3d体积中的坐标处的球体)。正如我所说,矩阵中的数据没有与矩阵轴对齐,因此通过将其偏移为b2的大小来修改目标坐标位置并不是最大的想法(但我考虑过的一个)。这可能是迂腐的,但我宁愿从一开始就把它弄好。

有人可以提供任何建议吗?

0 个答案:

没有答案