旋转点集后,寻找5个最共线点的算法返回错误结果
寻找点集中最接近共线的5个点
我有一个包含15个不同x、y坐标点的点集,想找出其中5个最接近共线的点(无需完全共线,只要是所有5点组合中最接近共线的)。
当前实现步骤
- 使用
itertools.combinations生成所有可能的5点组合 - 遍历每一组5点组合
- 计算第一个点到其他点的斜率
- 计算第一个斜率与其他斜率的绝对差
- 求和所有差值
- 比较所有组合的差值和,返回和最小的组合
该算法存在问题:在points_0deg点集上工作正常,但将同一点集旋转80度得到points_80deg后,算法会错误地识别红点为最共线点,而非绿点。
相关代码
import itertools points_0deg = [[818.5, 395.5], [688.5, 586.5], [556.5, 448.5], [819.5, 779.5], [657.5, 892.5], [558.5, 727.5], [658.5, 278.5], [453.5, 279.5], [426.5, 588.5], [877.5, 589.5], [458.5, 893.5], [301.5, 403.5], [296.5, 774.5], [241.5, 583.5], [558.5, 585.5]] points_80deg = [[498.5, 397.5], [665.5, 558.5], [505.5, 665.5], [356.5, 533.5], [781.5, 711.5], [876.5, 463.5], [958.5, 641.5], [619.5, 816.5], [700.5, 373.5], [925.5, 838.5], [414.5, 906.5], [322.5, 737.5], [580.5, 998.5], [776.5, 975.5], [640.5, 687.5]] def check_collinear(points): x1, y1 = points[0] slope = [] for point in points[1:]: x, y = point slope.append((y - y1) / (x - x1) if (x - x1) != 0 else float('inf')) diff = [] for val in slope[1:]: diff.append(abs(slope[0] - val)) return sum(diff) def find_most_collinear(points): combinations = list(itertools.combinations(points, 5)) collinear_points = None min_sum = float('inf') for comb in combinations: s = check_collinear(comb) if s <= min_sum: min_sum = s collinear_points = comb return collinear_points if __name__ == '__main__': print(find_most_collinear(points_0deg)) print(find_most_collinear(points_80deg))
内容的提问来源于stack exchange,提问作者user3662357
相关产品推荐
相关产品推荐

