Skip to content

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

feat: support to_json func (fixed issue #489)

SWHL1a94bb1935e3
diff --git a/python/rapidocr/utils/output.py b/python/rapidocr/utils/output.py
index e129f02..2d7f3f0 100644
--- a/python/rapidocr/utils/output.py
+++ b/python/rapidocr/utils/output.py
@@ -2,11 +2,12 @@
# @Author: SWHL
# @Contact: [email protected]
from dataclasses import dataclass, field
-from typing import List, Optional, Tuple, Union
+from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
from .logger import Logger
+from .to_json import ToJSON
from .to_markdown import ToMarkdown
from .utils import save_img
from .vis_res import VisRes
@@ -35,20 +36,23 @@ class RapidOCROutput:
return 0
return len(self.txts)
- def to_json(self):
- pass
+ def to_json(self) -> Optional[List[Dict[Any, Any]]]:
+ if any(v is None for v in (self.boxes, self.txts, self.scores)):
+ logger.warning("The identified content is empty.")
+ return None
+ return ToJSON.to(self.boxes, self.txts, self.scores)
def to_markdown(self) -> str:
return ToMarkdown.to(self.boxes, self.txts)
- def vis(self, save_path: Optional[str] = None):
+ def vis(self, save_path: Optional[str] = None) -> Optional[np.ndarray]:
if self.img is None or self.boxes is None:
logger.warning("No image or boxes to visualize.")
- return
+ return None
if self.viser is None:
logger.error("vis instance is None")
- return
+ return None
if all(v is None for v in self.word_results):
vis_img = self.viser(self.img, self.boxes, self.txts, self.scores)
diff --git a/python/rapidocr/utils/to_json.py b/python/rapidocr/utils/to_json.py
new file mode 100644
index 0000000..ae4ab7a
--- /dev/null
+++ b/python/rapidocr/utils/to_json.py
@@ -0,0 +1,17 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from typing import Any, Dict, List, Tuple
+
+import numpy as np
+
+
+class ToJSON:
+ @classmethod
+ def to(
+ cls, boxes: np.ndarray, txts: Tuple[str], scores: Tuple[float]
+ ) -> List[Dict[Any, Any]]:
+ results = []
+ for box, txt, score in zip(boxes, txts, scores):
+ results.append({"box": box.tolist(), "txt": txt, "score": score})
+ return results
diff --git a/python/rapidocr/utils/to_markdown.py b/python/rapidocr/utils/to_markdown.py
index d4d79ae..0d5d9db 100644
--- a/python/rapidocr/utils/to_markdown.py
+++ b/python/rapidocr/utils/to_markdown.py
@@ -5,7 +5,6 @@ import numpy as np
class ToMarkdown:
@classmethod
def to(cls, boxes, txts) -> str:
- # def to(cls, result: RapidOCROutput) -> str:
"""
根据 OCR 结果的坐标信息,将文本还原为近似原始排版的 Markdown。