(4,1,2)numpy的数组排序顺时针 [英] (4,1,2) Numpy Array Sort Clockwise

查看:491
本文介绍了(4,1,2)numpy的数组排序顺时针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy的数组如下:

I have a numpy array as the following:

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

这4个点重新present摆在一个图像上的矩形的顶点,我需要顺时针重新排序,并将其保存到一个新的NP阵列(顶部左>右上 - >下 - 右键 - >底部 - 左)。在我的例子将是:

This 4 points represent the vertices of a rectangle that lies on a image, I need to reorder them clockwise and save it to a new np array, (top-left-> top-right -> bottom - right -> bottom - left). In my example it will be:

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

我已阅读但我对numpy的技能是不是好实现它...

I have read this but my skills on numpy aren't as good to implement it...

谢谢!

推荐答案

您可以做这样的事情 -

You could do something like this -

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)

样的输入,输出 -

Sample input, output -

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)

这篇关于(4,1,2)numpy的数组排序顺时针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆