Domanda

I wrote an implementation of the De Casteljau algorithm to create a Bezier curve. My problem is the function ignores the second control point, it does calculate some kind of curve, but it is not correct.

def DeCasteljau(CNTRL_P, t):
    ReP = points.point()
    Ret = points.point()

    n = len(CNTRL_P)
    k = 0
    tmp = 0

    while k < n:
        tmp = (((1 - t)**((n-1) - k))  *  (t**k))
        ReP.addP(CNTRL_P[k])
        #ReP.Prnt()
        ReP.mulP(tmp)   
        Ret.addP(ReP)
        ReP.Clr() #ReP => (0,0)
        tmp = 0
        k = k + 1

    return Ret

For example: CNTRL_P = [P0, P1, P2] It ignores P1

class point():
    def __init__(self, X = 0, Y = 0):
        self.x = X
        self.y = Y

    def addP(self, P1):
        self.x = self.x + (P1.getX()) 
        self.y = self.y + (P1.getY())

    def subP(self, C = 0, D = 0):
        self.x = self.x - C
        self.y = self.y - D

    def mulP(self, C):
        self.x = self.x * C
        self.y = self.y * C

    def getX(self):
        a = self.x
        return a

    def getY(self):
        a = self.y
        return a

    def Prnt(self):
        print "X:", self.x,"Y:", self.y

    def Clr(self):
        self.x = 0
        self.y = 0
È stato utile?

Soluzione

Implementation looks faulty. Where's the recursion?

Does this give you better results?

def DeCasteljau2(CNTRL_P, t):

    tmp_points = CNTRL_P[:]

    while len(tmp_points) > 1:

        for k in range(len(tmp_points)-1):
            ReP = point()
            ReP2 = point()

            ReP.addP(tmp_points[k])
            ReP2.addP(tmp_points[k+1])

            ReP.mulP((1-t))
            ReP2.mulP(t)

            ReP.addP(ReP2)
            tmp_points[k] = ReP

        tmp_points.pop()

    return tmp_points[0]

This is the result after each iteration:

P0 | P1 | P2

P0 * (1-t) + P1 * t | P1 * (1-t) + P2

(P0 * (1-t) + P1 * t)*(1-t) + (P1 * (1-t) + P2)*t

You repeat the algorithm until you only have 1 point left. Each point P(n) in the next solution is the result of P(n) * (1-t) + p(n+1) * t from the last solution. At each iteration the last point is discarded since there is no next point that you could multiply and add with.

Wikipedia probably can explain that better than me: link

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