Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating bounding box of numpy array

Tags:

python

numpy

I'm struggling with a simple question. I have a numpy array of the form:

[[[ 1152.07507324   430.84799194]
  [ 4107.82910156   413.95199585]
  [ 4127.64941406  2872.32006836]
  [ 1191.71643066  2906.11206055]]]

And I want to calculate the bounding box, meaning, I want to have the leftmost, topmost, rightmost and bottommost point.

This should be a correct solution

[[[ 1152.07507324   413.95199585]
  [ 4127.64941406   413.95199585]
  [ 4127.64941406  2906.11206055]
  [ 1152.07507324  2906.11206055]]]

I developed a nasty function that does the trick, but I'm very unsatisfied with it since its not really pythonic/numpyic

def bounding_box(iterable):
    minimum_x = min(iterable[0], key=lambda x:x[0])[0]
    maximum_x = max(iterable[0], key=lambda x:x[0])[0]
    minimum_y = min(iterable[0], key=lambda x:x[1])[1]
    maximum_y = max(iterable[0], key=lambda x:x[1])[1]

    return numpy.array([[(minimum_x, minimum_y), (maximum_x, minimum_y), (maximum_x, maximum_y), (minimum_x, maximum_y)]], dtype=numpy.float32)

Do you have any idea how to optimize the function above, perhaps using numpy builtins?

like image 962
anopheles Avatar asked Sep 16 '12 01:09

anopheles


2 Answers

Use the numpy.min and numpy.max builtins:

def bounding_box(iterable):
    min_x, min_y = numpy.min(iterable[0], axis=0)
    max_x, max_y = numpy.max(iterable[0], axis=0)
    return numpy.array([(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)])
like image 76
nneonneo Avatar answered Sep 21 '22 23:09

nneonneo


returns the same as previous answer but shorter and cleaner

returns 2*2 ndarray

def bbox(points):
    """
    [xmin xmax]
    [ymin ymax]
    """
    a = zeros((2,2))
    a[:,0] = np.min(points, axis=0)
    a[:,1] = np.max(points, axis=0)
    return a
like image 36
tal Avatar answered Sep 20 '22 23:09

tal