Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying opencv image using python flask

I'm doing some processing on an image using opencv and using the python flask api. I'd like to display the image in the browser.

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)

However, I'm getting empty, invalid image as output. What am I doing wrong?

like image 784
Abhishek Thakur Avatar asked Mar 14 '17 13:03

Abhishek Thakur


People also ask

How do you show an image in a flask?

When we want to store an image in our web application made from flask, we can store the image in the folder we allocated for flask app, containing the app.py, scripts. The folder i allocated is look, and within look folder, i made a sub folder called static. Inside static folder, store the image.

Can I use OpenCV in flask?

You can use the 'pip install flask' and 'pip install opencv-python' command. I use the PyCharm IDE to develop flask applications. To easily install libraries in PyCharm follow these steps.


1 Answers

As mentioned in the comments, you need to return the bytes of an image, not a base64 string.

Try the following:

retval, buffer = cv2.imencode('.png', output_img)
response = make_response(buffer.tobytes())
like image 153
Alexey Grigorev Avatar answered Oct 04 '22 20:10

Alexey Grigorev