[英]How do you make line segments between two points and find out how many points intersect the line?
我有生成点之间所有可能线的代码:
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()
但我想每条线相交多少点。 (点是蓝色的)
也许是这样的(未经测试):
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)
使用此距离度量。 http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html它在结尾处具有漂亮的向量表达式。 置换所有点线组合,如果d小于epsilon,则有一个交点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.