按顺时针方向排列多维点

2024-09-30 22:17:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个简单的程序,我想顺时针排列我的坐标点

fourPointsCard.append(firstPoint)
fourPointsCard.append(secondPoint)
fourPointsCard.append(thirdPoint)
fourPointsCard.append(fourPoint)

我创建了一个包含我所有4点的列表,并给出下一个列表

fourPointsCard = [array([[508, 116]], dtype=int32), array([[351, 129]], dtype=int32), array([[371, 379]], dtype=int32), array([[527, 366]], dtype=int32)]

有没有办法顺时针或逆时针排列这些点


Tags: 程序列表arraydtypeappend办法int32逆时针
1条回答
网友
1楼 · 发布于 2024-09-30 22:17:42

您的点似乎形成了一个凸面形状,这将允许此方法工作。简单地说,找到点的质心,然后找到从质心到每个点的夹角。基于此角度对点进行排序。我假设第一列是水平的,第二列是垂直的

import numpy as np

fourPointsCard = [np.array([[508, 116]]), np.array([[351, 129]]), np.array([[371, 379]]), np.array([[527, 366]])]

arr = np.array(fourPointsCard)[:, 0] # Remove singleton dimension

# Find the centroid
cen = np.mean(arr, axis=0)

# Find the angle from each point to its centroid
angles = np.arctan2(arr[:,1] - cen[1], arr[:,0] - cen[0])

# Because arctan spans -pi to pi, let's switch to 0 to 2*pi
angles[angles < 0] = angles[angles < 0] + 2*np.pi

# Order based on angle - ascending order
ind = np.argsort(angles)

# Reorder your points
arr_sorted = arr[ind]

arr将包含NumPy数组中的原始点,而arr_sorted将根据角度按升序对点进行排序。升序意味着您的点将按顺时针顺序排列。如果要逆时针排序,请使用ind = np.argsort(-angles)上排序

以下是订购前后的要点:

In [20]: arr
Out[20]:
array([[508, 116],
       [351, 129],
       [371, 379],
       [527, 366]])

In [21]: arr_sorted
Out[21]:
array([[527, 366],
       [371, 379],
       [351, 129],
       [508, 116]])

相关问题 更多 >