11

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?

0

1 Answer 1

12

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())
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this and added "output_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)", the make_response statement crashes; not sure how to debug this (in VS Code)
fixed it, "from flask import make_response" was needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.