Skip to content

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

Fixed issue #122

SWHL6d53213d18d1
diff --git a/.github/workflows/gen_whl_to_pypi_rapidocr_ort.yml b/.github/workflows/gen_whl_to_pypi_rapidocr_ort.yml
index b24dcd8..972e70b 100644
--- a/.github/workflows/gen_whl_to_pypi_rapidocr_ort.yml
+++ b/.github/workflows/gen_whl_to_pypi_rapidocr_ort.yml
@@ -38,7 +38,8 @@ jobs:
cp $DIR_NAME/resources/models/*.onnx python/rapidocr_onnxruntime/models/
cp $DIR_NAME/resources/models/*.onnx python/rapidocr_openvino/models/
cd python
- pip install -r requirements.txt
+ pip install -r requirements_ort.txt
+ pip install pytest wheel get_pypi_latest_version
cd tests
wget $TWO_DIM_IMAGE -O two_dim_image.npy
mv two_dim_image.npy test_files/
@@ -78,25 +79,18 @@ jobs:
- name: Run setup_onnxruntime.py
run: |
cd python
- pip install -r requirements.txt
+ pip install setuptools get_pypi_latest_version wheel
mkdir rapidocr_onnxruntime_t
mv rapidocr_onnxruntime rapidocr_onnxruntime_t
mv rapidocr_onnxruntime_t rapidocr_onnxruntime
cd rapidocr_onnxruntime
- echo "from .rapidocr_onnxruntime.rapid_ocr_api import RapidOCR" > __init__.py
+ echo "from .rapidocr_onnxruntime.main import RapidOCR" > __init__.py
cd ..
python -m pip install --upgrade pip
python setup_onnxruntime.py bdist_wheel ${{ github.event.head_commit.message }}
mv dist ../
- # - name: Publish distribution 📦 to Test PyPI
- # uses: pypa/[email protected]
- # with:
- # password: ${{ secrets.TEST_PYPI_API_TOKEN }}
- # repository_url: https://test.pypi.org/legacy/
- # packages_dir: dist/
-
- name: Publish distribution 📦 to PyPI
uses: pypa/[email protected]
with:
diff --git a/.github/workflows/gen_whl_to_pypi_rapidocr_vino.yml b/.github/workflows/gen_whl_to_pypi_rapidocr_vino.yml
index 7bdedde..1e41132 100644
--- a/.github/workflows/gen_whl_to_pypi_rapidocr_vino.yml
+++ b/.github/workflows/gen_whl_to_pypi_rapidocr_vino.yml
@@ -38,7 +38,8 @@ jobs:
cp $DIR_NAME/resources/models/*.onnx python/rapidocr_onnxruntime/models/
cp $DIR_NAME/resources/models/*.onnx python/rapidocr_openvino/models/
cd python
- pip install -r requirements.txt
+ pip install -r requirements_vino.txt
+ pip install pytest wheel get_pypi_latest_version
cd tests
wget $TWO_DIM_IMAGE -O two_dim_image.npy
mv two_dim_image.npy test_files/
@@ -78,25 +79,18 @@ jobs:
- name: Run setup_openvino.py
run: |
cd python
- pip install -r requirements.txt
+ pip install setuptools get_pypi_latest_version wheel
mkdir rapidocr_openvino_t
mv rapidocr_openvino rapidocr_openvino_t
mv rapidocr_openvino_t rapidocr_openvino
cd rapidocr_openvino
- echo "from .rapidocr_openvino.rapid_ocr_api import RapidOCR" > __init__.py
+ echo "from .rapidocr_openvino.main import RapidOCR" > __init__.py
cd ..
python -m pip install --upgrade pip
python setup_openvino.py bdist_wheel ${{ github.event.head_commit.message }}
mv dist ../
- # - name: Publish distribution 📦 to Test PyPI
- # uses: pypa/[email protected]
- # with:
- # password: ${{ secrets.TEST_PYPI_API_TOKEN }}
- # repository_url: https://test.pypi.org/legacy/
- # packages_dir: dist/
-
- name: Publish distribution 📦 to PyPI
uses: pypa/[email protected]
with:
diff --git a/docs/doc_whl_rapidocr_ort.md b/docs/doc_whl_rapidocr_ort.md
index 5e13b35..2d89a6a 100644
--- a/docs/doc_whl_rapidocr_ort.md
+++ b/docs/doc_whl_rapidocr_ort.md
@@ -1,116 +1,8 @@
-## rapidocr-onnxruntime Package
+## rapidocr-onnxruntime
<p>
<a href=""><img src="https://img.shields.io/badge/Python->=3.6,<3.12-aff.svg"></a>
<a href=""><img src="https://img.shields.io/badge/OS-Linux%2C%20Win%2C%20Mac-pink.svg"></a>
<a href="https://pepy.tech/project/rapidocr_onnxruntime"><img src="https://static.pepy.tech/personalized-badge/rapidocr_onnxruntime?period=total&units=abbreviation&left_color=grey&right_color=blue&left_text=Downloads%20Ort"></a>
</p>
-### 1. Install package by pypi.
-```bash
-$ pip install rapidocr-onnxruntime
-```
-
-### 2. Use.
-- Run by script.
- ```python
- import cv2
- from rapidocr_onnxruntime import RapidOCR
-
- rapid_ocr = RapidOCR()
-
- img_path = 'tests/test_files/ch_en_num.jpg'
-
- # Support:Union[str, np.ndarray, bytes, Path]
- # str
- result, elapse = rapid_ocr(img_path)
-
- # np.ndarray
- img = cv2.imread('tests/test_files/ch_en_num.jpg')
- result, elapse = rapid_ocr(img)
-
- # bytes
- with open(img_path, 'rb') as f:
- result, elapse = rapid_ocr(f.read())
-
- # Path
- result, elapse = rapid_ocr(Path(img_path))
- print(result)
-
- # result: [[dt_boxes], txt, score]
- # e.g.:[[left-top, right-top, right-down, left-top], '小明', '0.99']
-
- # elapse: [det_elapse, cls_elapse, rec_elapse]
- # all_elapse = det_elapse + cls_elapse + rec_elapse
-
- # If without valid texts, result: (None, None )
- ```
-
-- Run by command line.
- ```bash
- $ rapidocr_onnxruntime -h
- usage: rapidocr_onnxruntime [-h] -img IMG_PATH [-p] [--text_score TEXT_SCORE]
- [--use_angle_cls USE_ANGLE_CLS]
- [--use_text_det USE_TEXT_DET]
- [--print_verbose PRINT_VERBOSE]
- [--min_height MIN_HEIGHT]
- [--width_height_ratio WIDTH_HEIGHT_RATIO]
- [--det_use_cuda DET_USE_CUDA]
- [--det_model_path DET_MODEL_PATH]
- [--det_limit_side_len DET_LIMIT_SIDE_LEN]
- [--det_limit_type {max,min}]
- [--det_thresh DET_THRESH]
- [--det_box_thresh DET_BOX_THRESH]
- [--det_unclip_ratio DET_UNCLIP_RATIO]
- [--det_use_dilation DET_USE_DILATION]
- [--det_score_mode {slow,fast}]
- [--cls_use_cuda CLS_USE_CUDA]
- [--cls_model_path CLS_MODEL_PATH]
- [--cls_image_shape CLS_IMAGE_SHAPE]
- [--cls_label_list CLS_LABEL_LIST]
- [--cls_batch_num CLS_BATCH_NUM]
- [--cls_thresh CLS_THRESH]
- [--rec_use_cuda REC_USE_CUDA]
- [--rec_model_path REC_MODEL_PATH]
- [--rec_img_shape REC_IMAGE_SHAPE]
- [--rec_batch_num REC_BATCH_NUM]
-
- optional arguments:
- -h, --help show this help message and exit
- -img IMG_PATH, --img_path IMG_PATH MUST
- -p, --print_cost
-
- Global:
- --text_score TEXT_SCORE
- --use_angle_cls USE_ANGLE_CLS
- --use_text_det USE_TEXT_DET
- --print_verbose PRINT_VERBOSE
- --min_height MIN_HEIGHT
- --width_height_ratio WIDTH_HEIGHT_RATIO
-
- Det:
- --det_use_cuda DET_USE_CUDA
- --det_model_path DET_MODEL_PATH
- --det_limit_side_len DET_LIMIT_SIDE_LEN
- --det_limit_type {max,min}
- --det_thresh DET_THRESH
- --det_box_thresh DET_BOX_THRESH
- --det_unclip_ratio DET_UNCLIP_RATIO
- --det_use_dilation DET_USE_DILATION
- --det_score_mode {slow,fast}
-
- Cls:
- --cls_use_cuda CLS_USE_CUDA
- --cls_model_path CLS_MODEL_PATH
- --cls_image_shape CLS_IMAGE_SHAPE
- --cls_label_list CLS_LABEL_LIST
- --cls_batch_num CLS_BATCH_NUM
- --cls_thresh CLS_THRESH
-
- Rec:
- --rec_use_cuda REC_USE_CUDA
- --rec_model_path REC_MODEL_PATH
- --rec_img_shape REC_IMAGE_SHAPE
- --rec_batch_num REC_BATCH_NUM
-
- $ rapidocr_onnxruntime -img tests/test_files/ch_en_num.jpg
- ```
+### See [Documentation](https://rapidai.github.io/RapidOCRDocs/docs/install_usage/rapidocr/rapidocr_onnxruntime/)
diff --git a/docs/doc_whl_rapidocr_vino.md b/docs/doc_whl_rapidocr_vino.md
index 6ce0ec4..1f6121c 100644
--- a/docs/doc_whl_rapidocr_vino.md
+++ b/docs/doc_whl_rapidocr_vino.md
@@ -1,111 +1,8 @@
-## rapidocr-openvino Package
+## rapidocr-openvino
<p>
<a href=""><img src="https://img.shields.io/badge/Python->=3.6,<3.12-aff.svg"></a>
<a href=""><img src="https://img.shields.io/badge/OS-Linux%2C%20Win%2C%20Mac-pink.svg"></a>
<a href="https://pepy.tech/project/rapidocr_openvino"><img src="https://static.pepy.tech/personalized-badge/rapidocr_openvino?period=total&units=abbreviation&left_color=grey&right_color=blue&left_text=Downloads%20Vino"></a>
</p>
-### 1. Install package by pypi.
-```shell
-$ pip install rapidocr-openvino
-```
-
-
-### 2. Use.
-- Run by script.
- ```python
- import cv2
- from rapidocr_openvino import RapidOCR
-
- rapid_ocr = RapidOCR()
-
- img_path = 'tests/test_files/ch_en_num.jpg'
-
- # Support:Union[str, np.ndarray, bytes, Path]
- # str
- result, elapse = rapid_ocr(img_path)
-
- # np.ndarray
- img = cv2.imread('tests/test_files/ch_en_num.jpg')
- result, elapse = rapid_ocr(img)
-
- # bytes
- with open(img_path, 'rb') as f:
- result, elapse = rapid_ocr(f.read())
-
- # Path
- result, elapse = rapid_ocr(Path(img_path))
- print(result)
-
- # result: [[dt_boxes], txt, score]
- # e.g.:[[left-top, right-top, right-down, left-top], '小明', '0.99']
-
- # elapse: [det_elapse, cls_elapse, rec_elapse]
- # all_elapse = det_elapse + cls_elapse + rec_elapse
-
- # If without valid texts, result: (None, None )
- ```
-
-- Run by command line.
- ```bash
- $ rapidocr_openvino -h
- usage: rapidocr_openvino [-h] -img IMG_PATH [-p] [--text_score TEXT_SCORE]
- [--use_angle_cls USE_ANGLE_CLS]
- [--use_text_det USE_TEXT_DET]
- [--print_verbose PRINT_VERBOSE]
- [--min_height MIN_HEIGHT]
- [--width_height_ratio WIDTH_HEIGHT_RATIO]
- [--det_model_path DET_MODEL_PATH]
- [--det_limit_side_len DET_LIMIT_SIDE_LEN]
- [--det_limit_type {max,min}]
- [--det_thresh DET_THRESH]
- [--det_box_thresh DET_BOX_THRESH]
- [--det_unclip_ratio DET_UNCLIP_RATIO]
- [--det_use_dilation DET_USE_DILATION]
- [--det_score_mode {slow,fast}]
- [--cls_model_path CLS_MODEL_PATH]
- [--cls_image_shape CLS_IMAGE_SHAPE]
- [--cls_label_list CLS_LABEL_LIST]
- [--cls_batch_num CLS_BATCH_NUM]
- [--cls_thresh CLS_THRESH]
- [--rec_model_path REC_MODEL_PATH]
- [--rec_img_shape REC_IMAGE_SHAPE]
- [--rec_batch_num REC_BATCH_NUM]
-
- optional arguments:
- -h, --help show this help message and exit
- -img IMG_PATH, --img_path IMG_PATH
- -p, --print_cost
-
- Global:
- --text_score TEXT_SCORE
- --use_angle_cls USE_ANGLE_CLS
- --use_text_det USE_TEXT_DET
- --print_verbose PRINT_VERBOSE
- --min_height MIN_HEIGHT
- --width_height_ratio WIDTH_HEIGHT_RATIO
-
- Det:
- --det_model_path DET_MODEL_PATH
- --det_limit_side_len DET_LIMIT_SIDE_LEN
- --det_limit_type {max,min}
- --det_thresh DET_THRESH
- --det_box_thresh DET_BOX_THRESH
- --det_unclip_ratio DET_UNCLIP_RATIO
- --det_use_dilation DET_USE_DILATION
- --det_score_mode {slow,fast}
-
- Cls:
- --cls_model_path CLS_MODEL_PATH
- --cls_image_shape CLS_IMAGE_SHAPE
- --cls_label_list CLS_LABEL_LIST
- --cls_batch_num CLS_BATCH_NUM
- --cls_thresh CLS_THRESH
-
- Rec:
- --rec_model_path REC_MODEL_PATH
- --rec_img_shape REC_IMAGE_SHAPE
- --rec_batch_num REC_BATCH_NUM
-
- $ rapidocr_openvino -img tests/test_files/ch_en_num.jpg
- ```
\ No newline at end of file
+### See [Documentation](https://rapidai.github.io/RapidOCRDocs/docs/install_usage/rapidocr/rapidocr_openvino/)
diff --git a/python/demo.py b/python/demo.py
index 60a91e1..1cccf48 100644
--- a/python/demo.py
+++ b/python/demo.py
@@ -99,11 +99,9 @@ def visualize(image_path, result, font_path="resources/fonts/FZYTK.TTF"):
if __name__ == "__main__":
rapid_ocr = RapidOCR()
- image_path = "res.png"
- # with open(image_path, "rb") as f:
- # img = f.read()
- img = cv2.imread(image_path)
- img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+ image_path = "tests/test_files/ch_en_num.jpg"
+ with open(image_path, "rb") as f:
+ img = f.read()
result, elapse_list = rapid_ocr(img)
print(result)
print(elapse_list)
diff --git a/python/rapidocr_onnxruntime/__init__.py b/python/rapidocr_onnxruntime/__init__.py
index fd53856..ecc8206 100644
--- a/python/rapidocr_onnxruntime/__init__.py
+++ b/python/rapidocr_onnxruntime/__init__.py
@@ -1,5 +1,5 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
-from .rapid_ocr_api import RapidOCR
+from .main import RapidOCR
from .utils import LoadImageError
diff --git a/python/rapidocr_onnxruntime/config.yaml b/python/rapidocr_onnxruntime/config.yaml
index 988e49e..3bd2061 100644
--- a/python/rapidocr_onnxruntime/config.yaml
+++ b/python/rapidocr_onnxruntime/config.yaml
@@ -1,7 +1,8 @@
Global:
text_score: 0.5
- use_angle_cls: true
- use_text_det: true
+ use_det: true
+ use_cls: true
+ use_rec: true
print_verbose: false
min_height: 30
width_height_ratio: 8
diff --git a/python/rapidocr_onnxruntime/rapid_ocr_api.py b/python/rapidocr_onnxruntime/main.py
similarity index 54%
rename from python/rapidocr_onnxruntime/rapid_ocr_api.py
rename to python/rapidocr_onnxruntime/main.py
index faef39c..e9c98d4 100644
--- a/python/rapidocr_onnxruntime/rapid_ocr_api.py
+++ b/python/rapidocr_onnxruntime/main.py
@@ -2,9 +2,8 @@
# @Author: SWHL
# @Contact: [email protected]
import copy
-import importlib
from pathlib import Path
-from typing import Optional, Union
+from typing import List, Optional, Tuple, Union
import cv2
import numpy as np
@@ -38,73 +37,126 @@ class RapidOCR:
self.min_height = global_config["min_height"]
self.width_height_ratio = global_config["width_height_ratio"]
- self.use_text_det = config["Global"]["use_text_det"]
- if self.use_text_det:
- self.text_detector = TextDetector(config["Det"])
+ self.use_det = config["Global"]["use_det"]
+ self.text_det = TextDetector(config["Det"])
- self.text_recognizer = TextRecognizer(config["Rec"])
+ self.use_cls = config["Global"]["use_cls"]
+ self.text_cls = TextClassifier(config["Cls"])
- self.use_angle_cls = config["Global"]["use_angle_cls"]
- if self.use_angle_cls:
- self.text_cls = TextClassifier(config["Cls"])
+ self.use_rec = config["Global"]["use_rec"]
+ self.text_rec = TextRecognizer(config["Rec"])
self.load_img = LoadImage()
- def __call__(self, img_content: Union[str, np.ndarray, bytes, Path], **kwargs):
+ def __call__(
+ self,
+ img_content: Union[str, np.ndarray, bytes, Path],
+ use_det: Optional[bool] = None,
+ use_cls: Optional[bool] = None,
+ use_rec: Optional[bool] = None,
+ **kwargs,
+ ):
+ if use_det is None:
+ use_det = self.use_det
+
+ if use_cls is None:
+ use_cls = self.use_cls
+
+ if use_rec is None:
+ use_rec = self.use_rec
+
if kwargs:
box_thresh = kwargs.get("box_thresh", 0.5)
unclip_ratio = kwargs.get("unclip_ratio", 1.6)
text_score = kwargs.get("text_score", 0.5)
- self.text_detector.postprocess_op.box_thresh = box_thresh
- self.text_detector.postprocess_op.unclip_ratio = unclip_ratio
+ self.text_det.postprocess_op.box_thresh = box_thresh
+ self.text_det.postprocess_op.unclip_ratio = unclip_ratio
self.text_score = text_score
img = self.load_img(img_content)
- h, w = img.shape[:2]
- if self.width_height_ratio == -1:
- use_limit_ratio = False
- else:
- use_limit_ratio = w / h > self.width_height_ratio
- if not self.use_text_det or h <= self.min_height or use_limit_ratio:
- dt_boxes, img_crop_list = self.get_boxes_img_without_det(img, h, w)
- det_elapse = 0.0
- else:
- dt_boxes, det_elapse = self.text_detector(img)
- if dt_boxes is None or len(dt_boxes) < 1:
+ if use_det and not use_cls and not use_rec:
+ # only det
+ dt_boxes, det_elapse, img_crop_list = self.auto_text_det(img)
+ if dt_boxes is None or img_crop_list is None:
return None, None
- if self.print_verbose:
- print(f"dt_boxes num: {len(dt_boxes)}, elapse: {det_elapse}")
+ det_res = [box.tolist() for box in dt_boxes]
+ return det_res, [det_elapse]
+
+ if not use_det and use_cls and not use_rec:
+ # only cls
+ img, cls_res, cls_elapse = self.text_cls(img)
+ return cls_res, [cls_elapse]
- dt_boxes = self.sorted_boxes(dt_boxes)
- img_crop_list = self.get_crop_img_list(img, dt_boxes)
+ if not use_det and not use_cls and use_rec:
+ # only rec
+ rec_res, rec_elapse = self.text_rec(img)
+ rec_res = [[res[0], res[1]] for res in rec_res]
+ return rec_res, [rec_elapse]
+
+ if use_det and use_cls and use_rec:
+ # det + cls + rec
+ dt_boxes, det_elapse, img_crop_list = self.auto_text_det(img)
+ if dt_boxes is None or img_crop_list is None:
+ return None, None
- cls_elapse = 0.0
- if self.use_angle_cls:
img_crop_list, _, cls_elapse = self.text_cls(img_crop_list)
+ rec_res, rec_elapse = self.text_rec(img_crop_list)
+ dt_boxes, rec_res = self.filter_result(dt_boxes, rec_res)
+ if dt_boxes is None and rec_res is None:
+ return None, None
- if self.print_verbose:
- print(f"cls num: {len(img_crop_list)}, elapse: {cls_elapse}")
+ ocr_res = [
+ [box.tolist(), res[0], res[1]] for box, res in zip(dt_boxes, rec_res)
+ ]
+ return ocr_res, [det_elapse, cls_elapse, rec_elapse]
- rec_res, rec_elapse = self.text_recognizer(img_crop_list)
- if self.print_verbose:
- print(f"rec_res num: {len(rec_res)}, elapse: {rec_elapse}")
+ if use_det and not use_cls and use_rec:
+ # det + rec
+ dt_boxes, det_elapse, img_crop_list = self.auto_text_det(img)
+ if dt_boxes is None or img_crop_list is None:
+ return None, None
- filter_boxes, filter_rec_res = self.filter_boxes_rec_by_score(dt_boxes, rec_res)
- fina_result = [
- [dt.tolist(), rec[0], str(rec[1])]
- for dt, rec in zip(filter_boxes, filter_rec_res)
- ]
- if fina_result:
- return fina_result, [det_elapse, cls_elapse, rec_elapse]
- return None, None
+ rec_res, rec_elapse = self.text_rec(img_crop_list)
+ dt_boxes, rec_res = self.filter_result(dt_boxes, rec_res)
+ if dt_boxes is None and rec_res is None:
+ return None, None
- @staticmethod
- def init_module(module_name, class_name):
- module_part = importlib.import_module(module_name)
- return getattr(module_part, class_name)
+ ocr_res = [
+ [box.tolist(), res[0], res[1]] for box, res in zip(dt_boxes, rec_res)
+ ]
+ return ocr_res, [det_elapse, rec_elapse]
+
+ if not use_det and use_cls and use_rec:
+ # cls + rec
+ img, cls_res, cls_elapse = self.text_cls(img)
+ rec_res, rec_elapse = self.text_rec(img)
+ ocr_res = [[res[0], res[1]] for res in rec_res]
+ return ocr_res, [cls_elapse, rec_elapse]
+
+ def auto_text_det(
+ self,
+ img: np.ndarray,
+ ) -> Tuple[Optional[np.ndarray], float, Optional[List[np.ndarray]]]:
+ h, w = img.shape[:2]
+ if self.width_height_ratio == -1:
+ use_limit_ratio = False
+ else:
+ use_limit_ratio = w / h > self.width_height_ratio
+
+ if not self.use_det or h <= self.min_height or use_limit_ratio:
+ dt_boxes, img_crop_list = self.get_boxes_img_without_det(img, h, w)
+ return dt_boxes, 0.0, img_crop_list
+
+ dt_boxes, det_elapse = self.text_det(img)
+ if dt_boxes is None or len(dt_boxes) < 1:
+ return None, 0.0, None
+
+ dt_boxes = self.sorted_boxes(dt_boxes)
+ img_crop_list = self.get_crop_img_list(img, dt_boxes)
+ return dt_boxes, det_elapse, img_crop_list
def get_boxes_img_without_det(self, img, h, w):
x0, y0, x1, y1 = 0, 0, w, h
@@ -181,13 +233,16 @@ class RapidOCR:
break
return _boxes
- def filter_boxes_rec_by_score(self, dt_boxes, rec_res):
+ def filter_result(self, dt_boxes, rec_res):
filter_boxes, filter_rec_res = [], []
for box, rec_reuslt in zip(dt_boxes, rec_res):
text, score = rec_reuslt
- if score >= self.text_score:
+ if float(score) >= self.text_score:
filter_boxes.append(box)
filter_rec_res.append(rec_reuslt)
+
+ if len(filter_boxes) <= 0:
+ return None, None
return filter_boxes, filter_rec_res
@@ -195,7 +250,9 @@ def main():
args = init_args()
ocr_engine = RapidOCR(**vars(args))
- result, elapse_list = ocr_engine(args.img_path)
+ result, elapse_list = ocr_engine(
+ args.img_path, use_det=args.use_det, use_cls=args.use_cls, use_rec=args.use_rec
+ )
print(result)
if args.print_cost:
print(elapse_list)
diff --git a/python/rapidocr_onnxruntime/utils.py b/python/rapidocr_onnxruntime/utils.py
index 35e42df..4a1d76a 100644
--- a/python/rapidocr_onnxruntime/utils.py
+++ b/python/rapidocr_onnxruntime/utils.py
@@ -223,8 +223,9 @@ def init_args():
global_group = parser.add_argument_group(title="Global")
global_group.add_argument("--text_score", type=float, default=0.5)
- global_group.add_argument("--use_angle_cls", type=bool, default=True)
- global_group.add_argument("--use_text_det", type=bool, default=True)
+ global_group.add_argument("--use_det", type=bool, default=True)
+ global_group.add_argument("--use_cls", type=bool, default=True)
+ global_group.add_argument("--use_rec", type=bool, default=True)
global_group.add_argument("--print_verbose", type=bool, default=False)
global_group.add_argument("--min_height", type=int, default=30)
global_group.add_argument("--width_height_ratio", type=int, default=8)
diff --git a/python/rapidocr_openvino/__init__.py b/python/rapidocr_openvino/__init__.py
index fd53856..ecc8206 100644
--- a/python/rapidocr_openvino/__init__.py
+++ b/python/rapidocr_openvino/__init__.py
@@ -1,5 +1,5 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
-from .rapid_ocr_api import RapidOCR
+from .main import RapidOCR
from .utils import LoadImageError
diff --git a/python/rapidocr_openvino/config.yaml b/python/rapidocr_openvino/config.yaml
index 988e49e..3bd2061 100644
--- a/python/rapidocr_openvino/config.yaml
+++ b/python/rapidocr_openvino/config.yaml
@@ -1,7 +1,8 @@
Global:
text_score: 0.5
- use_angle_cls: true
- use_text_det: true
+ use_det: true
+ use_cls: true
+ use_rec: true
print_verbose: false
min_height: 30
width_height_ratio: 8
diff --git a/python/rapidocr_openvino/rapid_ocr_api.py b/python/rapidocr_openvino/main.py
similarity index 54%
rename from python/rapidocr_openvino/rapid_ocr_api.py
rename to python/rapidocr_openvino/main.py
index faef39c..e9c98d4 100644
--- a/python/rapidocr_openvino/rapid_ocr_api.py
+++ b/python/rapidocr_openvino/main.py
@@ -2,9 +2,8 @@
# @Author: SWHL
# @Contact: [email protected]
import copy
-import importlib
from pathlib import Path
-from typing import Optional, Union
+from typing import List, Optional, Tuple, Union
import cv2
import numpy as np
@@ -38,73 +37,126 @@ class RapidOCR:
self.min_height = global_config["min_height"]
self.width_height_ratio = global_config["width_height_ratio"]
- self.use_text_det = config["Global"]["use_text_det"]
- if self.use_text_det:
- self.text_detector = TextDetector(config["Det"])
+ self.use_det = config["Global"]["use_det"]
+ self.text_det = TextDetector(config["Det"])
- self.text_recognizer = TextRecognizer(config["Rec"])
+ self.use_cls = config["Global"]["use_cls"]
+ self.text_cls = TextClassifier(config["Cls"])
- self.use_angle_cls = config["Global"]["use_angle_cls"]
- if self.use_angle_cls:
- self.text_cls = TextClassifier(config["Cls"])
+ self.use_rec = config["Global"]["use_rec"]
+ self.text_rec = TextRecognizer(config["Rec"])
self.load_img = LoadImage()
- def __call__(self, img_content: Union[str, np.ndarray, bytes, Path], **kwargs):
+ def __call__(
+ self,
+ img_content: Union[str, np.ndarray, bytes, Path],
+ use_det: Optional[bool] = None,
+ use_cls: Optional[bool] = None,
+ use_rec: Optional[bool] = None,
+ **kwargs,
+ ):
+ if use_det is None:
+ use_det = self.use_det
+
+ if use_cls is None:
+ use_cls = self.use_cls
+
+ if use_rec is None:
+ use_rec = self.use_rec
+
if kwargs:
box_thresh = kwargs.get("box_thresh", 0.5)
unclip_ratio = kwargs.get("unclip_ratio", 1.6)
text_score = kwargs.get("text_score", 0.5)
- self.text_detector.postprocess_op.box_thresh = box_thresh
- self.text_detector.postprocess_op.unclip_ratio = unclip_ratio
+ self.text_det.postprocess_op.box_thresh = box_thresh
+ self.text_det.postprocess_op.unclip_ratio = unclip_ratio
self.text_score = text_score
img = self.load_img(img_content)
- h, w = img.shape[:2]
- if self.width_height_ratio == -1:
- use_limit_ratio = False
- else:
- use_limit_ratio = w / h > self.width_height_ratio
- if not self.use_text_det or h <= self.min_height or use_limit_ratio:
- dt_boxes, img_crop_list = self.get_boxes_img_without_det(img, h, w)
- det_elapse = 0.0
- else:
- dt_boxes, det_elapse = self.text_detector(img)
- if dt_boxes is None or len(dt_boxes) < 1:
+ if use_det and not use_cls and not use_rec:
+ # only det
+ dt_boxes, det_elapse, img_crop_list = self.auto_text_det(img)
+ if dt_boxes is None or img_crop_list is None:
return None, None
- if self.print_verbose:
- print(f"dt_boxes num: {len(dt_boxes)}, elapse: {det_elapse}")
+ det_res = [box.tolist() for box in dt_boxes]
+ return det_res, [det_elapse]
+
+ if not use_det and use_cls and not use_rec:
+ # only cls
+ img, cls_res, cls_elapse = self.text_cls(img)
+ return cls_res, [cls_elapse]
- dt_boxes = self.sorted_boxes(dt_boxes)
- img_crop_list = self.get_crop_img_list(img, dt_boxes)
+ if not use_det and not use_cls and use_rec:
+ # only rec
+ rec_res, rec_elapse = self.text_rec(img)
+ rec_res = [[res[0], res[1]] for res in rec_res]
+ return rec_res, [rec_elapse]
+
+ if use_det and use_cls and use_rec:
+ # det + cls + rec
+ dt_boxes, det_elapse, img_crop_list = self.auto_text_det(img)
+ if dt_boxes is None or img_crop_list is None:
+ return None, None
- cls_elapse = 0.0
- if self.use_angle_cls:
img_crop_list, _, cls_elapse = self.text_cls(img_crop_list)
+ rec_res, rec_elapse = self.text_rec(img_crop_list)
+ dt_boxes, rec_res = self.filter_result(dt_boxes, rec_res)
+ if dt_boxes is None and rec_res is None:
+ return None, None
- if self.print_verbose:
- print(f"cls num: {len(img_crop_list)}, elapse: {cls_elapse}")
+ ocr_res = [
+ [box.tolist(), res[0], res[1]] for box, res in zip(dt_boxes, rec_res)
+ ]
+ return ocr_res, [det_elapse, cls_elapse, rec_elapse]
- rec_res, rec_elapse = self.text_recognizer(img_crop_list)
- if self.print_verbose:
- print(f"rec_res num: {len(rec_res)}, elapse: {rec_elapse}")
+ if use_det and not use_cls and use_rec:
+ # det + rec
+ dt_boxes, det_elapse, img_crop_list = self.auto_text_det(img)
+ if dt_boxes is None or img_crop_list is None:
+ return None, None
- filter_boxes, filter_rec_res = self.filter_boxes_rec_by_score(dt_boxes, rec_res)
- fina_result = [
- [dt.tolist(), rec[0], str(rec[1])]
- for dt, rec in zip(filter_boxes, filter_rec_res)
- ]
- if fina_result:
- return fina_result, [det_elapse, cls_elapse, rec_elapse]
- return None, None
+ rec_res, rec_elapse = self.text_rec(img_crop_list)
+ dt_boxes, rec_res = self.filter_result(dt_boxes, rec_res)
+ if dt_boxes is None and rec_res is None:
+ return None, None
- @staticmethod
- def init_module(module_name, class_name):
- module_part = importlib.import_module(module_name)
- return getattr(module_part, class_name)
+ ocr_res = [
+ [box.tolist(), res[0], res[1]] for box, res in zip(dt_boxes, rec_res)
+ ]
+ return ocr_res, [det_elapse, rec_elapse]
+
+ if not use_det and use_cls and use_rec:
+ # cls + rec
+ img, cls_res, cls_elapse = self.text_cls(img)
+ rec_res, rec_elapse = self.text_rec(img)
+ ocr_res = [[res[0], res[1]] for res in rec_res]
+ return ocr_res, [cls_elapse, rec_elapse]
+
+ def auto_text_det(
+ self,
+ img: np.ndarray,
+ ) -> Tuple[Optional[np.ndarray], float, Optional[List[np.ndarray]]]:
+ h, w = img.shape[:2]
+ if self.width_height_ratio == -1:
+ use_limit_ratio = False
+ else:
+ use_limit_ratio = w / h > self.width_height_ratio
+
+ if not self.use_det or h <= self.min_height or use_limit_ratio:
+ dt_boxes, img_crop_list = self.get_boxes_img_without_det(img, h, w)
+ return dt_boxes, 0.0, img_crop_list
+
+ dt_boxes, det_elapse = self.text_det(img)
+ if dt_boxes is None or len(dt_boxes) < 1:
+ return None, 0.0, None
+
+ dt_boxes = self.sorted_boxes(dt_boxes)
+ img_crop_list = self.get_crop_img_list(img, dt_boxes)
+ return dt_boxes, det_elapse, img_crop_list
def get_boxes_img_without_det(self, img, h, w):
x0, y0, x1, y1 = 0, 0, w, h
@@ -181,13 +233,16 @@ class RapidOCR:
break
return _boxes
- def filter_boxes_rec_by_score(self, dt_boxes, rec_res):
+ def filter_result(self, dt_boxes, rec_res):
filter_boxes, filter_rec_res = [], []
for box, rec_reuslt in zip(dt_boxes, rec_res):
text, score = rec_reuslt
- if score >= self.text_score:
+ if float(score) >= self.text_score:
filter_boxes.append(box)
filter_rec_res.append(rec_reuslt)
+
+ if len(filter_boxes) <= 0:
+ return None, None
return filter_boxes, filter_rec_res
@@ -195,7 +250,9 @@ def main():
args = init_args()
ocr_engine = RapidOCR(**vars(args))
- result, elapse_list = ocr_engine(args.img_path)
+ result, elapse_list = ocr_engine(
+ args.img_path, use_det=args.use_det, use_cls=args.use_cls, use_rec=args.use_rec
+ )
print(result)
if args.print_cost:
print(elapse_list)
diff --git a/python/rapidocr_openvino/utils.py b/python/rapidocr_openvino/utils.py
index b5d6983..ad78cdc 100644
--- a/python/rapidocr_openvino/utils.py
+++ b/python/rapidocr_openvino/utils.py
@@ -155,8 +155,9 @@ def init_args():
global_group = parser.add_argument_group(title="Global")
global_group.add_argument("--text_score", type=float, default=0.5)
- global_group.add_argument("--use_angle_cls", type=bool, default=True)
- global_group.add_argument("--use_text_det", type=bool, default=True)
+ global_group.add_argument("--use_det", type=bool, default=True)
+ global_group.add_argument("--use_cls", type=bool, default=True)
+ global_group.add_argument("--use_rec", type=bool, default=True)
global_group.add_argument("--print_verbose", type=bool, default=False)
global_group.add_argument("--min_height", type=int, default=30)
global_group.add_argument("--width_height_ratio", type=int, default=8)
diff --git a/python/requirements_ort.txt b/python/requirements_ort.txt
new file mode 100644
index 0000000..4111d1f
--- /dev/null
+++ b/python/requirements_ort.txt
@@ -0,0 +1,8 @@
+pyclipper>=1.2.0
+onnxruntime>=1.7.0
+opencv_python>=4.5.1.48
+numpy>=1.19.5
+six>=1.15.0
+Shapely>=1.7.1
+PyYAML
+Pillow
diff --git a/python/requirements.txt b/python/requirements_vino.txt
similarity index 56%
rename from python/requirements.txt
rename to python/requirements_vino.txt
index de13753..881bbd3 100644
--- a/python/requirements.txt
+++ b/python/requirements_vino.txt
@@ -1,13 +1,8 @@
pyclipper>=1.2.0
-Shapely>=1.7.1
+openvino>=2022.2.0
opencv_python>=4.5.1.48
-six>=1.15.0
numpy>=1.19.5
-Pillow
+six>=1.15.0
+Shapely>=1.7.1
PyYAML
-pytest>=7.2.1
-pip==22.3.1
-onnxruntime>=1.11.0
-openvino>=2022.2.0
-wheel
-get_pypi_latest_version
\ No newline at end of file
+Pillow
\ No newline at end of file
diff --git a/python/setup_onnxruntime.py b/python/setup_onnxruntime.py
index 71a2d85..91d5832 100644
--- a/python/setup_onnxruntime.py
+++ b/python/setup_onnxruntime.py
@@ -3,11 +3,18 @@
# @Contact: [email protected]
import sys
from pathlib import Path
+from typing import List, Union
import setuptools
from get_pypi_latest_version import GetPyPiLatestVersion
+def read_txt(txt_path: Union[Path, str]) -> List[str]:
+ with open(txt_path, "r", encoding="utf-8") as f:
+ data = [v.rstrip("\n") for v in f]
+ return data
+
+
def get_readme():
root_dir = Path(__file__).resolve().parent.parent
readme_path = str(root_dir / "docs" / "doc_whl_rapidocr_ort.md")
@@ -30,6 +37,10 @@ if len(sys.argv) > 2:
VERSION_NUM = matched_versions
sys.argv = sys.argv[:2]
+project_urls = {
+ "Documentation": "https://rapidai.github.io/RapidOCRDocs/docs/install_usage/rapidocr/rapidocr_onnxruntime/",
+}
+
setuptools.setup(
name=MODULE_NAME,
version=VERSION_NUM,
@@ -40,18 +51,10 @@ setuptools.setup(
author="SWHL",
author_email="[email protected]",
url="https://github.com/RapidAI/RapidOCR",
+ project_urls=project_urls,
license="Apache-2.0",
include_package_data=True,
- install_requires=[
- "pyclipper>=1.2.1",
- "onnxruntime>=1.7.0",
- "opencv_python>=4.5.1.48",
- "numpy>=1.19.3",
- "six>=1.15.0",
- "Shapely>=1.7.1",
- "PyYAML",
- "Pillow",
- ],
+ install_requires=read_txt("requirements_ort.txt"),
package_dir={"": MODULE_NAME},
packages=setuptools.find_namespace_packages(where=MODULE_NAME),
package_data={"": ["*.onnx", "*.yaml"]},
@@ -68,6 +71,6 @@ setuptools.setup(
],
python_requires=">=3.6,<3.12",
entry_points={
- "console_scripts": [f"{MODULE_NAME}={MODULE_NAME}.rapid_ocr_api:main"],
+ "console_scripts": [f"{MODULE_NAME}={MODULE_NAME}.main:main"],
},
)
diff --git a/python/setup_openvino.py b/python/setup_openvino.py
index 6431c93..107e4ac 100644
--- a/python/setup_openvino.py
+++ b/python/setup_openvino.py
@@ -3,11 +3,18 @@
# @Contact: [email protected]
import sys
from pathlib import Path
+from typing import List, Union
import setuptools
from get_pypi_latest_version import GetPyPiLatestVersion
+def read_txt(txt_path: Union[Path, str]) -> List[str]:
+ with open(txt_path, "r", encoding="utf-8") as f:
+ data = [v.rstrip("\n") for v in f]
+ return data
+
+
def get_readme():
root_dir = Path(__file__).resolve().parent.parent
readme_path = str(root_dir / "docs" / "doc_whl_rapidocr_vino.md")
@@ -23,7 +30,6 @@ obtainer = GetPyPiLatestVersion()
latest_version = obtainer(MODULE_NAME)
VERSION_NUM = obtainer.version_add_one(latest_version)
-# 优先提取commit message中的语义化版本号,如无,则自动加1
if len(sys.argv) > 2:
match_str = " ".join(sys.argv[2:])
matched_versions = obtainer.extract_version(match_str)
@@ -31,6 +37,10 @@ if len(sys.argv) > 2:
VERSION_NUM = matched_versions
sys.argv = sys.argv[:2]
+project_urls = {
+ "Documentation": "https://rapidai.github.io/RapidOCRDocs/docs/install_usage/rapidocr/rapidocr_openvino/",
+}
+
setuptools.setup(
name=MODULE_NAME,
version=VERSION_NUM,
@@ -41,18 +51,10 @@ setuptools.setup(
author="SWHL",
author_email="[email protected]",
url="https://github.com/RapidAI/RapidOCR",
+ project_urls=project_urls,
license="Apache-2.0",
include_package_data=True,
- install_requires=[
- "pyclipper>=1.2.1",
- "openvino>=2022.2.0",
- "opencv_python>=4.5.1.48",
- "numpy>=1.19.3",
- "six>=1.15.0",
- "Shapely>=1.7.1",
- "PyYAML",
- "Pillow",
- ],
+ install_requires=read_txt("requirements_vino.txt"),
package_dir={"": MODULE_NAME},
packages=setuptools.find_namespace_packages(where=MODULE_NAME),
package_data={"": ["*.onnx", "*.yaml", "*.txt"]},
@@ -69,6 +71,6 @@ setuptools.setup(
],
python_requires=">=3.6,<3.12",
entry_points={
- "console_scripts": [f"{MODULE_NAME}={MODULE_NAME}.rapid_ocr_api:main"],
+ "console_scripts": [f"{MODULE_NAME}={MODULE_NAME}.main:main"],
},
)
diff --git a/python/tests/test_all_ort.py b/python/tests/test_all_ort.py
index 718610e..5b6ce74 100644
--- a/python/tests/test_all_ort.py
+++ b/python/tests/test_all_ort.py
@@ -9,21 +9,55 @@ import numpy as np
import pytest
root_dir = Path(__file__).resolve().parent.parent
-print(root_dir)
sys.path.append(str(root_dir))
from rapidocr_onnxruntime import LoadImageError, RapidOCR
-rapid_ocr = RapidOCR()
+engine = RapidOCR()
tests_dir = root_dir / "tests" / "test_files"
+img_path = tests_dir / "ch_en_num.jpg"
-def test_normal():
- img_path = tests_dir / "ch_en_num.jpg"
+def test_only_det():
+ result, _ = engine(img_path, use_det=True, use_cls=False, use_rec=False)
+
+ assert len(result) == 18
+ assert result[0][0] == [5.0, 2.0]
+
+
+def test_only_cls():
+ img_path = tests_dir / "text_cls.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=True, use_rec=False)
+ assert len(result) == 1
+ assert result[0][0] == "0"
+
+
+def test_only_rec():
+ img_path = tests_dir / "text_rec.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=False, use_rec=True)
+ assert len(result) == 1
+ assert result[0][0] == "韩国小馆"
+
+
+def test_det_rec():
+ result, _ = engine(img_path, use_det=True, use_cls=False, use_rec=True)
+ assert result[0][1] == "正品促销"
+ assert len(result) == 16
+
+
+def test_cls_rec():
+ img_path = tests_dir / "text_cls.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=True, use_rec=True)
+
+ assert len(result) == 1
+ assert result[0][0] == "韩国小馆"
+
+
+def test_det_cls_rec():
img = cv2.imread(str(img_path))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
- result, _ = rapid_ocr(img)
+ result, _ = engine(img)
assert result[0][1] == "正品促销"
assert len(result) == 16
@@ -31,70 +65,64 @@ def test_normal():
def test_empty():
img = None
with pytest.raises(LoadImageError) as exc_info:
- rapid_ocr(img)
+ engine(img)
raise LoadImageError
assert exc_info.type is LoadImageError
def test_zeros():
img = np.zeros([640, 640, 3], np.uint8)
- result, _ = rapid_ocr(img)
+ result, _ = engine(img)
assert result is None
def test_input_str():
- img_path = tests_dir / "ch_en_num.jpg"
- result, _ = rapid_ocr(str(img_path))
+ result, _ = engine(str(img_path))
assert result[0][1] == "正品促销"
assert len(result) == 16
def test_input_bytes():
- img_path = tests_dir / "ch_en_num.jpg"
with open(img_path, "rb") as f:
- result, _ = rapid_ocr(f.read())
+ result, _ = engine(f.read())
assert result[0][1] == "正品促销"
assert len(result) == 16
def test_input_path():
- img_path = tests_dir / "ch_en_num.jpg"
- result, _ = rapid_ocr(img_path)
+ result, _ = engine(img_path)
assert result[0][1] == "正品促销"
assert len(result) == 16
def test_input_parameters():
img_path = tests_dir / "ch_en_num.jpg"
- rapid_ocr = RapidOCR(text_score=1)
- result, _ = rapid_ocr(img_path)
+ engine = RapidOCR(text_score=1)
+ result, _ = engine(img_path)
assert result is None
def test_input_det_parameters():
- img_path = tests_dir / "ch_en_num.jpg"
with pytest.raises(FileNotFoundError) as exc_info:
- rapid_ocr = RapidOCR(det_model_path="1.onnx")
- result, _ = rapid_ocr(img_path)
+ engine = RapidOCR(det_model_path="1.onnx")
+ result, _ = engine(img_path)
raise FileNotFoundError()
assert exc_info.type is FileNotFoundError
def test_input_cls_parameters():
- img_path = tests_dir / "ch_en_num.jpg"
with pytest.raises(FileNotFoundError) as exc_info:
- rapid_ocr = RapidOCR(cls_model_path="1.onnx")
- result, _ = rapid_ocr(img_path)
+ engine = RapidOCR(cls_model_path="1.onnx")
+ result, _ = engine(img_path)
raise FileNotFoundError()
assert exc_info.type is FileNotFoundError
def test_input_rec_parameters():
- img_path = tests_dir / "ch_en_num.jpg"
with pytest.raises(FileNotFoundError) as exc_info:
- rapid_ocr = RapidOCR(rec_model_path="1.onnx")
- result, _ = rapid_ocr(img_path)
+ engine = RapidOCR(rec_model_path="1.onnx")
+ result, _ = engine(img_path)
raise FileNotFoundError()
assert exc_info.type is FileNotFoundError
@@ -102,19 +130,18 @@ def test_input_rec_parameters():
def test_input_three_ndim_two_channel():
img_npy = tests_dir / "two_dim_image.npy"
image_array = np.load(str(img_npy))
- result, _ = rapid_ocr(image_array)
+ result, _ = engine(image_array)
assert len(result) == 87
def test_input_three_ndim_one_channel():
- img_path = tests_dir / "ch_en_num.jpg"
img = cv2.imread(str(img_path))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = img[:, :, 0]
img = img[..., None] # (H, W, 1)
- result, _ = rapid_ocr(img)
+ result, _ = engine(img)
assert result[0][1] == "正品促销"
assert len(result) == 16
diff --git a/python/tests/test_all_vino.py b/python/tests/test_all_vino.py
index cf74e6a..612fe05 100644
--- a/python/tests/test_all_vino.py
+++ b/python/tests/test_all_vino.py
@@ -13,17 +13,51 @@ sys.path.append(str(root_dir))
from rapidocr_openvino import LoadImageError, RapidOCR
-rapid_ocr = RapidOCR()
-
+engine = RapidOCR()
tests_dir = root_dir / "tests" / "test_files"
+img_path = tests_dir / "ch_en_num.jpg"
+
+
+def test_only_det():
+ result, _ = engine(img_path, use_det=True, use_cls=False, use_rec=False)
+
+ assert len(result) == 18
+ assert result[0][0] == [5.0, 2.0]
+
+
+def test_only_cls():
+ img_path = tests_dir / "text_cls.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=True, use_rec=False)
+ assert len(result) == 1
+ assert result[0][0] == "0"
+
+
+def test_only_rec():
+ img_path = tests_dir / "text_rec.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=False, use_rec=True)
+ assert len(result) == 1
+ assert result[0][0] == "韩国小馆"
+
+
+def test_det_rec():
+ result, _ = engine(img_path, use_det=True, use_cls=False, use_rec=True)
+ assert result[0][1] == "正品促销"
+ assert len(result) == 16
+
+def test_cls_rec():
+ img_path = tests_dir / "text_cls.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=True, use_rec=True)
-def test_normal():
- image_path = tests_dir / "ch_en_num.jpg"
- img = cv2.imread(str(image_path))
+ assert len(result) == 1
+ assert result[0][0] == "韩国小馆"
+
+
+def test_det_cls_rec():
+ img = cv2.imread(str(img_path))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
- result, _ = rapid_ocr(img)
+ result, _ = engine(img)
assert result[0][1] == "正品促销"
assert len(result) == 16
@@ -31,69 +65,83 @@ def test_normal():
def test_empty():
img = None
with pytest.raises(LoadImageError) as exc_info:
- rapid_ocr(img)
+ engine(img)
raise LoadImageError
assert exc_info.type is LoadImageError
def test_zeros():
img = np.zeros([640, 640, 3], np.uint8)
- result, _ = rapid_ocr(img)
+ result, _ = engine(img)
assert result is None
def test_input_str():
- image_path = tests_dir / "ch_en_num.jpg"
- result, _ = rapid_ocr(str(image_path))
+ result, _ = engine(str(img_path))
assert result[0][1] == "正品促销"
assert len(result) == 16
def test_input_bytes():
- image_path = tests_dir / "ch_en_num.jpg"
- with open(image_path, "rb") as f:
- result, _ = rapid_ocr(f.read())
+ with open(img_path, "rb") as f:
+ result, _ = engine(f.read())
assert result[0][1] == "正品促销"
assert len(result) == 16
def test_input_path():
- image_path = tests_dir / "ch_en_num.jpg"
- result, _ = rapid_ocr(image_path)
+ result, _ = engine(img_path)
assert result[0][1] == "正品促销"
assert len(result) == 16
def test_input_parameters():
- image_path = tests_dir / "ch_en_num.jpg"
- rapid_ocr = RapidOCR(text_score=1)
- result, _ = rapid_ocr(image_path)
+ img_path = tests_dir / "ch_en_num.jpg"
+ engine = RapidOCR(text_score=1)
+ result, _ = engine(img_path)
assert result is None
def test_input_det_parameters():
- image_path = tests_dir / "ch_en_num.jpg"
with pytest.raises(FileNotFoundError) as exc_info:
- rapid_ocr = RapidOCR(det_model_path="1.onnx")
- result, _ = rapid_ocr(image_path)
+ engine = RapidOCR(det_model_path="1.onnx")
+ result, _ = engine(img_path)
raise FileNotFoundError()
assert exc_info.type is FileNotFoundError
def test_input_cls_parameters():
- image_path = tests_dir / "ch_en_num.jpg"
with pytest.raises(FileNotFoundError) as exc_info:
- rapid_ocr = RapidOCR(cls_model_path="1.onnx")
- result, _ = rapid_ocr(image_path)
+ engine = RapidOCR(cls_model_path="1.onnx")
+ result, _ = engine(img_path)
raise FileNotFoundError()
assert exc_info.type is FileNotFoundError
def test_input_rec_parameters():
- image_path = tests_dir / "ch_en_num.jpg"
with pytest.raises(FileNotFoundError) as exc_info:
- rapid_ocr = RapidOCR(rec_model_path="1.onnx")
- result, _ = rapid_ocr(image_path)
+ engine = RapidOCR(rec_model_path="1.onnx")
+ result, _ = engine(img_path)
raise FileNotFoundError()
assert exc_info.type is FileNotFoundError
+
+
+def test_input_three_ndim_two_channel():
+ img_npy = tests_dir / "two_dim_image.npy"
+ image_array = np.load(str(img_npy))
+ result, _ = engine(image_array)
+
+ assert len(result) == 87
+
+
+def test_input_three_ndim_one_channel():
+ img = cv2.imread(str(img_path))
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
+ img = img[:, :, 0]
+ img = img[..., None] # (H, W, 1)
+
+ result, _ = engine(img)
+
+ assert result[0][1] == "正品促销"
+ assert len(result) == 16