找到位于两点之间的直线上的点,以精确的线段,python

问题描述 投票:0回答:3

我有 2 个点,(x0,y0) (x1,y1),它们形成一条线 L。我找到了斜率 M。 现在我想在L上的这2个点之间找到3个点,即它们之间的距离精确,意味着所有点之间的距离相同。 如果我用“-”字符测量距离,它可能是这样的: p1---p2---p3---p4---p5 其中 p1 和 p5 是我的起点。

首先我想到通过这样做来找到坡度:

def findSlope(p1, p2):
if (p1[0] - p2[0] != 0):
    return (p1[1] - p2[1])/p1[0] - p2[0]
else:
    return 0

这很容易,但获得实际分数对我来说并不容易。 我想过做这样的事情:

def findThreePoints(p1,p2):

    slope = findSlope(p1,p2)
    c = p1[1] - slope*p1[0]
    x1 = (p1[0] + p2[0])/4
    x2 = (p1[0] + p2[0])/2
    x3 = (3*(p1[0] + p2[0]))/4
    y1 = slope*x1 + c
    y2 = slope*x2 + c
    y3 = slope*x3 + c

虽然这种方法有效,但它的编码风格/效率不是很好,因为如果我希望函数给出超过 3 分,我将需要它更长。

是否有任何内置方法可以使用 Numpy 执行此操作,或者只是一种更有效的方法来解决此问题,这不会使我的代码看起来像是仅为特定目的而编写的?

python line points
3个回答
7
投票

就这么简单:

import numpy as np

#create the points 
number_of_points=3
xs=np.linspace(x0,x1,number_of_points+2)
ys=np.linspace(y0,y1,number_of_points+2)

#print them
for i in range(len(xs)):
    print (xs[i],ys[i])

它也适用于水平或垂直线


1
投票

如果直线方程为

y = m*x + q

为什么不使用 FOR 循环? 比如:

import numpy
#define n in the code or by input
n = 100
#define the x and y arrays with numpy.array
x = numpy.zeros(n)
y = numpy.zeros(n)    

#define the start, stop values in your code or by input
start = 1
stop = 10

#define the step, depending by n
step = (stop - start)/n #if you want n points

i = 0
for a in numpy.arange (start, stop, step):
 x[i] = a 
 y[i] = m*a + q
 i = i + 1 #there are better ways to do this

当然这对于垂直线不起作用,但是为这些线找到点没有问题(x是常数)


0
投票

这里是一个general

numpy
oneliner,遵循与
line_nd
方法相同的接口
skimage
,但它适用于任何n维点,而不仅仅是2D:

line_nd_np = lambda start, stop, num_points: tuple([np.linspace(start[i], stop[i], num=num_points) for i in range(len(start))])

因此,遵循与

line_nd
相同的接口,
line_nd_np
返回一个元组,其中每个坐标一一对应的 numpy 数组(例如 (xs, ys, zs,...))。

line_nd_np(start=(0,0,0), stop=(1,1,1), num_points=3)

(array([0. , 0.5, 1. ]), array([0. , 0.5, 1. ]), array([0. , 0.5, 1. ]))

如果想要只需要一个数组,其中的点位于开始和结束之间的线上,那么一条线可以变成:

line_points = lambda start, stop, num_points=100: np.vstack([np.linspace(start[i], stop[i], num=num_points) for i in range(len(start))]).T 

然后,可以得到:

line_points(start=(0,0,0), end=(1,1,1), num_points=3)
array([[0. , 0. , 0. ],
       [0.5, 0.5, 0.5],
       [1. , 1. , 1. ]])
© www.soinside.com 2019 - 2024. All rights reserved.