使用python flask显示opencv图像

时间:2017-03-14 13:55:12

标签: python opencv flask

我正在使用opencv和使用python flask api对图像进行一些处理。我想在浏览器中显示图像。

import cv2
from flask import Flask, request, make_response
import base64
import numpy as np
import urllib

app = Flask(__name__)


@app.route('/endpoint', methods=['GET'])
def process():
    image_url = request.args.get('imageurl')
    requested_url = urllib.urlopen(image_url)
    image_array = np.asarray(bytearray(requested_url.read()), dtype=np.uint8)
    img = cv2.imdecode(image_array, -1)


    # Do some processing, get output_img

    retval, buffer = cv2.imencode('.png', output_img)
    png_as_text = base64.b64encode(buffer)
    response = make_response(png_as_text)
    response.headers['Content-Type'] = 'image/png'
    return response

if __name__ == '__main__':
    app.run(debug=True)

然而,我得到空的,无效的图像作为输出。我做错了什么?

1 个答案:

答案 0 :(得分:4)

如评论中所述,您需要返回图像的字节,而不是base64字符串。

尝试以下方法:

retval, buffer = cv2.imencode('.png', output_img)
response = make_response(buffer.tobytes())