You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

直线路线检测、修正与优化:技术问题及代码纠错问询

道路坐标点修正问题

现有一条道路,整体以直线为主,仅包含少量90°转弯。将该道路转换为坐标系后,得到如下坐标点:

point 1 0.00 1.41
point 2 0.71 2.12
point 3 1.41 2.83
point 4 -1.41 5.66
point 5 -0.71 6.36
point 6 0.00 7.07
point 7 2.83 4.24
point 8 4.24 5.66
point 9 4.95 6.36
point 10 5.66 5.66
point 11 6.36 6.36
point 12 7.07 7.07
point 13 6.36 7.78
point 14 7.07 8.49
point 15 7.78 9.19
point 16 8.49 9.90
point 17 9.19 10.61
point 18 7.78 12.02
point 19 9.19 13.44
point 20 11.31 11.31
point 21 12.02 12.02
point 22 11.31 12.73
point 23 12.02 13.44

问题描述

  • 问题1:编写Python代码,检测偏离直线路线的点,并自动修正这些点以得到直线路线(假设始终存在可行的直线路线)。
  • 问题2:存在从point1到point14的直线路线,但按照上述给定的道路行驶会包含不必要的转弯,需确定哪些点需要修正才能获得该直线路线。

尝试的实现方案

问题1的实现代码

import numpy as np

# 计算两点间距离
def distance(point1, point2):
    x1, y1 = point1
    x2, y2 = point2
    return np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

# 判断三点是否共线
def are_collinear(p1, p2, p3):
    return abs(distance(p1, p2) + distance(p2, p3) - distance(p1, p3)) != 0

# 遍历点找出偏离直线路径的点
straight_route = [points[1]]
out_of_straight_points = []

for i in range(3, len(points) + 1):
    current_point = points[i]
    if not are_collinear(straight_route[-1], points[i - 1], current_point):
        out_of_straight_points.append(i)
    else:
        straight_route.append(current_point)

# 输出偏离直线的点
print("Points out of the straight route:", out_of_straight_points)

# 输出修正后的直线路径
print("Corrected Straight Route:")
for i, point in enumerate(straight_route):
    print(f"point {i + 1}: {point[0]:.2f} {point[1]:.2f}")

运行结果:

Points out of the straight route: [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Corrected Straight Route:
point 1: 0.00 1.41
point 2: 1.41 2.83
point 3: -0.71 6.36
point 4: 2.83 4.24
point 5: 4.95 6.36
point 6: 6.36 6.36
point 7: 6.36 7.78
point 8: 7.78 9.19
point 9: 9.19 10.61
point 10: 9.19 13.44
point 11: 12.02 12.02
point 12: 12.02 13.44

问题2的实现代码

def calculate_slope(point1, point2):
    x1, y1 = point1
    x2, y2 = point2
    if x2 - x1 == 0:
        return float('inf')  # 竖直线,斜率无穷大
    return round((y2 - y1) / (x2 - x1), 1)
# 定义point1和point14的索引
point1_index = 0
point14_index = 13

# 计算point1到point14的预期斜率
expected_slope = calculate_slope(points[point1_index], points[point14_index])
print("expected slope = ", expected_slope)

# 找出需要修正的点
points_to_correct = []

for i in range(point1_index, point14_index):
    actual_slope = calculate_slope(points[i], points[i + 1])
    print(actual_slope)
    if expected_slope != actual_slope:
        points_to_correct.append(i + 1)

print(f"Points to correct for a straight route: {points_to_correct}")

运行结果:

expected slope =  1.0
1.0
1.0
-1.0
1.0
1.0
-1.0
1.0
1.0
-1.0
1.0
1.0
-1.0
1.0
Points to correct for a straight route: [3, 6, 9, 12]

上述两种方案均存在错误,因为空间中存在多个斜率相同但并不共线的点。

内容的提问来源于stack exchange,提问作者Shahad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:32:05