多边形内点判断方法(基于向量方法非for循环)

本文记录使用向量方法寻找非规则四边行的内部区域,可不使用for循环语句,加快代码运行,其详细代码如下:

 

import numpy
import numpy as np
import torch

def distinguish_point_pos(corners_list, point):
    """
    :param corners_list: tensor(8), eight corner coordinate, clockwise
    :param point: tensor(N, 2), to be distinguished
    :return: bool tensor(N)
    """
    assert corners_list.shape[0] == 8
    A = corners_list[0:2]
    B = corners_list[2:4]
    C = corners_list[4:6]
    D = corners_list[6:8]
    P = point
    AB = B - A
    AP = P - A
    # ABXAP = (b.x - a.x, b.y - a.y) x (p.x - a.x, p.y - a.y)
    # = (b.x -a.y)(p.y - a.y) -(b.y - a.y)(p.x - a.x)
    ABXAP = (AB[0] * AP[:, 1]) - (AB[1] * AP[:, 0])  # size(N)
    # print(ABXAP)
    BC = C - B
    BP = P - B
    BCXBP = (BC[0] * BP[:, 1]) - (BC[1] * BP[:, 0])
    CD = D - C
    CP = P - C
    CDXCP = (CD[0] * CP[:, 1]) - (CD[1] * CP[:, 0])
    DA = A - D
    DP = P - D
    DAXDP = (DA[0] * DP[:, 1]) - (DA[1] * DP[:, 0])
    """
    if (ABXAP >= 0 and BCXBP >= 0 and CDXCP >= 0 and DAXDP >= 0) or \
        (ABXAP < 0 and BCXBP < 0 and CDXCP < 0 and DAXDP < 0):
        return True
    else:
        return False"""
    distin_list = torch.zeros_like(ABXAP).bool()  # 保留正负样本的变量
    # t0 = time.time()
    idx1 = (ABXAP >= 0) * (BCXBP >= 0) * (CDXCP >= 0) * (DAXDP >= 0)
    idx2 = (ABXAP < 0) * (BCXBP < 0) * (CDXCP < 0) * (DAXDP < 0)
    distin_list[idx1] = True
    distin_list[idx2] = True
    # t1 = time.time()
    # print('找点for循环时间', t1-t0)
    return distin_list


if __name__ == '__main__':
    corners_list=torch.tensor([2,2,
                               8,2,
                               8,6,
                               2,6])
    y, x = torch.meshgrid([torch.arange(0, 12), torch.arange(0, 12)])
    grid = torch.stack([x, y], dim=-1).float()
    grid_center = (grid + 0.5).reshape(-1, 2)
    distin_list=distinguish_point_pos(corners_list, grid_center)
    distin_list=distin_list.numpy().reshape(12,12)
    print(distin_list)
不规则多边形内部点判断方法

 

结果如下:

 

posted @ 2022-06-10 12:52  tangjunjun  阅读(51)  评论(0编辑  收藏  举报
https://rpc.cnblogs.com/metaweblog/tangjunjun