1

因此,我正在尝试使用 python 编写贝塞尔曲线,与以前我能够找到的帖子不同,我需要以这样一种方式对其进行编程,即总和会根据有多少样条线进行调整,因为我需要能够删除或添加样条线。

我的编程基于这个 wiki http://en.wikipedia.org/wiki/B%C3%A9zier_curve,就在标题“显式定义”之后,到目前为止,这就是我所做的

from __future__ import division
import math
import numpy as np
from pylab import*


fact = math.factorial
def binormal(n,i):
    koef = fact(n)/float((fact(i)*fact(n-i)))
    return koef


def bernstein(n,i,t):
    bern = binormal(n,i)*(1-t)**(n-i)*(t**i)
    return bern

f = open('polaerekoordinator.txt','r')
whole_thing = f.read().splitlines()
f.close() #these are the coordinates I'm am trying to use for now
#0.000 49.3719597
#9.0141211 49.6065178
#20.2151089 50.9161568
#32.8510895 51.3330612
#44.5151596 45.5941772
#50.7609444 35.3062477
#51.4409332 23.4890251 
#49.9188042 11.8336229
#49.5664711 0.000

alle = []

for entry in whole_thing:
    alle.append(entry.split(" "))

def bezier(t): #where t is how many points there is on the bezier curve
    n = len(alle)
    x = y = 0
    for i,entry in enumerate(alle):
        x +=float(entry[0])*bernstein(n,i,t)+x
    for i,entry in enumerate(alle):
        y +=float(entry[1])*bernstein(n,i,t)+y
    return x,y

bezier(np.arange(0,1,0.01))

我现在的问题是我需要对 x 和 y 坐标求和,所以它们变成了这样

y = [y0, y0+y1, y0+y1+y2, y0+y1+y2+...+yn]

和 x 一样

任何指针?

4

2 回答 2

1

我认为您可以使用 np.cumsum http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html

>>>y = np.arange(0,1,0.1)
>>>[ 0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9]
>>>y_cum = np.cumsum(y)
>>>[ 0.   0.1  0.3  0.6  1.   1.5  2.1  2.8  3.6  4.5]

编辑:

使用您的示例坐标,我得到以下输出:

x,y = bezier(np.arange(0,1,0.01))
plot(x,y)

贝塞尔曲线

 plot(np.cumsum(x),np.cumsum(y))

bezier_cumsum

假设这就是你要找的!

于 2013-11-08T12:09:51.903 回答
0

我不太清楚您要完成什么,但可能是这样的:

for i, v in enumerate(y):
    y2.append(sum(y[:i+1]))

演示:

>>> y = [1, 2, 3]
>>> y2 = []
>>> for i, v in enumerate(y):
    y2.append(sum(y[:i+1]))


>>> y2
[1, 3, 6]
>>> 

或者,使用列表推导的快捷方式:

y2 = [sum(y[:i+1]) for i,_ in enumerate(y)]

嗯,希望对你有帮助!

于 2013-11-08T12:33:19.043 回答