转载请注明出处:小锋学长生活大爆炸[xfxuezhagn.cn]
如果本文帮助到了你,欢迎[点赞、收藏、关注]哦~
问题描述
在使用cnocr调用onnxruntime时候遇到报错:
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\rapidocr\inference_engine\onnxruntime\main.py", line 62, in __init__ self.session = InferenceSession( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\onnxruntime\capi\onnxruntime_inference_collection.py", line 349, in __init__ raise TypeError("Unable to load from type '{0}'".format(type(path_or_bytes))) TypeError: Unable to load from type '<class 'pathlib.WindowsPath'>'
问题的关键在于 onnxruntime 无法处理 pathlib.WindowsPath 类型的路径,而 cnocr 或 rapidocr 在传递模型路径时使用了这种类型。
解决方案
如果能接触到源码,就直接手动转换:
from cnocr import CnOcr
from pathlib import Path
# 获取模型路径并转换为字符串
model_path = str(Path("xxx/ch_PP-OCRv5_det_infer.onnx"))
如果不想改源码,就打个补丁(推荐):
import onnxruntime
import pathlib
# 保存原始的 InferenceSession
_orig_InferenceSession = onnxruntime.InferenceSession
# 创建包装函数
def _patched_InferenceSession(path_or_bytes, *args, **kwargs):
if isinstance(path_or_bytes, pathlib.Path):
path_or_bytes = str(path_or_bytes)
return _orig_InferenceSession(path_or_bytes, *args, **kwargs)
# 打补丁
onnxruntime.InferenceSession = _patched_InferenceSession
# 现在导入 cnocr 应该正常工作
from cnocr import CnOcr