Flask OpenCV Send and Receive Images in Bytes Flask OpenCV Send and Receive Images in Bytes flask flask

Flask OpenCV Send and Receive Images in Bytes


The following has worked for me. I don't have the client code but I have a curl request. That should do the trick,

SERVER

from flask import requestfrom PIL import Imageimport io@app.route("/add_face", methods=["POST"])def predict():    image = request.files["image"]    image_bytes = Image.open(io.BytesIO(image.read()))

CLIENT SIDE

curl -X POST -F image=@PATH/TO/FILE 'http://localhost:5000/add_face'


It is easier to send images in base64 format, by doing that you get rid of problems about sending/receiving binary data since you just work with a string. Also it is more convenient in web stuff. Tested code below:Server side:

from flask import Flask, render_template, requestimport pandas as pdimport cv2import numpy as npimport base64app = Flask(__name__)@app.route('/add_face', methods=['GET', 'POST'])def add_face():    if request.method == 'POST':        #  read encoded image        imageString = base64.b64decode(request.form['img'])        #  convert binary data to numpy array        nparr = np.fromstring(imageString, np.uint8)        #  let opencv decode image to correct format        img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR);        cv2.imshow("frame", img)        cv2.waitKey(0)    return "list of names & faces"if __name__ == '__main__':    app.run(debug=True, port=5000)

Client side:

import requestsimport base64URL = "http://localhost:5000/add_face"#  first, encode our image with base64with open("block.png", "rb") as imageFile:    img = base64.b64encode(imageFile.read())response = requests.post(URL, data={"name":"obama", "img":str(img)})print(response.content)

You can use COLOR instead of ANYCOLOR if you are sure about your input images.