from flask import Flask, request
from werkzeug.utils import secure_filename
import cv2
import easyocr
import os
# Initializing flask app
app = Flask(__name__)
@app.route('/data')
def index():
return ("
Hi, I am running fine as backend. Please use the frontend to perform text extraction.
")
# Route for seeing a data
@app.route('/data', methods=['POST'])
def get_time():
file = request.files['file']
file.save(secure_filename(file.filename))
#except:
# return["Sorry something went wrong. Perhaps you did not select your image. Please try again."]
rois = request.form['rois'].split(',')
div = request.form['divisionWH'].split(',')
print(rois, "\n", div)
img = cv2.imread(secure_filename(file.filename))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# specify languages and other configs
reader = easyocr.Reader(['en'], gpu=False)
IacH, IacW = img.shape
IapW, IapH = int(div[0]), int(div[1])
Rw = IacW / IapW
Rh = IacH / IapH
# print(Rw,Rh)
output = ""
if len(rois) > 1:
for i in range(int(len(rois) / 4)):
j = i * 4
global X1, X2, Y1, Y2
x1, y1, x2, y2 = int(rois[j]), int(rois[j + 1]), int(rois[j + 2]), int(rois[j + 3])
X1, Y1, X2, Y2 = int(Rw * x1), Rh * y1, int(Rw * x2), Rh * y2
Offset_y1 = ((IacH * y1 / 100) * 0.02) / 100
Offset_y2 = ((IacH * y2 / 100) * 0.05) / 100
print(Offset_y1)
Y1 = int(Y1)
Y2 = int(Y2 + Offset_y2)
img_ROI = img[Y1:Y2, X1:X2]
result = reader.readtext(img_ROI, paragraph='True')
for res in result:
top_left = tuple(res[0][0]) # top left coordinates as tuple
bottom_right = tuple(res[0][2]) # bottom right coordinates as tuple
# draw rectangle on image
cv2.rectangle(img_ROI, top_left, bottom_right, (0, 255, 0), 2)
# write recognized text on image (top_left) minus 10 pixel on y
cv2.putText(img_ROI, res[1], (top_left[0], top_left[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(255, 0, 0, 1))
output = output + res[1] + '\n\n'
print(output)
cv2.rectangle(img_ROI, (X1, Y1), (X2, Y2), (255, 0, 255), 2)
else:
result = reader.readtext(img, paragraph='True')
print(result, "Result")
# iterate on all results
for res in result:
top_left = tuple(res[0][0]) # top left coordinates as tuple
bottom_right = tuple(res[0][2]) # bottom right coordinates as tuple
# draw rectangle on image
top_left = (int(top_left[0]), int(top_left[1]))
bottom_right = (int(bottom_right[0]), int(bottom_right[1]))
cv2.rectangle(img, top_left, bottom_right, (0, 255, 0), 2)
# write recognized text on image (top_left) minus 10 pixel on y
# cv2.putText(img, res[1], (top_left[0], top_left[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
output = output + res[1]
print('ok')
os.remove(secure_filename(file.filename))
return [output]
if __name__ == "__main__":
app.run(debug=True,host="0.0.0.0",port=5000)