如何将图像直接从烧瓶服务器发送到 html?

Sha*_*nde 6 javascript python flask

我是flask的新手,正在尝试制作一个应用程序,这样的图像由html和js从网络摄像头拍摄,然后通过ajax请求发送到服务器。我得到了这部分。然后对图像进行一些处理,并将其发送回前端。我知道如何在烧瓶中正常发送数据,如

@app.route('/')
def function():
    return render_template("index.html", data = data)
Run Code Online (Sandbox Code Playgroud)

但是在python中图像是numpy数组的形式,js无法读取numpy数组并将其转换为图像(至少我不知道有什么方法可以做到这一点)。那么有什么方法可以做到呢?

fur*_*ras 10

这显示了如何将numpy数组转换为PIL.Image然后使用它io.BytesIO在内存中创建文件 PNG。

然后您可以使用send_file()将 PNG 发送到客户端。

from flask import Flask, send_file
from PIL import Image
import numpy as np
import io

app = Flask(__name__)

raw_data = [
    [[255,255,255],[0,0,0],[255,255,255]],
    [[0,0,1],[255,255,255],[0,0,0]],
    [[255,255,255],[0,0,0],[255,255,255]],
]

@app.route('/image.png')
def image():
    # my numpy array 
    arr = np.array(raw_data)

    # convert numpy array to PIL Image
    img = Image.fromarray(arr.astype('uint8'))

    # create file-object in memory
    file_object = io.BytesIO()

    # write PNG in file-object
    img.save(file_object, 'PNG')

    # move to beginning of file so `send_file()` it will read from start    
    file_object.seek(0)

    return send_file(file_object, mimetype='image/PNG')


app.run()
Run Code Online (Sandbox Code Playgroud)

与您可以将其作为 GIF 或 JPG 发送的方式相同。