如何在 Flask 中使用 opencv 图像渲染模板,而无需将文件写入磁盘



>我尝试在不将opencv图像写入磁盘的情况下渲染烧瓶模板。也许有人知道如何实现这一点。

@app.route('/upload')
def upload_file():
   return render_template('upload.html')
@app.route('/uploader', methods = ['GET', 'POST'])
def uploaded_file():
    if request.method == 'POST':
    photo = request.files['file']
    in_memory_file = io.BytesIO()
    photo.save(in_memory_file)
    data = np.fromstring(in_memory_file.getvalue(), dtype=np.uint8)
    color_image_flag = 1
    img = cv2.imdecode(data, color_image_flag)
    frame,res=recogn(img)
    imencoded = cv2.imencode(".jpg", frame)[1]
    ###If i put there next line it will work(i can render template
    ###photo=file), but i don't want write image
    ###to disk
    ###cv2.imwrite('file.jpg',frame)
    return render_template('from_file.html', photo=imencoded)
    Template look like this 
    <h3><img src="{{ photo }}" width="50%"></h3>

你可以对缓冲区进行base64编码,它并不漂亮,但它应该可以工作。

import base64
@app.route('/uploader', methods = ['GET', 'POST'])
def uploaded_file():
    if request.method == 'POST':
    photo = request.files['file']
    in_memory_file = io.BytesIO()
    photo.save(in_memory_file)
    data = np.fromstring(in_memory_file.getvalue(), dtype=np.uint8)
    color_image_flag = 1
    img = cv2.imdecode(data, color_image_flag)
    frame,res=recogn(img)
    imencoded = cv2.imencode(".jpg", frame)[1]
    jpg_as_text = base64.b64encode(imencoded)
    return render_template('from_file.html', photo=jpg_as_text)

然后你的模板看起来像

<h3><img src="data:image/jpeg;charset=utf-8;base64, {{photo}}" width="50%"></h3>

试一试。

最新更新