繁体   English   中英

Numpy中的线段相交算法

[英]Segment Line Intersection algorithm in Numpy

我有两个线段AB: (A1,B1), (A2,B2)和axis_dx坐标间隔。 我应该找到所有与坐标轴间隔相交的点, ie,axis_dx 我已经找到了这些点,但是,问题是有时代码将两个起点和终点坐标相加两次,如下例所示。 我如何在所有情况下都解决该问题,即在段线的任何位置..? 我在这里先向您的帮助表示感谢。

简单的例子: 在这里

import numpy as np

def intrsctd_pnts(A,B, axis_dx):

   N, M = np.shape(A)

   # slope of each link ( straight line)
   delta_x = (A[:, 0] - B[:, 0])
   delta_y = (A[:, 1] - B[:, 1])
   # Each line beginning and ending (min,max) values for intersected points
   lx_min = np.minimum(B[:,0], A[:,0])
   lx_max = np.maximum(B[:,0], A[:,0])
   ly_min = np.minimum(B[:,1], A[:,1])
   ly_max = np.maximum(B[:,1], A[:,1])

   lx_floor = np.ceil(lx_min / axis_dx) * axis_dx
   lx_ceil = np.floor(lx_max / axis_dx) * axis_dx
   ly_floor = np.ceil(ly_min / axis_dx) * axis_dx
   ly_ceil = np.floor(ly_max / axis_dx) * axis_dx

   for i in range(N):
     AB = []
     if delta_x[i]<>0. and delta_y[i]<>0.:
            m = delta_y[i]/delta_x[i]
            b = B[i, 1] - m * B[i, 0]
            # calculate all intersected x coordinates
            x = np.arange(lx_floor[i], lx_ceil[i]+axis_dx, axis_dx)
            y = m * x + b
            AB = zip(x, y)
            # calculate all intersected y coordinates
            y = np.arange(ly_floor[i], ly_ceil[i]+axis_dx, axis_dx)
            #print 'y: ',y
            x = (y - b) / m
            AB.extend(zip(x, y))
     elif delta_x[i]==0. and delta_y[i]<>0.:
            y = np.arange(ly_floor[i], ly_ceil[i]+axis_dx, axis_dx)
            x = B[i,0]*np.ones(len(y))
            AB = zip(x,y)
     elif delta_x[i]<>0. and delta_y[i]==0.:
            x = np.arange(lx_floor[i], lx_ceil[i]+axis_dx, axis_dx)
            y = B[i,1]*np.ones(len(x))
            AB = zip(x,y)

     AB.append((B[i,0], B[i,1]))
     AB.append((A[i,0], A[i,1]))
     AB.sort()
     return AB

# A = (A1,A2)
A = np.array([ [9., 23.], [21., 29.]])  # ,
# B = (B1,B2)
B = np.array([ [24., 35.], [28., 21.]])  # ,
axis_dx = 1.
intrsctd_pnts(A,B, axis_dx)

这是删除几乎重叠的点的代码,如果两个连续点之间的距离小于阈值,则删除最后一个点:

r = np.array(intrsctd_pnts(A,B, axis_dx))
idx = np.where(np.sum(np.diff(r, axis=0)**2, -1) < 1e-20)[0]+1
r2 = np.delete(r, idx, axis=0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM