我有一个位于二维数组内的边界框,其中边界框外的区域被标记为' nan'。我正在寻找一种方法来定位边界框的4个角,也就是说,与“' nan”相邻的值的索引。值。我可以在“for-loop”中进行此操作。方式,但只是想知道是否有更快的方法这样做。
对于以下示例,结果应返回行索引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]]
感谢。
答案 0 :(得分:2)
这将给出两个轴的最大值和最小值:
xmax, ymax = np.max(np.where(~np.isnan(a)), 1)
xmin, ymin = np.min(np.where(~np.isnan(a)), 1)
答案 1 :(得分:1)
查看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)]
答案 2 :(得分:1)
您必须检查所有nans的矩阵
row, col = np.where(~np.isnan(matrix))
r1, c1 = row[ 0], col[ 0]
r2, c2 = row[-1], col[-1]