predictor.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. from ....utils.func_register import FuncRegister
  15. from ....modules.text_detection.model_list import MODELS
  16. from ...common.batch_sampler import ImageBatchSampler
  17. from ...common.reader import ReadImage
  18. from ..common import (
  19. Resize,
  20. ResizeByShort,
  21. Normalize,
  22. ToCHWImage,
  23. ToBatch,
  24. StaticInfer,
  25. )
  26. from ..base import BasicPredictor
  27. from .processors import DetResizeForTest, NormalizeImage, DBPostProcess
  28. from .result import TextDetResult
  29. class TextDetPredictor(BasicPredictor):
  30. entities = MODELS
  31. _FUNC_MAP = {}
  32. register = FuncRegister(_FUNC_MAP)
  33. def __init__(self, *args, **kwargs):
  34. super().__init__(*args, **kwargs)
  35. self.pre_tfs, self.infer, self.post_op = self._build()
  36. def _build_batch_sampler(self):
  37. return ImageBatchSampler()
  38. def _get_result_class(self):
  39. return TextDetResult
  40. def _build(self):
  41. pre_tfs = {"Read": ReadImage(format="RGB")}
  42. for cfg in self.config["PreProcess"]["transform_ops"]:
  43. tf_key = list(cfg.keys())[0]
  44. func = self._FUNC_MAP[tf_key]
  45. args = cfg.get(tf_key, {})
  46. name, op = func(self, **args) if args else func(self)
  47. if op:
  48. pre_tfs[name] = op
  49. pre_tfs["ToBatch"] = ToBatch()
  50. infer = StaticInfer(
  51. model_dir=self.model_dir,
  52. model_prefix=self.MODEL_FILE_PREFIX,
  53. option=self.pp_option,
  54. )
  55. post_op = self.build_postprocess(**self.config["PostProcess"])
  56. return pre_tfs, infer, post_op
  57. def process(self, batch_data):
  58. batch_raw_imgs = self.pre_tfs["Read"](imgs=batch_data)
  59. batch_imgs, batch_shapes = self.pre_tfs["Resize"](imgs=batch_raw_imgs)
  60. batch_imgs = self.pre_tfs["Normalize"](imgs=batch_imgs)
  61. batch_imgs = self.pre_tfs["ToCHW"](imgs=batch_imgs)
  62. x = self.pre_tfs["ToBatch"](imgs=batch_imgs)
  63. batch_preds = self.infer(x=x)
  64. polys, scores = self.post_op(batch_preds, batch_shapes)
  65. return {
  66. "input_path": batch_data,
  67. "input_img": batch_raw_imgs,
  68. "dt_polys": polys,
  69. "dt_scores": scores,
  70. }
  71. @register("DecodeImage")
  72. def build_readimg(self, channel_first, img_mode):
  73. assert channel_first == False
  74. return "Read", ReadImage(format=img_mode)
  75. @register("DetResizeForTest")
  76. def build_resize(self, **kwargs):
  77. # TODO: align to PaddleOCR
  78. if self.model_name in ("PP-OCRv4_server_det", "PP-OCRv4_mobile_det"):
  79. resize_long = kwargs.get("resize_long", 960)
  80. return "Resize", DetResizeForTest(
  81. limit_side_len=resize_long, limit_type="max"
  82. )
  83. return "Resize", DetResizeForTest(**kwargs)
  84. @register("NormalizeImage")
  85. def build_normalize(
  86. self,
  87. mean=[0.485, 0.456, 0.406],
  88. std=[0.229, 0.224, 0.225],
  89. scale=1 / 255,
  90. order="",
  91. channel_num=3,
  92. ):
  93. return "Normalize", NormalizeImage(
  94. mean=mean, std=std, scale=scale, order=order, channel_num=channel_num
  95. )
  96. @register("ToCHWImage")
  97. def build_to_chw(self):
  98. return "ToCHW", ToCHWImage()
  99. def build_postprocess(self, **kwargs):
  100. if kwargs.get("name") == "DBPostProcess":
  101. return DBPostProcess(
  102. thresh=kwargs.get("thresh", 0.3),
  103. box_thresh=kwargs.get("box_thresh", 0.7),
  104. max_candidates=kwargs.get("max_candidates", 1000),
  105. unclip_ratio=kwargs.get("unclip_ratio", 2.0),
  106. use_dilation=kwargs.get("use_dilation", False),
  107. score_mode=kwargs.get("score_mode", "fast"),
  108. box_type=kwargs.get("box_type", "quad"),
  109. )
  110. else:
  111. raise Exception()
  112. @register("DetLabelEncode")
  113. def foo(self, *args, **kwargs):
  114. return None, None
  115. @register("KeepKeys")
  116. def foo(self, *args, **kwargs):
  117. return None, None