predictor.py 3.7 KB

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