predictor.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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.predictor.transforms import image_common
  18. from ...base import BasePredictor
  19. from .keys import SegKeys as K
  20. from . import transforms as T
  21. from .utils import InnerConfig
  22. from ..support_models import SUPPORT_MODELS
  23. class SegPredictor(BasePredictor):
  24. """ SegPredictor """
  25. support_models = SUPPORT_MODELS
  26. def __init__(self,
  27. model_dir,
  28. kernel_option,
  29. pre_transforms=None,
  30. post_transforms=None,
  31. has_prob_map=False):
  32. super().__init__(
  33. model_dir=model_dir,
  34. kernel_option=kernel_option,
  35. pre_transforms=pre_transforms,
  36. post_transforms=post_transforms)
  37. self.has_prob_map = has_prob_map
  38. def load_other_src(self):
  39. """ load the inner config file """
  40. infer_cfg_file_path = os.path.join(self.model_dir, 'inference.yml')
  41. if not os.path.exists(infer_cfg_file_path):
  42. raise FileNotFoundError(
  43. f"Cannot find config file: {infer_cfg_file_path}")
  44. return InnerConfig(infer_cfg_file_path)
  45. @classmethod
  46. def get_input_keys(cls):
  47. """ get input keys """
  48. return [[K.IMAGE], [K.IM_PATH]]
  49. @classmethod
  50. def get_output_keys(cls):
  51. """ get output keys """
  52. return [K.SEG_MAP]
  53. def _run(self, batch_input):
  54. """ run """
  55. images = [data[K.IMAGE] for data in batch_input]
  56. input_ = np.stack(images, axis=0)
  57. if input_.ndim == 3:
  58. input_ = input_[:, np.newaxis]
  59. input_ = input_.astype(dtype=np.float32, copy=False)
  60. outputs = self._predictor.predict([input_])
  61. out_maps = outputs[0]
  62. # In-place update
  63. pred = batch_input
  64. for dict_, out_map in zip(pred, out_maps):
  65. if self.has_prob_map:
  66. # `out_map` is prob map
  67. dict_[K.PROB_MAP] = out_map
  68. dict_[K.SEG_MAP] = np.argmax(out_map, axis=1)
  69. else:
  70. # `out_map` is seg map
  71. dict_[K.SEG_MAP] = out_map
  72. return pred
  73. def _get_pre_transforms_for_data(self, data):
  74. """ _get_pre_transforms_for_data """
  75. # If `K.IMAGE` (the decoded image) is found, return a default list of
  76. # transformation operators for the input (if possible).
  77. # If `K.IMAGE` (the decoded image) is not found, `K.IM_PATH` (the image
  78. # path) must be contained in the input. In this case, we infer
  79. # transformation operators from the config file.
  80. # In cases where the input contains both `K.IMAGE` and `K.IM_PATH`,
  81. # `K.IMAGE` takes precedence over `K.IM_PATH`.
  82. if K.IMAGE not in data:
  83. if K.IM_PATH not in data:
  84. raise KeyError(
  85. f"Key {repr(K.IM_PATH)} is required, but not found.")
  86. logging.info(
  87. f"Transformation operators for data preprocessing will be inferred from config file."
  88. )
  89. pre_transforms = self.other_src.pre_transforms
  90. pre_transforms.insert(0, image_common.ReadImage())
  91. pre_transforms.append(image_common.ToCHWImage())
  92. else:
  93. raise RuntimeError(
  94. f"`{self.__class__.__name__}` does not have default transformation operators to preprocess the input. "
  95. f"Please set `pre_transforms` when using the {repr(K.IMAGE)} key in input dict."
  96. )
  97. return pre_transforms
  98. def _get_post_transforms_for_data(self, data):
  99. """ _get_post_transforms_for_data """
  100. if data.get('cli_flag', False):
  101. output_dir = data.get("output_dir", "./")
  102. return [T.SaveSegResults(output_dir), T.PrintResult()]
  103. return []