首页 > 解决方案 > 如何将动画视频文件(由 matplotlib 创建)传递给 Flask 中的模板文件

问题描述

我正在尝试显示matplotlib.animation模板 html 文件中生成的动画视频文件。在下面的代码后,我收到:flask.cli.NoAppException: While importing "plot", an ImportError was raised:

这是代码:

from flask import Flask, request, render_template, send_file

import matplotlib.pyplot as plt
from matplotlib import animation
import io
import base64
import numpy as np
import pandas as pd
import seaborn as sns
from StringIO import StringIO
@app.route('/anim')
def build_animated():
    *****
    # Movement instance creation-----------------------------
    movement1=Movement(train1, track1)
    # Move the train on the track
    movement1.move()
    y = movement1.speed
    x = movement1.pos


    Writer = animation.writers['ffmpeg']
    writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)

    fig = plt.figure()
    ax = plt.axes(xlim=(0, 35), ylim=(0, 350))
    line, = ax.plot([], [], lw=2)
    # initialization function: plot the background of each frame
    def init():
        line.set_data([], [])
        return line,

    # animation function.  This is called sequentially
    def animate(i):
        # y = movement1.speed
        # x = movement1.pos
        line.set_data(x[:i*25000], y[:i*25000])
        return line,

    anim = animation.FuncAnimation(fig, animate, init_func=init,
                                    frames=20, interval=36, blit=True)
    anim.save('basic_animation.mp4', writer=writer)
    img = StringIO()
    fig.savefig(img)
    img.seek(0)
    return send_file(img, mimetype='image/png')

我希望视频文件显示在模板文件夹中的 html 文件中

标签: pythonmatplotlibflask

解决方案


推荐阅读