1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| import math
class Point: def __init__(self, x, y): self.x = x self.y = y def get_point(self): return self.x, self.y
def point_to_line_distance(point: Point, start: Point, end: Point):
"""点到线的距离
Args:
point (_type_): 点坐标(x,y)
start (_type_): 线段的起点 (x,y)
end (_type_): 线段的终点(x,y)
Returns:
float: 点线距离
"""
x, y = point.get_point()
x1, y1 = start.get_point()
x2, y2 = end.get_point()
numerator = abs((y2 - y1) * x - (x2 - x1) * y + x2 * y1 - y2 * x1)
denominator = ((y2 - y1)**2 + (x2 - x1)**2)**0.5
if denominator==0:
distance=0
else:
distance=numerator / denominator
return distance def douglas_peucker(traj, epsilon: float):
""" 使用道格拉斯-普克算法划分并简化轨迹
Args:
traj (List[Point]): 轨迹列表
epsilon (float): 控制分割的阈值
Returns:
segmented_trajectories: 每个分割段的原始轨迹列表
simplified_trajectories: 每个分割段的简化轨迹列表
"""
if len(traj) < 3:
return [traj], [traj]
dmax = 0
index = 0
end = len(traj) - 1
for i in range(1, end):
d = point_to_line_distance(traj[i], traj[0], traj[end])
if d > dmax:
index = i
dmax = d
if dmax > epsilon:
part1, simplified_part1 = douglas_peucker(traj[:index + 1], epsilon)
part2, simplified_part2 = douglas_peucker(traj[index:], epsilon)
return part1 + part2, simplified_part1 + simplified_part2
else:
simplified_traj = [traj[0], traj[end]]
return [traj], [simplified_traj]
|