在OCR检测时出现了问题(flask接口)
把OCR检测写成flask接口之后,读取出来的图片信息完全不沾边了
具体代码如下:
```python
import base64
import json
import logging.config
import os
from PIL import Image
from werkzeug.exceptions import HTTPException
from flask import Flask, request, make_response, jsonify
from api_exception import APIException, ServerError
import cv2
import numpy as np
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
app = Flask(__name__)
logging.config.fileConfig('logging.conf')
api_logger = logging.getLogger('apilog')
def making_response(json_data):
response = make_response(jsonify(json_data))
response.headers['Content-Type'] = 'application/json;charset=UTF-8'
return response
@app.errorhandler(Exception)
def framework_error(e):
if isinstance(e, APIException):
api_logger.debug(f"Client IP:{e.remote_addr}, Status:{e.code}, Msg:{e.msg}")
return e
elif isinstance(e, HTTPException):
api_logger.debug(f"Client IP:localhost, Status:{e.code}, Msg:{e.description}")
return APIException(msg=e.description, code=e.code, error_code="2998")
else:
api_logger.error(api_logger.exception(e))
return ServerError(remote_addr="localhost")
@app.route('/', methods=['GET'])
def index():
return "Hello World!"
@app.route('/ocr', methods=['POST'])
def cert_ocr():
# api_json = {"msg": None,
# "status": 200
# }
try: # 加载模型
ocr_detection = pipeline(
Tasks.ocr_detection,
model='damo/cv_resnet18_ocr-detection-line-level_damo')
ocr_recognition = pipeline(
Tasks.ocr_recognition,
model='damo/cv_convnextTiny_ocr-recognition-general_damo')
api_logger.info("200,Start load model!")
except Exception as a1:
# api_json["msg"] = "load model error!"
# api_json["status"] = 2998
api_logger.warning("load model error!")
try: # 加载数据
data = request.get_data()
api_logger.info("200,Start request!")
except Exception as a2:
# api_json["msg"] = "No data obtained!"
# api_json["status"] = 2998
api_logger.warning("No data, request status: invalid!")
try: # json
data = json.loads(data)
api_logger.info("200,start load")
except Exception as a3:
# api_json["msg"] = "Data loading error!"
# api_json["status"] = 2998
api_logger.error("Data loading error!")
try: # base64处理
image1 = base64.b64decode(data["image1"].encode())
# image_decode = base64.b64decode(image1)
api_logger.info("Data conversion start!")
except Exception as a4:
# api_json["msg"] = "Data conversion error!"
# api_json["status"] = 2998
api_logger.error("Data conversion error!")
try: # ocr识别
img1 = cv2.imdecode(np.frombuffer(image1, np.uint8), cv2.IMREAD_ANYCOLOR)
result = ocr_recognition(img1)
api_logger.info("Data processing start!")
except Exception as a5:
# api_json["msg"] = "Data processing error!"
# api_json["status"] = 2998
api_logger.warning("Data processing error!")
print(result)
# api_json["msg"] = "successful!"
api_logger.info("successful!")
# face_recognition(image1,image2)
print("~~~~~~~~~~~~", result)
return jsonify(result)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False)
运行结果如下:
```python
2023-02-22 17:37:39|INFO |saver.py[:1284]|Restoring parameters from damo/cv_resnet18_ocr-detection-line-level_damo\tf_ckpts\checkpoint-80000
2023-02-22 17:37:39|INFO |api.py[:59 ]|200,Start load model!
2023-02-22 17:37:39|INFO |api.py[:66 ]|200,Start request!
2023-02-22 17:37:39|INFO |api.py[:73 ]|200,start load
2023-02-22 17:37:39|INFO |api.py[:81 ]|Data conversion start!
2023-02-22 17:37:39|INFO |api.py[:89 ]|Data processing start!
{'text': '餐'}
2023-02-22 17:37:39|INFO |api.py[:97 ]|successful!
~~~~~~~~~~~~ {'text': '餐'}
2023-02-22 17:37:39|INFO |_internal.py[:224 ]|127.0.0.1 - - [22/Feb/2023 17:37:39] "POST /ocr HTTP/1.1" 200 -
正常用别的代码识别出来的结果是一个正常的银行开户许可证上的信息
我的期望就是想找到信息识别错误的原因