Numpy:在二维数组中查找边界框

Numpy: Finding the bounding box within a 2d array

我有一个位于二维数组内的边界框,边界框外的区域标记为 'nan'。我正在寻找一种方法来定位边界框的 4 个角,也就是与 'nan' 值相邻的值的索引。我可以用 'for-loop' 的方式做到这一点,但只是想知道是否有更快的方法。

对于以下示例,结果应 return 行索引 2,4,列索引 1、4。

[[nan,nan,nan,nan,nan,nan,nan],
 [nan,nan,nan,nan,nan,nan,nan],
 [nan, 0,  7,  3,  3, nan,nan],
 [nan, 7,  6,  9,  9, nan,nan],
 [nan, 7,  9, 10,  1, nan,nan],
 [nan,nan,nan,nan,nan,nan,nan]]

谢谢。

看看np.where:

import numpy as np
a = [[nan,nan,nan,nan,nan,nan,nan],
    [nan,nan,nan,nan,nan,nan,nan],
    [nan, 0,  7,  3,  3, nan,nan],
    [nan, 7,  6,  9,  9, nan,nan],
    [nan, 7,  9, 10,  1, nan,nan],
    [nan,nan,nan,nan,nan,nan,nan]]

where_not_nan = np.where(np.logical_not(np.isnan(a)))

您应该能够从 where_not_nan:

获取边界框
bbox = [ (where_not_nan[0][0], where_not_nan[1][0]), 
        (where_not_nan[0][0], where_not_nan[1][-1]), 
        (where_not_nan[0][-1], where_not_nan[1][0]), 
        (where_not_nan[0][-1], where_not_nan[1][-1]) ]

bbox
# [(2, 1), (2, 4), (4, 1), (4, 4)]

这将给出两个轴的最大值和最小值:

xmax, ymax = np.max(np.where(~np.isnan(a)), 1)
xmin, ymin = np.min(np.where(~np.isnan(a)), 1)

您必须检查所有 nans 的矩阵

row, col = np.where(~np.isnan(matrix))
r1, c1 = row[ 0], col[ 0]
r2, c2 = row[-1], col[-1]