predictor.py 6.6 KB

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