Chiefscreation
Chiefscreation

Reputation: 181

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'. 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. 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.

[[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.

Upvotes: 0

Views: 1779

Answers (3)

lcastillov
lcastillov

Reputation: 2153

You must check for matrix with all nans

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

Upvotes: 1

dermen
dermen

Reputation: 5382

Have a look at 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:

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)]

Upvotes: 1

Aguy
Aguy

Reputation: 8059

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)

Upvotes: 3

Related Questions