【问题标题】:Elegant batch segment intersection calculation with numpy使用 numpy 进行优雅的批处理段相交计算
【发布时间】:2021-11-02 10:18:43
【问题描述】:

我有一个现实生活中的问题。我有一个表示由其地理坐标定义的道路的路段(我们称它们为 p1_road_test 和 p2_road_test),并且想测试它是否与另一组路段相交(我给所有路段不同的坐标以保持简单):

p1_road_test = np.array([1, 1]) # x, y value of point 1 of the road segment
p2_road_test = np.array([2, 4]) # x, y value of point 2 of the road segment

其他段由一个原点 (p_origin_test) 和另一个点 (p_moved_test) 定义,该点描述了原点在一年内移动到的位置:

p_origin_test = np.matrix([(3, 5, 6), (1, 1, 2)]) 
p_moved_test = np.matrix([(1,3, 3), (3, 3, 2)])
# basically, the original point (3, 1)  moved to position (1, 3) and spans the segment accordingly. (5, 1) moves to (3, 3) etc.

p_origin_test
Out[46]: 
matrix([[3, 5, 6],
        [1, 1, 2]])

p_moved_test Out[47]:  
matrix([[1, 3, 3],
        [3, 3, 2]])

我选择了一个 numpy 矩阵来存储数据以加快计算速度,因为我有 30000 多个路段需要针对街道路段进行测试。最后,我想知道当第二段继续以这种“速度”移动时,第二段是否会与街道相交(一个月后对 p_moved 进行了调查)。

我按照this post 计算两个线段是否相交并得出它们的 s 和 t 值。到目前为止一切顺利。

X1, Y1 = p1_road_test[0], p1_road_test[1]
X2, Y2 = p2_road_test[0], p2_road_test[1]

#count = 0
Segment1 = ((X1, Y1), (X2, Y2))
for i in range(0, np.shape(p_origin_test)[1]):
    X3, Y3 = p_origin_test[0, i], p_origin_test[1, i]
    X4, Y4 = p_moved_test[0, i], p_moved_test[1, i]
    Segment2 = ((X3, Y3), (X4, Y4))

    dx1 = X2 - X1
    dx2 = X4 - X3
    dy1 = Y2 - Y1
    dy2 = Y4 - Y3
    
    det = dx1 * dy2 - dx2 * dy1
    
    dx3 = X1 - X3
    dy3 = Y1 - Y3
    
    det1 = dx1 * dy3 - dx3 * dy1
    det2 = dx2 * dy3 - dx3 * dy2
    
    s = 3 / dx1
    t = 1 / dx1
    
    s = det1 / det
    t = det2 / det
    if s < 0.0 or s > 1.0 or t < 0.0 or t > 1.0:
        print('false', s, t)  # no intersect
    else:
        print(s, t)

导致预期的输出:

0.75 0.5
false 1.5 1.0
false 1.5555555555555556 0.3333333333333333

但是,我希望有另一个矩阵作为输出,其维度与我的输入数据集 (2, 30000) 相同,其中包含 s 和 t 值,因为我需要它来进一步推导“每时间单位的变化” .另外我知道有一种比遍历列更优雅的计算方式,但我想不通。

非常感谢您对此的意见。

我正在 Linux Mint 19.3 上的 Spyder3 中使用 Python 3.6.9。

【问题讨论】:

    标签: python numpy geometry intersection


    【解决方案1】:

    我现在创建了两个列表,

    s_list = []
    t_list = []
    

    在其中存储了 s 和 t 值

    [...]
    
    if s < 0.0 or s > 1.0 or t < 0.0 or t > 1.0:
        print('false', s, t)  # no intersect
    else:
        print(s, t)
    s_list.append(s)
    t_list.append(t)
    

    并由此创建了一个矩阵。

    st_values = np.matrix([s_list, t_list])
    

    不过,我确信还有更好的解决方案!?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      相关资源
      最近更新 更多