(4,1,2)Numpy Array按顺序排序

时间:2015-05-06 22:20:55

标签: python arrays numpy

我有一个numpy数组如下:

my_array = np.float32([[[ 323. , 143.]], [[ 237. , 143.]], [[ 227. , 230.]], [[ 318. , 233.]]])

这4个点代表位于图像上的矩形的顶点,我需要将它们顺时针重新排序并将其保存到新的np数组中(左上角 - >右上角 - >右上角 - 右下角 - > bottom - left)。在我的例子中,它将是:

[237,  143] -> [323, 143] -> [318, 233] -> [227, 230]

我已阅读this但我在numpy上的技巧并不适合实施...

谢谢!

2 个答案:

答案 0 :(得分:4)

你可以这样做 -

import numpy as np
from scipy.spatial import distance

def sortpts_clockwise(A):
    # Sort A based on Y(col-2) coordinates
    sortedAc2 = A[np.argsort(A[:,1]),:]

    # Get top two and bottom two points
    top2 = sortedAc2[0:2,:]
    bottom2 = sortedAc2[2:,:]

    # Sort top2 points to have the first row as the top-left one
    sortedtop2c1 = top2[np.argsort(top2[:,0]),:]
    top_left = sortedtop2c1[0,:]

    # Use top left point as pivot & calculate sq-euclidean dist against
    # bottom2 points & thus get bottom-right, bottom-left sequentially
    sqdists = distance.cdist(top_left[None], bottom2, 'sqeuclidean')
    rest2 = bottom2[np.argsort(np.max(sqdists,0))[::-1],:]

    # Concatenate all these points for the final output
    return np.concatenate((sortedtop2c1,rest2),axis =0)

示例输入,输出 -

In [85]: A
Out[85]: 
array([[ 281.,  147.],
       [ 213.,  170.],
       [ 239.,  242.],
       [ 307.,  219.]], dtype=float32)

In [86]: sortpts_clockwise(A)
Out[86]: 
array([[ 213.,  170.],
       [ 281.,  147.],
       [ 307.,  219.],
       [ 239.,  242.]], dtype=float32)

答案 1 :(得分:0)

如果您需要,请在示例中显示

new_array = my_array[[1,0,3,2]]

或完全顺时针(通常,不仅仅是4点)

n = len(my_array)
order = [i for i in range(0, n-2)]
order.insert(0, n-1)
new_array = my_array[order]