RicardoM.Lu1 2023-02-22 18:06 采纳率: 80.6%
浏览 194
已结题

把OCR检测写成flask接口后出现了问题

在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  ]|200Start 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 -

正常用别的代码识别出来的结果是一个正常的银行开户许可证上的信息
我的期望就是想找到信息识别错误的原因

  • 写回答

10条回答 默认 最新

  • 程序猿_Mr. Guo 2023-02-22 18:14
    关注

    可以尝试下这个代码看看

    from io import BytesIO
    
    from PIL import Image
    
    @app.route('/ocr', methods=['POST'])
    def cert_ocr():
        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 e:
            api_logger.warning("load model error!")
            raise APIException(msg="load model error!", code=2998, error_code="2998")
    
        try:
            # 加载数据
            data = request.get_data()
            api_logger.info("200,Start request!")
        except Exception as e:
            api_logger.warning("No data, request status: invalid!")
            raise APIException(msg="No data obtained!", code=2998, error_code="2998")
    
        try:
            # json
            data = json.loads(data)
            api_logger.info("200,start load")
        except Exception as e:
            api_logger.error("Data loading error!")
            raise APIException(msg="Data loading error!", code=2998, error_code="2998")
    
        try:
            # base64处理
            image_data = data.get("image1")
            if not image_data:
                raise APIException(msg="No image data found!", code=2998, error_code="2998")
    
            image_bytes = base64.b64decode(image_data)
            image = Image.open(BytesIO(image_bytes))
            api_logger.info("Data conversion start!")
        except Exception as e:
            api_logger.error("Data conversion error!")
            raise APIException(msg="Data conversion error!", code=2998, error_code="2998")
    
        try:
            # ocr识别
            img = np.array(image)
            result = ocr_recognition(img)
            api_logger.info("Data processing start!")
    
        except Exception as e:
            api_logger.warning("Data processing error!")
            raise APIException(msg="Data processing error!", code=2998, error_code="2998")
    
        api_logger.info("successful!")
        return jsonify(result)
    
    评论

报告相同问题?

问题事件

  • 系统已结题 3月2日
  • 创建了问题 2月22日

悬赏问题

  • ¥15 gojs 点击按钮node的position位置进行改变,再次点击回到原来的位置
  • ¥15 计算决策面并仿真附上结果
  • ¥20 halcon 图像拼接
  • ¥15 webstorm上开发的vue3+vite5+typeScript打包时报错
  • ¥15 vue使用gojs,需求在link中的虚线上添加方向箭头
  • ¥15 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥100 求ASMedia ASM1184e & ASM1187e 芯片datasheet/规格书
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么