0

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.

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.