Matplotlib set_data 使我的程序冻结(请检查“更新问题”)

Ped*_*ram 0 python opencv matplotlib python-multithreading

我试图绘制两个更新图,一个是图表,另一个是从相机捕获的图像。

我在这一行收到一个错误:

"current_line.set_data(y_data)" in the "update" function.  
The error says: "AttributeError: 'list' object has no attribute 'set_data'".
Run Code Online (Sandbox Code Playgroud)

知道为什么我会收到此错误吗?如果我注释掉这一行,我将从相机中获取不断变化的图像,除第二个图外的所有内容看起来都很好(因为第二个图未更新)但我也需要更新第二个图。

y_data = [0]
# Capture intial frame
ret, initial_frame = lsd.cap.read()

# Function for making the initial figure
def makeFigure():
    fig = plt.figure()

    # Show frame
    ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
    plot_frame = ax1.imshow(initial_frame, animated=True)

    # Set the limits of the plot and plot the graph
    ax2 = plt.subplot2grid((2, 2), (1, 0), colspan=2)
    ax2.set_title('Title')
    ax2.set_ylabel('Y-Label')
    ax2.set_ylim(0, 100)
    ax2.set_xlim(0, 100)
    ax2.grid()
    line = ax2.plot(y_data, 'o-')

    return fig, plot_frame, line

def update(i, current_frame, current_line, y_data):
    # Capture original frame_new_RGB from camera
    ret, frame_new_original = lsd.cap.read()

    # Changing frame_new_original's color order
    frame_new_RGB = cv2.cvtColor(frame_new_original, cv2.COLOR_BGRA2RGB)

    y_data.append(randint(0, 9))

    # Update figure
    current_line.set_data(y_data)

    # Update frame
    current_frame.set_data(frame_new_RGB)


# Make figures and animate the figures
curr_fig, curr_frame, curr_line = makeFigure()
anim = FuncAnimation(curr_fig, update, fargs=[curr_frame, curr_line, y_data], interval=10)

plt.show()

# When everything done, release the capture
lsd.cap.release()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

更新的问题:

第一个问题解决了,但现在我面临另一个问题。我的程序在运行后冻结并且没有产生任何错误。还有另一件事可能与这个问题有关,我是多线程的,这段代码在主线程中。

tmd*_*son 5

ax.plot返回一个Line2D实例列表(在您的情况下,它是一个 1 项列表)。这是因为可以一次绘制多条线ax.plot

因此,在您的情况下,您只需要获取列表的第一项。最简单的方法可能是改变这一行:

line = ax2.plot(y_data, 'o-')
Run Code Online (Sandbox Code Playgroud)

对此:

line, = ax2.plot(y_data, 'o-')
Run Code Online (Sandbox Code Playgroud)

请注意,虽然您的问题是关于设置data行的,而不是添加 a legend,但此问答在这里是相关的,因为解决方案是相同的:Python legend attribute error