predictor.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 typing import List, Union
  16. from ....utils.func_register import FuncRegister
  17. from ....modules.text_detection.model_list import MODELS
  18. from ...common.batch_sampler import ImageBatchSampler
  19. from ...common.reader import ReadImage
  20. from ..common import (
  21. Resize,
  22. ResizeByShort,
  23. Normalize,
  24. ToCHWImage,
  25. ToBatch,
  26. StaticInfer,
  27. )
  28. from ..base import BasicPredictor
  29. from .processors import DetResizeForTest, NormalizeImage, DBPostProcess
  30. from .result import TextDetResult
  31. class TextDetPredictor(BasicPredictor):
  32. entities = MODELS
  33. _FUNC_MAP = {}
  34. register = FuncRegister(_FUNC_MAP)
  35. def __init__(
  36. self,
  37. limit_side_len: Union[int, None] = None,
  38. limit_type: Union[str, None] = None,
  39. thresh: Union[float, None] = None,
  40. box_thresh: Union[float, None] = None,
  41. unclip_ratio: Union[float, None] = None,
  42. *args,
  43. **kwargs
  44. ):
  45. super().__init__(*args, **kwargs)
  46. self.limit_side_len = limit_side_len
  47. self.limit_type = limit_type
  48. self.thresh = thresh
  49. self.box_thresh = box_thresh
  50. self.unclip_ratio = unclip_ratio
  51. self.pre_tfs, self.infer, self.post_op = self._build()
  52. def _build_batch_sampler(self):
  53. return ImageBatchSampler()
  54. def _get_result_class(self):
  55. return TextDetResult
  56. def _build(self):
  57. pre_tfs = {"Read": ReadImage(format="RGB")}
  58. for cfg in self.config["PreProcess"]["transform_ops"]:
  59. tf_key = list(cfg.keys())[0]
  60. func = self._FUNC_MAP[tf_key]
  61. args = cfg.get(tf_key, {})
  62. name, op = func(self, **args) if args else func(self)
  63. if op:
  64. pre_tfs[name] = op
  65. pre_tfs["ToBatch"] = ToBatch()
  66. infer = StaticInfer(
  67. model_dir=self.model_dir,
  68. model_prefix=self.MODEL_FILE_PREFIX,
  69. option=self.pp_option,
  70. )
  71. post_op = self.build_postprocess(**self.config["PostProcess"])
  72. return pre_tfs, infer, post_op
  73. def process(
  74. self,
  75. batch_data: List[Union[str, np.ndarray]],
  76. limit_side_len: Union[int, None] = None,
  77. limit_type: Union[str, None] = None,
  78. thresh: Union[float, None] = None,
  79. box_thresh: Union[float, None] = None,
  80. unclip_ratio: Union[float, None] = None,
  81. ):
  82. batch_raw_imgs = self.pre_tfs["Read"](imgs=batch_data.instances)
  83. batch_imgs, batch_shapes = self.pre_tfs["Resize"](
  84. imgs=batch_raw_imgs,
  85. limit_side_len=limit_side_len or self.limit_side_len,
  86. limit_type=limit_type or self.limit_type,
  87. )
  88. batch_imgs = self.pre_tfs["Normalize"](imgs=batch_imgs)
  89. batch_imgs = self.pre_tfs["ToCHW"](imgs=batch_imgs)
  90. x = self.pre_tfs["ToBatch"](imgs=batch_imgs)
  91. batch_preds = self.infer(x=x)
  92. polys, scores = self.post_op(
  93. batch_preds,
  94. batch_shapes,
  95. thresh=thresh or self.thresh,
  96. box_thresh=box_thresh or self.box_thresh,
  97. unclip_ratio=unclip_ratio or self.unclip_ratio,
  98. )
  99. return {
  100. "input_path": batch_data.input_paths,
  101. "page_index": batch_data.page_indexes,
  102. "input_img": batch_raw_imgs,
  103. "dt_polys": polys,
  104. "dt_scores": scores,
  105. }
  106. @register("DecodeImage")
  107. def build_readimg(self, channel_first, img_mode):
  108. assert channel_first == False
  109. return "Read", ReadImage(format=img_mode)
  110. @register("DetResizeForTest")
  111. def build_resize(
  112. self,
  113. limit_side_len: Union[int, None] = None,
  114. limit_type: Union[str, None] = None,
  115. **kwargs
  116. ):
  117. # TODO: align to PaddleOCR
  118. if self.model_name in (
  119. "PP-OCRv4_server_det",
  120. "PP-OCRv4_mobile_det",
  121. "PP-OCRv3_server_det",
  122. "PP-OCRv3_mobile_det",
  123. ):
  124. limit_side_len = self.limit_side_len or kwargs.get("resize_long", 960)
  125. limit_type = self.limit_type or kwargs.get("limit_type", "max")
  126. else:
  127. limit_side_len = self.limit_side_len or kwargs.get("resize_long", 736)
  128. limit_type = self.limit_type or kwargs.get("limit_type", "min")
  129. return "Resize", DetResizeForTest(
  130. limit_side_len=limit_side_len, limit_type=limit_type, **kwargs
  131. )
  132. @register("NormalizeImage")
  133. def build_normalize(
  134. self,
  135. mean=[0.485, 0.456, 0.406],
  136. std=[0.229, 0.224, 0.225],
  137. scale=1 / 255,
  138. order="",
  139. channel_num=3,
  140. ):
  141. return "Normalize", NormalizeImage(
  142. mean=mean, std=std, scale=scale, order=order, channel_num=channel_num
  143. )
  144. @register("ToCHWImage")
  145. def build_to_chw(self):
  146. return "ToCHW", ToCHWImage()
  147. def build_postprocess(self, **kwargs):
  148. if kwargs.get("name") == "DBPostProcess":
  149. return DBPostProcess(
  150. thresh=self.thresh or kwargs.get("thresh", 0.3),
  151. box_thresh=self.box_thresh or kwargs.get("box_thresh", 0.6),
  152. unclip_ratio=self.unclip_ratio or kwargs.get("unclip_ratio", 2.0),
  153. max_candidates=kwargs.get("max_candidates", 1000),
  154. use_dilation=kwargs.get("use_dilation", False),
  155. score_mode=kwargs.get("score_mode", "fast"),
  156. box_type=kwargs.get("box_type", "quad"),
  157. )
  158. else:
  159. raise Exception()
  160. @register("DetLabelEncode")
  161. def foo(self, *args, **kwargs):
  162. return None, None
  163. @register("KeepKeys")
  164. def foo(self, *args, **kwargs):
  165. return None, None