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. )
  27. from ..base import BasePredictor
  28. from .processors import DetResizeForTest, NormalizeImage, DBPostProcess
  29. from .result import TextDetResult
  30. class TextDetPredictor(BasePredictor):
  31. entities = MODELS
  32. _FUNC_MAP = {}
  33. register = FuncRegister(_FUNC_MAP)
  34. def __init__(
  35. self,
  36. limit_side_len: Union[int, None] = None,
  37. limit_type: Union[str, None] = None,
  38. thresh: Union[float, None] = None,
  39. box_thresh: Union[float, None] = None,
  40. unclip_ratio: Union[float, None] = None,
  41. input_shape=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.input_shape = input_shape
  52. self.pre_tfs, self.infer, self.post_op = self._build()
  53. def _build_batch_sampler(self):
  54. return ImageBatchSampler()
  55. def _get_result_class(self):
  56. return TextDetResult
  57. def _build(self):
  58. pre_tfs = {"Read": ReadImage(format="RGB")}
  59. for cfg in self.config["PreProcess"]["transform_ops"]:
  60. tf_key = list(cfg.keys())[0]
  61. func = self._FUNC_MAP[tf_key]
  62. args = cfg.get(tf_key, {})
  63. name, op = func(self, **args) if args else func(self)
  64. if op:
  65. pre_tfs[name] = op
  66. pre_tfs["ToBatch"] = ToBatch()
  67. infer = self.create_static_infer()
  68. post_op = self.build_postprocess(**self.config["PostProcess"])
  69. return pre_tfs, infer, post_op
  70. def process(
  71. self,
  72. batch_data: List[Union[str, np.ndarray]],
  73. limit_side_len: Union[int, None] = None,
  74. limit_type: Union[str, None] = None,
  75. thresh: Union[float, None] = None,
  76. box_thresh: Union[float, None] = None,
  77. unclip_ratio: Union[float, None] = None,
  78. ):
  79. batch_raw_imgs = self.pre_tfs["Read"](imgs=batch_data.instances)
  80. batch_imgs, batch_shapes = self.pre_tfs["Resize"](
  81. imgs=batch_raw_imgs,
  82. limit_side_len=limit_side_len or self.limit_side_len,
  83. limit_type=limit_type or self.limit_type,
  84. )
  85. batch_imgs = self.pre_tfs["Normalize"](imgs=batch_imgs)
  86. batch_imgs = self.pre_tfs["ToCHW"](imgs=batch_imgs)
  87. x = self.pre_tfs["ToBatch"](imgs=batch_imgs)
  88. batch_preds = self.infer(x=x)
  89. polys, scores = self.post_op(
  90. batch_preds,
  91. batch_shapes,
  92. thresh=thresh or self.thresh,
  93. box_thresh=box_thresh or self.box_thresh,
  94. unclip_ratio=unclip_ratio or self.unclip_ratio,
  95. )
  96. return {
  97. "input_path": batch_data.input_paths,
  98. "page_index": batch_data.page_indexes,
  99. "input_img": batch_raw_imgs,
  100. "dt_polys": polys,
  101. "dt_scores": scores,
  102. }
  103. @register("DecodeImage")
  104. def build_readimg(self, channel_first, img_mode):
  105. assert channel_first == False
  106. return "Read", ReadImage(format=img_mode)
  107. @register("DetResizeForTest")
  108. def build_resize(
  109. self,
  110. limit_side_len: Union[int, None] = None,
  111. limit_type: Union[str, None] = None,
  112. **kwargs
  113. ):
  114. # TODO: align to PaddleOCR
  115. if self.model_name in (
  116. "PP-OCRv4_server_det",
  117. "PP-OCRv4_mobile_det",
  118. "PP-OCRv3_server_det",
  119. "PP-OCRv3_mobile_det",
  120. ):
  121. limit_side_len = self.limit_side_len or kwargs.get("resize_long", 960)
  122. limit_type = self.limit_type or kwargs.get("limit_type", "max")
  123. else:
  124. limit_side_len = self.limit_side_len or kwargs.get("resize_long", 736)
  125. limit_type = self.limit_type or kwargs.get("limit_type", "min")
  126. return "Resize", DetResizeForTest(
  127. limit_side_len=limit_side_len,
  128. limit_type=limit_type,
  129. input_shape=self.input_shape,
  130. **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