我正在努力解决一个简单的问题。我有一个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内置函数吗?
答案 0 :(得分:10)
使用numpy.min
和numpy.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)])
答案 1 :(得分:1)
返回与之前的答案相同但更短更清洁的
返回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