四点顺序排序

方法一

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]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容