predictor.py 3.9 KB

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