numpy 获取数组轴的最大值和最小值,然后重新整形

14ifxucb  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(117)

我有一个文本文件,其中的线条定义了几个多边形:

x1,y1,x2,y2,x3,y3,x4,y4
x1,y1,x2,y2,x3,y3,x4,y4
.
.
.

etc

我想把它们读到一个numpy数组与一个轴具有相同的形状的多边形(即。盒子)和其他人喜欢:

[x_min,y_min],[x_min,y_max],[x_max,y_max],[x_max,y_min]

其中x_min是最小x坐标,x_max是最大值等。
我可以读取并获得max和mins:

boxes_x = np.loadtxt(label_path,usecols=np.arange(0,8,2),dtype=int,delimiter=",")
boxes_y = np.loadtxt(label_path,usecols=np.arange(1,8,2),dtype=int,delimiter=",")

 x_max = boxes_x[:].max(axis=1)
 y_max = boxes_y[:].max(axis=1)
 x_min = boxes_x[:].min(axis=1)
 y_min = boxes_y[:].min(axis=1)

但将它们塑造成正确的形状,即[num_boxes,4,2],证明是困难的。
最好的方法是什么?

unhi4e5o

unhi4e5o1#

立即将文件读入boxes

boxes = np.loadtxt(label_path, dtype=int,delimiter=",")

假设boxes表示4个条目(多边形):

array([[15, 10, 20, 31,  6, 28, 23,  3],
       [30, 24,  7, 13, 24,  4, 29, 20],
       [ 1,  7,  0, 14,  2, 11,  6, 24],
       [15, 18,  7,  7,  1,  1, 21, 13]])

分别为 xy 坐标找到minmax

x_min, x_max = boxes[:, ::2].min(1), boxes[:, ::2].max(1)
y_min, y_max = boxes[:, 1::2].min(1), boxes[:, 1::2].max(1)

构建所需结构和形状的输出数组:

out_boxes = np.dstack([x_min, y_min, x_min, y_max, 
                       x_max, y_max, x_max, y_min]).reshape(-1, 4, 2)

样品输出:

array([[[ 6,  3],
        [ 6, 31],
        [23, 31],
        [23,  3]],

       [[ 7,  4],
        [ 7, 24],
        [30, 24],
        [30,  4]],

       [[ 0,  7],
        [ 0, 24],
        [ 6, 24],
        [ 6,  7]],

       [[ 1,  1],
        [ 1, 18],
        [21, 18],
        [21,  1]]])
out_boxes.shape
(4, 4, 2)

相关问题