This time, I will make a note of one of the ways to receive images in the python framework flask. Specifically, it receives the image in a base64-encoded format, decodes it on the flask side, and restores the image. Then, use open-cv to convert the restored image to grayscale, encode it to base64 again, and make a note of it.
The library to be used is as follows.
requirements.txt
flask
flask-cors
opencv-python
opencv-contrib-python
I want to handle multiple data in the request, so I will use json format.
[
{
id : 0
Image : id4zFjyrkAuSI2vUBKVLP...(Base64 encoded image)
},
{
id : 1
Image : k75GN/oll7KUCulSpSM/S...(Base64 encoded image)
}
]
main.py
from flask import Flask, jsonify, request
from flask_cors import CORS
import cv2
import numpy as np
import base64
app = Flask('flask-tesseract-api')
CORS(app)
@app.route("/image/", methods=["POST"])
def post():
"""
Convert image to grayscale
"""
response = []
for json in request.json:
#Decode Image
img_stream = base64.b64decode(json['Image'])
#Convert to an array
img_array = np.asarray(bytearray(img_stream), dtype=np.uint8)
# open-Grayscale with cv
img_gray = cv2.imdecode(img_array, 0)
#Save conversion result
cv2.imwrite('result.png', img_before)
#Encode for saved file
with open('result.png', "rb") as f:
img_base64 = base64.b64encode(f.read()).decode('utf-8')
#Boxed in response json
response.append({'id':json['id'], 'result' : img_base64})
return jsonify(response)
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000,debug=True)
I was able to send multiple images encoded to flask as json format. With this, you can implement the function to handle multiple images at the same time.
Recommended Posts