【问题标题】:How do you make line segments between two points and find out how many points intersect the line?您如何在两点之间制作线段并找出与线相交的点数?
【发布时间】:2011-07-26 19:10:03
【问题描述】:

我的代码可以生成点之间所有可能的线:

import matplotlib.pyplot as plt
import matplotlib.lines as lines
import itertools 

fig=plt.figure()
ax=fig.add_subplot(111)
all_data = [[1,10],[2,10],[3,10],[4,10],[5,10],[3,1],[3,2],[3,3],[3,4],[3,5]]
x, y = zip(*all_data)
plt.scatter(x,y)
for pair in itertools.combinations(all_data,2):
    line=lines.Line2D(*zip(*pair))
    line.set_color('brown')
    ax.add_line(line)

plt.show()

但我想要每条线相交的点数。 (点为蓝色)

【问题讨论】:

  • 您是否想获得两条最合适的线条?尝试 RANSAC(即选择两个随机点,通过它们获得线,丢弃与线距离超过 1.0 的所有点,进行回归拟合。)

标签: python


【解决方案1】:

可能是这样的(未经测试):

def crossf(p1, p2):
  u"returns a boolean function for testing line (p1, p2)"
  if p1[0] == p2[0]:
    y = [p1[1], p2[1]]
    y.sort()
    # if p3 falls within the y range it is on the line
    return lambda p3: (p3[1] >= y[0]) and (p3[1] <= y[1])
  else:
    slope = p2[1] - p1[1], p2[0] - p1[0]
    # y/x ratio of point (p3 - p1) must equal slope
    return lambda p3: (p3[0] - p1[0]) * slope[1] == (p3[1] - p1[1]) * slope[0]

crosstests = dict([(pair, crossf(*pair) for pair in itertools.combinations(all_data,2)])

for pair in crosstests:
  for point in all_data:
    print 'point %s does %sfall on line %s' % (point, 
        '' if crosstests[pair](point) else 'not ', pair)

【讨论】:

    【解决方案2】:

    使用此距离度量。 http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html 它在结尾处有一个很好的矢量表达。置换所有点-线组合,如果 d 小于 epsilon,则有一个交集。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2020-12-17
      • 2020-03-25
      • 2022-11-30
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多