Flask部署OCR
2020-08-06 本文已影响0人
湯木
情形一:图片在服务器上,传输图片在服务器上的地址
Client:
# -*- coding: utf-8 -*-
import requests
import json
from pprint import pprint
def post(image_path):
URL = 'http://127.0.0.1:5000/ocr'
img_path = {'path': image_path}
req = requests.post(URL, data=img_path)
data = req.content.decode('utf-8')
data = json.loads(data)
pprint(data)
if __name__ == '__main__':
img_path = './doc/yan.jpg'
post(img_path)
Server:
from flask import Flask, request
import time
import imghdr
import numpy as np
import os
import cv2
import json
from numpyencoder import NumpyEncoder as NpEncoder
from tools.infer import utility
from tools.infer.predict_system import TextSystem
app = Flask(__name__)
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, time):
return obj.__str__()
else:
return super(NpEncoder, self).default(obj)
# 构建接口返回结果
def build_api_result(dt_boxes, rec_res):
result = {
"boxes": dt_boxes,
"result": rec_res
}
return json.dumps(result, cls=MyEncoder)
def load_model(args):
global text_sys
text_sys = TextSystem(args)
@app.route('/ocr', methods=['POST'])
def ocr():
if request.method == 'POST':
image_path = request.form["path"]
img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'GIF'}
if os.path.isfile(image_path) and imghdr.what(image_path) in img_end:
img = cv2.imread(image_path)
dt_boxes, rec_res = text_sys(img)
return build_api_result(dt_boxes, rec_res)
if __name__ == '__main__':
load_model(utility.parse_args())
app.run()
情形二:图片保存在本地,上传至服务器,并保存到服务器
Client:
# -*- coding: utf-8 -*-
import base64
import os
import requests
import json
from pprint import pprint
def post(image_path, img_type):
URL = 'http://127.0.0.1:5000/ocr' # url地址
# 将图片数据转成base64格式
with open(image_path, 'rb') as f:
img = base64.b64encode(f.read()).decode()
# 获取图片名
img_name = os.path.basename(image_path)
file = {'file': img,
'name': img_name,
'img_type': img_type
}
req = requests.post(URL, data=file)
data = req.content.decode('utf-8')
data = json.loads(data)
pprint(data)
if __name__ == '__main__':
img_path = 'E:\\驾驶证_E.jpg'
img_type = 'drivinglicense'
post(img_path, img_type)
Service:
import base64
import datetime
from flask import Flask, request
import time
import imghdr
import numpy as np
import os
import cv2
import json
from numpyencoder import NumpyEncoder as NpEncoder
from tools.infer import utility
from tools.infer.predict_system import TextSystem
app = Flask(__name__)
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, time):
return obj.__str__()
else:
return super(NpEncoder, self).default(obj)
# 构建接口返回结果
def build_api_result(dt_boxes, rec_res, img_class):
result = {
"boxes": dt_boxes,
"result": rec_res,
"class": img_class
}
return json.dumps(result, cls=MyEncoder)
def load_model(args):
global text_sys
text_sys = TextSystem(args)
def save_img(image_data, image_name):
time_now = datetime.datetime.now()
img_save_path = "./images/" + time_now.strftime("%Y-%m-%d-%H")
if not os.path.exists(img_save_path):
os.makedirs(img_save_path)
cv2.imwrite(os.path.join(img_save_path, image_name), image_data)
def image_decode():
img = base64.b64decode(str(request.form["file"]))
image_data = np.fromstring(img, np.uint8)
image_data = cv2.imdecode(image_data, cv2.IMREAD_COLOR)
return image_data
@app.route('/ocr', methods=['POST'])
def deep_ocr():
if request.method == 'POST':
# 获取图片类型
image_class = request.form["img_type"]
# 获取图片名
image_name = request.form["name"]
# 解析图片数据
image_data = image_decode()
# 保存图片
save_img(image_data, image_name)
# OCR
dt_boxes, rec_res = text_sys(image_data)
return build_api_result(dt_boxes, rec_res, image_class)
if __name__ == '__main__':
load_model(utility.parse_args())
app.run(host='0.0.0.0', debug=False)
模拟postman发送post请求提交文件
Client:
# -*- coding: utf-8 -*-
import requests
import json
from pprint import pprint
def post():
URL = 'http://127.0.0.1:5000/ocr'
files = {'file': open(r"E:\img1.jpg", 'rb')}
req = requests.post(URL, files=files)
data = req.content.decode('utf-8')
data = json.loads(data)
pprint(data)
if __name__ == '__main__':
post()
Service:
from flask import Flask, jsonify, request
from flask_cors import CORS
import re
import time
import os
import cv2
from datetime import datetime
from model_post_type import ocr as OCR
from model_postE_invoice import ocr as ocr_E
from model_postM_invoice import ocr as ocr_M
from apphelper.image import union_rbox
from application.invoice_e import invoice_e
from application.invoice_m import invoice_m
import pytz
port = 5000
allowed_extension = ['jpg', 'png', 'JPG']
# Flask
app = Flask(__name__)
CORS(app, resources=r'/*')
# 构建接口返回结果
def build_api_result(code, message, data, file_name, ocr_identify_time):
result = {
"code": code,
"message": message,
"data": data,
"FileName": file_name,
"ocrIdentifyTime": ocr_identify_time
}
return jsonify(result)
# 检查文件扩展名
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extension
# 增值税发票OCR识别接口
@app.route('/invoice-ocr', methods=['POST'])
def invoice_ocr():
# 校验请求参数
if 'file' not in request.files:
return build_api_result(101, "请求参数错误", {}, {}, {})
# 获取请求参数
file = request.files['file']
invoice_file_name = file.filename
# 检查文件扩展名
if not allowed_file(invoice_file_name):
return build_api_result(102, "失败,文件格式问题", {}, {}, {})
upload_path = "test"
whole_path = os.path.join(upload_path, invoice_file_name)
file.save(whole_path)
# 去章处理方法
def remove_stamp(path, invoice_file_name):
img = cv2.imread(path, cv2.IMREAD_COLOR)
B_channel, G_channel, R_channel = cv2.split(img) # 注意cv2.split()返回通道顺序
_, RedThresh = cv2.threshold(R_channel, 170, 355, cv2.THRESH_BINARY)
cv2.imwrite('./test/RedThresh_{}.jpg'.format(invoice_file_name), RedThresh)
def Recognition_invoice(path):
'''
识别发票类别
:param none:
:return: 发票类别
'''
remove_stamp(path, invoice_file_name)
img1 = './test/RedThresh_{}.jpg'.format(invoice_file_name)
img1 = cv2.imread(img1)
result_type = OCR(img1)
result_type = union_rbox(result_type, 0.2)
print(result_type)
if len(result_type) > 0:
N = len(result_type)
for i in range(N):
txt = result_type[i]['text'].replace(' ', '')
txt = txt.replace(' ', '')
type_1 = re.findall('电子普通', txt)
type_2 = re.findall('普通发票', txt)
type_3 = re.findall('专用发票', txt)
if type_1 == None:
type_1 = []
if type_2 == None:
type_2 = []
if type_3 == None:
type_3 = []
print(type_1)
print(type_2)
print(type_3)
if len(type_1) > 0:
return 1
else:
return 2
elif len(result_type) == 0:
return 2
Recognition_invoice = Recognition_invoice(whole_path)
img = cv2.imread(whole_path)
h, w = img.shape[:2]
if Recognition_invoice == 1:
result = ocr_E(img)
res = invoice_e(result)
res = res.res
elif Recognition_invoice == 2:
result = ocr_M(img)
res = invoice_m(result)
res = res.res
else:
res = []
if len(res) > 0:
tz = pytz.timezone('Asia/Shanghai') # 东八区
ocr_identify_time = datetime.fromtimestamp(int(time.time()), tz).strftime('%Y-%m-%d %H:%M:%S')
return build_api_result(100, "识别成功", res, invoice_file_name, ocr_identify_time)
elif len(res) == 0:
return build_api_result(104, "识别为空!", {}, {}, {})
if __name__ == "__main__":
# Run
app.config['JSON_AS_ASCII'] = False
app.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)