predictor.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 os
  15. import numpy as np
  16. from ....utils import logging
  17. from ...base import BasePredictor
  18. from ...base.predictor.transforms import image_common
  19. from . import transforms as T
  20. from .keys import DetKeys as K
  21. from .utils import InnerConfig
  22. from ..support_models import SUPPORT_MODELS
  23. class DetPredictor(BasePredictor):
  24. """ Detection Predictor """
  25. support_models = SUPPORT_MODELS
  26. def load_other_src(self):
  27. """ load the inner config file """
  28. infer_cfg_file_path = os.path.join(self.model_dir, 'inference.yml')
  29. if not os.path.exists(infer_cfg_file_path):
  30. raise FileNotFoundError(
  31. f"Cannot find config file: {infer_cfg_file_path}")
  32. return InnerConfig(infer_cfg_file_path)
  33. @classmethod
  34. def get_input_keys(cls):
  35. """ get input keys """
  36. return [[K.IMAGE], [K.IMAGE_PATH]]
  37. @classmethod
  38. def get_output_keys(cls):
  39. """ get output keys """
  40. return [K.BOXES]
  41. def _run(self, batch_input):
  42. """ run """
  43. input_dict = {}
  44. input_dict["image"] = np.stack(
  45. [data[K.IMAGE] for data in batch_input], axis=0).astype(
  46. dtype=np.float32, copy=False)
  47. input_dict["scale_factor"] = np.stack(
  48. [data[K.SCALE_FACTOR][::-1] for data in batch_input],
  49. axis=0).astype(
  50. dtype=np.float32, copy=False)
  51. input_dict["im_shape"] = np.stack(
  52. [data[K.IMAGE_SHAPE][::-1] for data in batch_input], axis=0).astype(
  53. dtype=np.float32, copy=False)
  54. input_ = [input_dict[i] for i in self._predictor.get_input_names()]
  55. batch_np_boxes, batch_np_boxes_num = self._predictor.predict(input_)
  56. pred = batch_input
  57. box_idx_start = 0
  58. for idx in range(len(batch_input)):
  59. np_boxes_num = batch_np_boxes_num[idx]
  60. box_idx_end = box_idx_start + np_boxes_num
  61. np_boxes = batch_np_boxes[box_idx_start:box_idx_end]
  62. box_idx_start = box_idx_end
  63. batch_input[idx][K.BOXES] = np_boxes
  64. return pred
  65. def _get_pre_transforms_for_data(self, data):
  66. """ get preprocess transforms """
  67. if K.IMAGE not in data:
  68. if K.IMAGE_PATH not in data:
  69. raise KeyError(
  70. f"Key {repr(K.IMAGE_PATH)} is required, but not found.")
  71. logging.info(
  72. f"Transformation operators for data preprocessing will be inferred from config file."
  73. )
  74. pre_transforms = self.other_src.pre_transforms
  75. pre_transforms.insert(0, image_common.ReadImage(format='RGB'))
  76. else:
  77. raise RuntimeError(
  78. f"`{self.__class__.__name__}` does not have default transformation operators to preprocess the input. "
  79. f"Please set `pre_transforms` when using the {repr(K.IMAGE)} key in input dict."
  80. )
  81. pre_transforms.insert(0, T.LoadLabels(self.other_src.labels))
  82. return pre_transforms
  83. def _get_post_transforms_for_data(self, data):
  84. """ get postprocess transforms """
  85. if data.get('cli_flag', False):
  86. output_dir = data.get("output_dir", "./")
  87. return [T.SaveDetResults(output_dir), T.PrintResult()]
  88. return []