0

I'm writing an API with Flask that takes a file as input, manipulates it with OpenCV, and then I want to return the file. Ideally I'd be able to return the file along with some meta data (the time it took the operation to complete).

The line that produces the image I want to return is:

image = cv2.rectangle(image, start_point, end_point, color, thickness)

Ideally I could return this straight from memory (without ever writing a temporary file)

Is this even possible?

Mike Coleman
  • 675
  • 5
  • 12

2 Answers2

3

Yes, this can be done

from flask import Flask, render_template , request , jsonify
from PIL import Image
import os , io , sys
import numpy as np 
import cv2
import base64

app = Flask(__name__)

start_point = (0, 0) 
end_point = (110, 110) 
color = (255, 0, 0)
thickness = 2

@app.route('/image' , methods=['POST'])
def mask_image():
    file = request.files['image'].read()
    npimg = np.fromstring(file, np.uint8)
    img = cv2.imdecode(npimg,cv2.IMREAD_COLOR)
    img = cv2.rectangle(img, start_point, end_point, color, thickness)
    img = Image.fromarray(img.astype("uint8"))
    rawBytes = io.BytesIO()
    img.save(rawBytes, "png")
    rawBytes.seek(0)
    img_base64 = base64.b64encode(rawBytes.read())
    return jsonify({'status':str(img_base64)})


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

Here, you return the base64 encoded image with the rectangle drawn on the image. You can see red rectangle added in the below image

enter image description here

bigbounty
  • 16,526
  • 5
  • 37
  • 65
1

Ideally I could return this straight from memory (without ever writing a temporary file)

Yes, that's possible. I suggest using Streaming with Context. Sample code to try below.

from flask import stream_with_context, Response

@app.route('/stream_image')
def stream_response():
    def generate():
        for i in range(100): # return in small chunks
            yield image(i)

    return Response(stream_with_context(generate()))

Otherwise, for static files, use the send_from_directory function. Well described examples you can find here on Sending files with Flask.

Mrinal Roy
  • 969
  • 7
  • 12