【问题标题】:(4,1,2) Numpy Array Sort Clockwise(4,1,2) Numpy 数组顺时针排序
【发布时间】:2015-07-17 07:06:03
【问题描述】:

我有一个如下的 numpy 数组:

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

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

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

我已经阅读了this,但我在 numpy 上的技能并不能很好地实现它......

谢谢!

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

你可以这样做 -

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)

【讨论】:

  • OP 注意:如果输入数组的形状为4 x 1 x 2,则可以在开始执行其余代码之前将其压缩为4 x 2 的形状。因此,在这种情况下可以使用开头的A = np.squeeze(A)
  • 效果很好,但我需要更改某些矩阵的容差,例如 A = np.float32([[281., 147.],[213. ,170.],[239. ,242 .], [307. ,219.]]),所以我做了一个可变公差,有没有建议给定点如何选择这个公差?
  • @LuisEnrique 请查看编辑。现在,它使用eucl。 dist.,所以必须更健壮。
【解决方案2】:

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

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2011-10-16
    • 2019-03-19
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2018-02-15
    • 2010-09-19
    相关资源
    最近更新 更多