Skip to content

📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.

fix(rapidocr): support gpu_id when using torch (#363)

SWHL1508d1a495ea
diff --git a/python/demo.py b/python/demo.py
index 569bccc..aec145d 100644
--- a/python/demo.py
+++ b/python/demo.py
@@ -1,13 +1,14 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
-from rapidocr import RapidOCR, VisRes
+from rapidocr import RapidOCR
engine = RapidOCR()
-vis = VisRes()
img_url = "https://img1.baidu.com/it/u=3619974146,1266987475&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=516"
result = engine(img_url)
print(result)
result.vis()
+
+engine.export_config("1.yaml")
diff --git a/python/rapidocr/config.yaml b/python/rapidocr/config.yaml
index 7ef08b1..9eb5868 100644
--- a/python/rapidocr/config.yaml
+++ b/python/rapidocr/config.yaml
@@ -39,6 +39,7 @@ EngineConfig:
torch:
use_cuda: false
+ gpu_id: 0
Det:
model_path: null
diff --git a/python/rapidocr/inference_engine/torch.py b/python/rapidocr/inference_engine/torch.py
index d845332..f3922a2 100644
--- a/python/rapidocr/inference_engine/torch.py
+++ b/python/rapidocr/inference_engine/torch.py
@@ -47,14 +47,15 @@ class TorchInferSession(InferSession):
self.use_gpu = False
if config.engine_cfg.use_cuda:
- self.predictor.cuda()
+ self.device = torch.device(f"cuda:{config.engine_cfg.gpu_id}")
+ self.predictor.to(self.device)
self.use_gpu = True
def __call__(self, img: np.ndarray):
with torch.no_grad():
inp = torch.from_numpy(img)
if self.use_gpu:
- inp = inp.cuda()
+ inp = inp.to(self.device)
# 适配跟onnx对齐取值逻辑
outputs = self.predictor(inp).cpu().numpy()
diff --git a/python/rapidocr/main.py b/python/rapidocr/main.py
index d863bc5..2c4b264 100644
--- a/python/rapidocr/main.py
+++ b/python/rapidocr/main.py
@@ -3,6 +3,7 @@
# @Contact: [email protected]
import argparse
import copy
+import shutil
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
@@ -79,6 +80,8 @@ class RapidOCR:
self.return_paddleocr_format = False
self.return_word_box = False
+ self.config = config
+
def __call__(
self,
img_content: Union[str, np.ndarray, bytes, Path],
@@ -318,27 +321,68 @@ class RapidOCR:
ParseParams.save(self.config, f)
+def generate_cfg(args):
+ if args.save_cfg_file is None:
+ args.save_cfg_file = "./default_rapidocr.yaml"
+
+ shutil.copyfile(DEFAULT_CFG_PATH, args.save_cfg_file)
+ print(f"The config file has saved in {args.save_cfg_file}")
+
+
+def check_install():
+ img_url = "https://github.com/RapidAI/RapidOCR/blob/a9bb7c1f44b6e00556ada90ac588f020d7637c4b/python/tests/test_files/ch_en_num.jpg?raw=true"
+ result = RapidOCR()(img_url)
+
+ if result.txts is None or result.txts[0] != "正品促销":
+ raise ValueError("The installation is incorrect!")
+
+ print("Success! rapidocr is installed correctly!")
+
+
def parse_args(arg_list: Optional[List[str]] = None):
parser = argparse.ArgumentParser()
- parser.add_argument("-img", "--img_path", type=str, default=None, required=True)
+ parser.add_argument("-img", "--img_path", type=str, default=None)
parser.add_argument("--text_score", type=float, default=0.5)
parser.add_argument("-vis", "--vis_res", action="store_true", default=False)
parser.add_argument("--vis_save_dir", type=Path, default=".")
parser.add_argument(
"-word", "--return_word_box", action="store_true", default=False
)
+
+ subparser = parser.add_subparsers(dest="command", help="Sub-command help")
+ parser_cfg = subparser.add_parser("config", help="Generate config file")
+ parser_cfg.add_argument("--save_cfg_file", type=Path, default=None)
+ parser_cfg.set_defaults(func=generate_cfg)
+
+ parser_check = subparser.add_parser(
+ "check", help="Check if it is installed correctly "
+ )
+ parser_check.set_defaults(func=check_install)
+
args = parser.parse_args(arg_list)
return args
def main(arg_list: Optional[List[str]] = None):
args = parse_args(arg_list)
+
+ if args.command == "config":
+ generate_cfg(args)
+ return
+
+ if args.command == "check":
+ check_install()
+ return
+
params = {
"Global.text_score": args.text_score,
"Global.return_word_box": args.return_word_box,
}
ocr_engine = RapidOCR(params=params)
+ if args.img_path is None:
+ raise ValueError("Please input the image path")
+
if args.return_word_box:
result = ocr_engine(args.img_path, return_word_box=args.return_word_box)
else:
diff --git a/python/resources/fonts/.gitkeep b/python/resources/fonts/.gitkeep
deleted file mode 100644
index e69de29..0000000