utils.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 codecs
  15. import yaml
  16. from ....utils import logging
  17. from ...base.predictor.transforms import image_common
  18. from .transforms import SaveDetResults, PadStride, DetResize, Pad
  19. class InnerConfig(object):
  20. """Inner Config"""
  21. def __init__(self, config_path):
  22. self.inner_cfg = self.load(config_path)
  23. def load(self, config_path):
  24. """ load infer config """
  25. with codecs.open(config_path, 'r', 'utf-8') as file:
  26. dic = yaml.load(file, Loader=yaml.FullLoader)
  27. return dic
  28. @property
  29. def pre_transforms(self):
  30. """ read preprocess transforms from config file """
  31. tfs_cfg = self.inner_cfg["Preprocess"]
  32. tfs = []
  33. for cfg in tfs_cfg:
  34. if cfg['type'] == 'NormalizeImage':
  35. mean = cfg.get('mean', 0.5)
  36. std = cfg.get('std', 0.5)
  37. scale = 1. / 255. if cfg.get('is_scale', True) else 1
  38. norm_type = cfg.get('norm_type', "mean_std")
  39. if norm_type != "mean_std":
  40. mean = 0
  41. std = 1
  42. tf = image_common.Normalize(mean=mean, std=std, scale=scale)
  43. elif cfg['type'] == 'Resize':
  44. interp = cfg.get('interp', 'LINEAR')
  45. if isinstance(interp, int):
  46. interp = {
  47. 0: 'NEAREST',
  48. 1: 'LINEAR',
  49. 2: 'CUBIC',
  50. 3: 'AREA',
  51. 4: 'LANCZOS4'
  52. }[interp]
  53. tf = DetResize(
  54. target_hw=cfg['target_size'],
  55. keep_ratio=cfg.get('keep_ratio', True),
  56. interp=interp)
  57. elif cfg['type'] == 'Permute':
  58. tf = image_common.ToCHWImage()
  59. elif cfg['type'] == 'PadStride':
  60. stride = cfg.get('stride', 32)
  61. tf = PadStride(stride=stride)
  62. elif cfg['type'] == 'Pad':
  63. fill_value = cfg.get('fill_value', [114.0, 114.0, 114.0])
  64. size = cfg.get('size', [640, 640])
  65. tf = Pad(size=size, fill_value=fill_value)
  66. else:
  67. raise RuntimeError(f"Unsupported type: {cfg['type']}")
  68. tfs.append(tf)
  69. return tfs
  70. @property
  71. def labels(self):
  72. """ the labels in inner config """
  73. return self.inner_cfg["label_list"]