索引错误:索引 3 超出尺寸为 3 的轴 0 的范围

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

这是我绘制贝塞尔曲线的代码:

def bezier(a):
    n = np.shape(a)[0]-1
        # initialise arrays
    B = np.zeros([101, 2])
    terms = np.zeros([n+1, 2])
        # create an array of values for t from 0 to 1 in 101 steps
    t = np.linspace(0, 1, 101)
        # loop through all t values
    for i in range(0, 101):
            #calculate terms inside sum in equation 13
            for j in range(0, n + 1):
                # YOUR CODE HERE
                terms[j,:] = ((1 - t[i]) ** 3 * a[0,:] \
                           + 3 * t[i] * (1-t[i]) ** 2 * a[1,:] \
                           + 3 * t[i] ** 2 * (1-t[i]) * a[2,:] 
                           + t[i] ** 3 * a[3,:])
        #sum terms to find Bezier curve
    B[i, :] = sum(terms, 0)
        # plot Bezier
    pl.plot(B[:, 0], B[:, 1])
        # plot control points
    pl.plot(a[:, 0], a[:, 1],'ko')
        # plot control polygon
    pl.plot(a[:, 0], a[:, 1],'k')
    return B 

当我尝试通过一些控制点时:

a = np.array([[0, 0], [0.5, 1], [1, 0]])
B = bezier(a)

我收到此索引错误:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-16-fce87c9f1c04> in <module>()
      1 a = np.array([[0, 0], [0.5, 1], [1, 0]])
----> 2 B = bezier(a)

<ipython-input-13-3bb3bb02cc87> in bezier(a)
     11            for j in range(0, n + 1):
     12                # YOUR CODE HERE
---> 13                terms[j,:] = ((1 - t[i]) ** 3 * a[0,:] + 3 * t[i] * (1-t[i]) ** 2 * a[1,:] + 3 * t[i] ** 2 * (1-t[i]) * a[2,:] + t[i] ** 3 * a[3,:])
     14        #sum terms to find Bezier curve
     15    B[i, :] = sum(terms, 0)

IndexError: index 3 is out of bounds for axis 0 with size 3

所以我认为它正在尝试访问容器外部的某些内容,但我看不到它在哪里,我需要更改代码。

python list indexoutofboundsexception
1个回答
0
投票

您的数组

a = np.array([[0, 0], [0.5, 1], [1, 0]]
没有索引为3的元素。向数组添加另一个点。无论如何,贝塞尔曲线需要四个点。

© www.soinside.com 2019 - 2024. All rights reserved.