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

如何在Python/NumPy中从数组的中心点添加不同的数组,python,arrays,numpy,Python,Arrays,Numpy,从开始,我想扩展代码,这样我就可以在中心进行添加 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,

从开始,我想扩展代码,这样我就可以在中心进行添加

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]]])
但理想情况下,我想做加法,这样3x3x3矩阵的中心就位于实际目标3,3,3的中心。而不是矩阵的角点在2,2,2。这个例子中的结果是一样的,因为我人为地移动了目标,目标是3,3,3到2,2,2,这样它会击中相同的位置,但是在我使用的实际代码中,矩阵中的数据没有与矩阵轴对齐,它是倾斜的,如果我做了类似的破解,结果会非常不同

实际上,我的b1矩阵的大小是可变的,但比5x5x5大得多,b2的大小是10x10x10或更大。我在目标矩阵b1中有精确的位置坐标,这是中心,我希望b2的数据中心被压印,基本上我正在处理3d体积图像数据,我想在3d体积的坐标处放置一个球体。正如我所说,矩阵中的数据没有与矩阵轴对齐,因此通过将目标坐标位置偏移为b2的大小来修改目标坐标位置不是最好的想法,而是我考虑过的想法。这可能有点迂腐,但我更愿意从一开始就把它做好


有人能提供一些建议吗?

那么使用偏移量有什么问题,坐标不是整数吗?默认情况下它们不是整数,但我已经这样做了。所以现在我用了一个偏移量。我想这是我必须坚持的。我现在有一个更大的问题,我得到了ValueError:在我的代码中无法将输入数组从shape3,2,3广播到shape3,0,3,因为我已经将它滚动到了我的全部主函数中。在某些情况下,它是有效的,而在其他情况下,它就是这样出现的。当我将b2阵列变小时,它通常会消失。