Java教程

不归则四边行内部点寻找(基于向量方法非for循环)

本文主要是介绍不归则四边行内部点寻找(基于向量方法非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)

 

结果如下:

 

这篇关于不归则四边行内部点寻找(基于向量方法非for循环)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!