如何用opencv图像在Flask中渲染模板而不将文件写入磁盘?

时间:2019-04-02 15:48:45

标签: python-3.x flask

我尝试渲染烧瓶模板,而不将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>

1 个答案:

答案 0 :(得分:0)

您可以对缓冲区进行base64编码,它虽然不漂亮,但是应该可以工作。

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

然后您的模板看起来像

{{1}}

尝试一下。