Skip to main content
 首页 » 编程设计

python之在numpy数组中填写超出范围的部分

2025年01月19日7sky-heaven

不完全确定我应该如何命名这个问题。但是我怎样才能得到一个 numpy 数组的一部分,其中一些值在边界之外?

请参阅下面我的简单示例代码:

def get_section(a, center, square_radius): 
    return a[center[0] - square_radius:center[0] + square_radius + 1, \ 
              center[1] - square_radius:center[1] + square_radius + 1] 
 
 
 
array = [ 
    [1, 2, 3, 4, 5, 6, 7, 8, 9], 
    [2, 3, 4, 5, 6, 7, 8, 9, 1], 
    [3, 4, 5, 0, 7, 8, 9, 1, 2], 
    [4, 5, 6, 7, 8, 9, 1, 2, 3], 
    [5, 0, 7, 8, 9, 4, 5, 6, 7], 
    [6, 7, 8, 9, 1, 2, 3, 4, 5] 
] 
a = np.asarray(array) 
square_radius = 2 
 
 
center = [2,3] 
print(get_section(a, center, square_radius)) 
 
center = [4,1] 
print(get_section(a, center, square_radius)) 

假设我有一个数组,但我想通过指定我想要的部分的中心和半径来获取它的一小部分。

第一个会打印出来:

[[2 3 4 5 6] 
 [3 4 5 6 7] 
 [4 5 0 7 8] 
 [5 6 7 8 9] 
 [0 7 8 9 4]] 

这正是我想要的。为简单起见,我将“0”放在所确定的 2 个示例的中心。

但是第二个会打印出[]

对于第二个,我想用 -1 填充外部值。因此我希望它返回:

[[-1  3  4  5  0] 
 [-1  4  5  6  7] 
 [-1  5  0  7  8] 
 [-1  6  7  8  9] 
 [-1 -1 -1 -1 -1]] 

我如何在 numpy 中执行此操作?

请您参考如下方法:

终于!我已经使用 np.pad 完成了它.我不确定是否有更好的方法来执行此操作,因为它最终变得非常复杂,但它工作正常:

def get_section(a, center, square_radius): 
    tp = max(0, -(center[0] - square_radius)) 
    bp = max(0, -((a.shape[0]-center[0]-1) - square_radius)) 
    lp = max(0, -(center[1] - square_radius)) 
    rp = max(0, -((a.shape[1]-center[1]-1) - square_radius)) 
    a = np.pad(a, [[tp, bp], [lp, rp]], 'constant', constant_values=-1) 
    return a[center[0] - square_radius + tp:center[0] + square_radius + 1 + tp, \ 
              center[1] - square_radius + lp:center[1] + square_radius + 1 + lp] 

并使用您的示例进行测试:

>>> center = [2,3] 
>>> print(get_section(a, center, square_radius)) 
[[2 3 4 5 6] 
 [3 4 5 6 7] 
 [4 5 0 7 8] 
 [5 6 7 8 9] 
 [0 7 8 9 4]] 
>>> center = [4,1] 
>>> print(get_section(a, center, square_radius)) 
[[-1  3  4  5  0] 
 [-1  4  5  6  7] 
 [-1  5  0  7  8] 
 [-1  6  7  8  9] 
 [-1 -1 -1 -1 -1]] 

为什么?

首先,让我们定义一个数组来测试np.pad()函数:

>>> a 
array([[1, 2], 
       [3, 4]]) 

然后我们可以快速演示填充是如何工作的,从这个例子中应该是相当不言自明的:

>>> np.pad(a, [[1, 2], [0, 3]], 'constant', constant_values=-1) 
array([[-1, -1, -1, -1, -1], 
       [ 1,  2, -1, -1, -1], 
       [ 3,  4, -1, -1, -1], 
       [-1, -1, -1, -1, -1], 
       [-1, -1, -1, -1, -1]]) 

所以我们现在知道我们可以将 -1s 添加到我们想要的任何边缘,我们现在只需要计算是否这样做(正方形与边缘重叠,如第二个示例所示)和,如果是这样,我们需要向每条边添加多少个 -1。

这些填充距离定义在函数的顶部(tp, bp, ... for top pad, bottom pad...)我们计算出来通过一些计算。

计算基本上只是用边缘和中心之间的距离减去 square_radius。然而,如果我们把它留在这里,那么我们通常会得到负的填充距离(在半径小于到边缘的距离的情况下,为了解决这个问题,我们只使用 max() 函数与 0 使填充距离仅为正(需要填充)或 0(该边缘不需要填充)。

然后,在定义了所有这些之后,我们只需使用这些值调用 a 上的 pad 函数即可。

最后,我们使用您最初的“正方形提取”技术来获取围绕中心坐标的正方形。唯一的区别是我们需要通过顶部焊盘和左侧焊盘来偏移此处的所有索引。我们需要这样做,就好像我们刚刚填充了 3 的左垫,那么最初是 4 的中心现在将是 1 的中心(因为索引从填充边缘开始)。因此,为了解决这个问题,我们只是通过将填充差异添加到所有索引来抵消索引。

希望你现在已经明白了!