Domanda

So I am trying to program a bezier curve using python, and unlike previously posts I have been able to find, I need to program It in such a way, that the summation adjust for how many splines there is, since I need to be able to remove or add splines.

I am basing my programming on this wiki http://en.wikipedia.org/wiki/B%C3%A9zier_curve right after the headline "Explicit definition" so far this is what I have made

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))

my problem right now is that I need to do a summation of the x and y coordinates, so they become something like this

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

and the same for x

any pointers?

È stato utile?

Soluzione

I think you can use 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]

Edit:

Using your example coordinates I get the following outputs:

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

bezier

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

bezier_cumsum

Assuming this is what you are looking for!

Altri suggerimenti

I'm not very clear on what're you trying to accomplish, but it's probably something like this:

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

Demo:

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


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

Or, the shortcut using list comprehension:

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

Well, hope it helps!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top