RapidOCRPDF
RapidOCRPDF copied to clipboard
调用GPU的rapid无法识别图片内容,但是调用CPU可以
# image_ocr_processor.py
import base64
import os
from pathlib import Path
from utils import response
# 本地使用cpu资源进行识别
from rapidocr_onnxruntime import RapidOCR
# 生产环境使用GPU资源进行识别
# from rapidocr_paddle import RapidOCR
class ImageOCRProcessor:
def __init__(self):
self.engine = RapidOCR() # 初始化OCR系统
# 生产环境使用GPU资源进行识别
# self.engine = RapidOCR(det_use_cuda=True, cls_use_cuda=True, rec_use_cuda=True)
def process_image(self, image_input, use_det=True, use_cls=True, use_rec=True):
# 根据输入类型处理图片
if isinstance(image_input, (bytes, bytearray)) or isinstance(image_input, Path):
# 如果输入是字节类型,则直接使用 engine 方法
result, _ = self.engine(image_input, use_det=use_det, use_cls=use_cls, use_rec=use_rec)
else:
raise ValueError("Unsupported rapidocr_image input type")
final_result = ""
for item in result:
text = item[1]
final_result += " "+text
# 将合并后的内容写入到文本文件中
with open('output.txt', 'w', encoding='utf-8') as file:
file.write(final_result)
# 将output.txt文件转成文件流
with open('output.txt', 'rb') as file:
file_content = file.read()
encoded_content = base64.b64encode(file_content).decode('utf-8')
# os.remove('output.txt')
response_result = response.success(encoded_content)
json_data = response_result.to_dict()
return json_data
# 为了在 Flask 应用中使用这个处理器,我们可以在这里直接创建一个实例并调用 process_image 方法
# 这里只是一个示例,您可以根据需要调整
if __name__ == '__main__':
image_path = Path('../tests/test_files/2.jpg')
image_processor = ImageOCRProcessor()
ocr_result = image_processor.process_image(image_path)
print(ocr_result)
主要区别在于import的init方法,在生产环境上使用GPU的调用方式,图片无法识别,转成CPU即可,可能是底层库的原因
rapidocr-onnxruntime==1.3.15
paddleocr~=2.7.0.3
使用的版本
我在百度AI Studio中测试rapidocr_paddle库,GPU端,没有问题。
建议先排查一下paddlepaddle库在生产环境下调用GPU有无问题,可以用以下代码来自查一下:
import paddle
print(paddle.utils.run_check())
# 如果出现PaddlePaddle is installed successfully!,说明您已成功安装。
issue先行关闭,有问题再开