分享项目 paddleOCR 之 onnxOCR
版本更新
PPOCRv4模型转onnx模型推理,精度和性能更高,推理速度比使用paddlepaddle框架快5倍
一.优势:
1.脱离深度学习训练框架,可直接用于部署的通用OCR。
2.在算力有限,精度不变的情况下使用paddleOCR转成ONNX模型,进行重新构建的一款可部署在arm架构和x86架构计算机上的OCR模型。
3.在同样性能的计算机上推理速度加速了4-5倍。
二.环境安装
python>=3.6
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
三.一键运行
python test_ocr.py
四、 附上我改写的测试代码 api server (2024.08.09)
下面代码执行前,需要额外安装 pyzbar。
pip3 install pyzbar -i https://pypi.mirrors.ustc.edu.cn/simple/
我把写了一个http api,同时ocr和qrcode识别探测。其中qrcode探测和识别我采用了2种方法。一是opencv自带的QRCodeDetector(),另一个是pyzbar。实测结果是自带的这个QRCodeDetector对一页当中多个二维码的情况存不能全部识别,而pyzbar就行。同时自带的还不能识别一些变体二维码,如下图所示的小恐龙二维码:
import cv2
import time
from onnxocr.onnx_paddleocr import ONNXPaddleOcr
import sys
from flask import Flask,request, Response, jsonify
import json
import os
from pyzbar.pyzbar import decode
model = ONNXPaddleOcr(use_angle_cls=True, use_gpu=False)
app= Flask(__name__)
def decode_qr_code(img):
decoded_objects=decode(img)
results=[]
for obj in decoded_objects:
result_dict={
"type":obj.type,
"data": obj.data.decode("utf-8")
}
results.append(result_dict)
return results
def qrcodeDetect(img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
qrcoder = cv2.QRCodeDetector()
codeinfo, points, straight_qrcode = qrcoder.detectAndDecode(img)
# 创建结果对象
result = {
'has_qrcode': int(bool(codeinfo)),
'result': codeinfo
}
return result
@app.route('/api/ocr',methods=['GET'])
def ocr():
# 这里实际上生产环境要做路径限制和检测,甚至是改用上传图片的方式
file_path=request.args.get('path')
if file_path and os.path.exists(file_path):
try:
s = time.time()
img = cv2.imread(file_path)
result = model.ocr(img)
results=[ item[1][0] for item in result[0] ]
result_str = ' '.join(results)
e = time.time()
has_qrcode=qrcodeDetect(img)
decode_qr=decode_qr_code(img)
d=e-s json_content=json.dumps({"time":d,"result":result_str,"has_qrcode":has_qrcode,"decode_qr":decode_qr},ensure_ascii=False)
return Response(json_content,mimetype='application/json'),200
except Exception as e:
return jsonify({'error':f'Error readig file:{str(e)}'}),500
else:
return jsonify({'error': 'Invalid or missing file path'}), 400
if __name__ == '__main__':
app.run(debug=True)
以上代码保存为 test_ocr_server.py
python3 test_ocr_server.py
curl -s http://127.0.0.1:5000/api/ocr?path=./test/13.png
13.png :