text_recognition.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. from ...utils.func_register import FuncRegister
  16. from ...modules.text_recognition.model_list import MODELS
  17. from ..components import *
  18. from ..results import TextRecResult
  19. from ..utils.process_hook import batchable_method
  20. from .base import CVPredictor
  21. class TextRecPredictor(CVPredictor):
  22. entities = MODELS
  23. _FUNC_MAP = {}
  24. register = FuncRegister(_FUNC_MAP)
  25. def _build_components(self):
  26. for cfg in self.config["PreProcess"]["transform_ops"]:
  27. tf_key = list(cfg.keys())[0]
  28. assert tf_key in self._FUNC_MAP
  29. func = self._FUNC_MAP[tf_key]
  30. args = cfg.get(tf_key, {})
  31. op = func(self, **args) if args else func(self)
  32. if op:
  33. self._add_component(op)
  34. predictor = ImagePredictor(
  35. model_dir=self.model_dir,
  36. model_prefix=self.MODEL_FILE_PREFIX,
  37. option=self.pp_option,
  38. )
  39. self._add_component(("Predictor", predictor))
  40. op = self.build_postprocess(**self.config["PostProcess"])
  41. self._add_component(op)
  42. @register("DecodeImage")
  43. def build_readimg(self, channel_first, img_mode):
  44. assert channel_first == False
  45. return ReadImage(format=img_mode)
  46. @register("RecResizeImg")
  47. def build_resize(self, image_shape):
  48. return OCRReisizeNormImg(rec_image_shape=image_shape)
  49. def build_postprocess(self, **kwargs):
  50. if kwargs.get("name") == "CTCLabelDecode":
  51. return CTCLabelDecode(
  52. character_list=kwargs.get("character_dict"),
  53. )
  54. else:
  55. raise Exception()
  56. @register("MultiLabelEncode")
  57. def foo(self, *args, **kwargs):
  58. return None
  59. @register("KeepKeys")
  60. def foo(self, *args, **kwargs):
  61. return None
  62. def _pack_res(self, single):
  63. keys = ["img_path", "rec_text", "rec_score"]
  64. return TextRecResult({key: single[key] for key in keys})