方法一
import numpy as np
def order_points(pts):
"""
# 四边形点的顺时针排序
:param pts: [[243.,9.], [ 4.,15.], [245.,233.], [ 5.,15.]] type:array
:return:
"""
# 基于x坐标进行排序
sorted_x = pts[np.argsort(pts[:, 0]), :]
# 最左边的两个点
leftmost = sorted_x[:2, :]
# 最右边的两个点
rightmost = sorted_x[2:, :]
if leftmost[0, 1] != leftmost[1, 1]:
# 最左边两个点的y坐标不同时,按y坐标从小到大排序
leftmost = leftmost[np.argsort(leftmost[:, 1]), :]
else:
# 最左边两个点的y坐标相同时,按x坐标从大到小排序
leftmost = leftmost[np.argsort(leftmost[:, 0])[::-1], :]
(tl, bl) = leftmost
if rightmost[0, 1] != rightmost[1, 1]:
# 最右边两个点的y坐标不同时,按y坐标从小到大排序
rightmost = rightmost[np.argsort(rightmost[:, 1]), :]
else:
# 最右边两个点的y坐标相同时,按x坐标从大到小排序
rightmost = rightmost[np.argsort(rightmost[:, 0])[::-1], :]
(tr, br) = rightmost
return np.array([tl, tr, br, bl], dtype="float32")
方法二
def sort_vertex(vertices):
"""
:param vertices: [[243.,9.], [ 4.,15.], [245.,233.], [ 5.,15.]] type:array
:return:
"""
assert vertices.ndim == 2
assert vertices.shape[-1] == 2
N = vertices.shape[0]
if N == 0:
return vertices
center = np.mean(vertices, axis=0)
directions = vertices - center
angles = np.arctan2(directions[:, 1], directions[:, 0])
sort_idx = np.argsort(angles)
vertices = vertices[sort_idx]
# 找出x_min, y_min
left_top = np.min(vertices, axis=0)
# 按照行向量求l2范数
dists = np.linalg.norm(left_top - vertices, axis=-1, ord=2)
# 定左上角的id
lefttop_idx = np.argmin(dists)
indexes = (np.arange(N, dtype=np.int32) + lefttop_idx) % N
return vertices[indexes]