5

我正在为一个简单的问题而苦苦挣扎。我有一个形式的numpy数组:

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

我想计算边界框,意思是,我想要最左边、最上面、最右边和最下面的点。

这应该是一个正确的解决方案

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

我开发了一个讨厌的函数来解决这个问题,但我对它非常不满意,因为它不是真正的 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)

您是否知道如何优化上述功能,也许使用 numpy 内置函数?

4

2 回答 2

10

使用numpy.minnumpy.max内置:

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)])
于 2012-09-16T01:22:09.670 回答
3

返回与上一个答案相同但更短更清晰

返回 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
于 2015-05-31T15:43:16.720 回答