[英]Numpy: Finding the bounding box within a 2d array
I have a bounding box that sits inside a 2-d array, where areas outside of the bounding box are marked as 'nan'. 我有一个位于2维数组内的边界框,其中边界框之外的区域被标记为“ nan”。 I am looking for a way to locate the 4 corners of the bounding box, aka, the indices of the values adjacent to the 'nan' value.
我正在寻找一种方法来定位边界框的4个角,也就是与“ nan”值相邻的值的索引。 I can do it in a 'for-loop' way, but just wonder if there are faster ways to do so.
我可以以“循环”方式进行操作,但是只是想知道是否有更快的方法。
For the following example, the results should return row index 2,4, and column index 1, 4. 对于以下示例,结果应返回行索引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]]
Thanks. 谢谢。
This will give max and min of the two axes: 这将给出两个轴的最大值和最小值:
xmax, ymax = np.max(np.where(~np.isnan(a)), 1)
xmin, ymin = np.min(np.where(~np.isnan(a)), 1)
Have a look at np.where
: 看看
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)))
You should be able to get the bounding box from where_not_nan
: 您应该能够从
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)]
You must check for matrix with all nans 您必须检查所有nan的矩阵
row, col = np.where(~np.isnan(matrix))
r1, c1 = row[ 0], col[ 0]
r2, c2 = row[-1], col[-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.