utils.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. def read_pre_transforms_from_file(config_path):
  19. """ read_pre_transforms_from_file """
  20. def _process_incompct_args(cfg, arg_names, action):
  21. for name in arg_names:
  22. if name in cfg:
  23. if action == 'ignore':
  24. logging.warning(f"Ignoring incompatible argument: {name}")
  25. elif action == 'raise':
  26. raise RuntimeError(
  27. f"Incompatible argument detected: {name}")
  28. else:
  29. raise ValueError(f"Unknown action: {action}")
  30. with codecs.open(config_path, 'r', 'utf-8') as file:
  31. dic = yaml.load(file, Loader=yaml.FullLoader)
  32. tfs_cfg = dic['Deploy']['transforms']
  33. tfs = []
  34. for cfg in tfs_cfg:
  35. if cfg['type'] == 'Normalize':
  36. tf = image_common.Normalize(
  37. mean=cfg.get('mean', 0.5), std=cfg.get('std', 0.5))
  38. elif cfg['type'] == 'Resize':
  39. tf = image_common.Resize(
  40. target_size=cfg.get('target_size', (512, 512)),
  41. keep_ratio=cfg.get('keep_ratio', False),
  42. size_divisor=cfg.get('size_divisor', None),
  43. interp=cfg.get('interp', 'LINEAR'))
  44. elif cfg['type'] == 'ResizeByLong':
  45. tf = image_common.ResizeByLong(
  46. target_long_edge=cfg['long_size'],
  47. size_divisor=None,
  48. interp='LINEAR')
  49. elif cfg['type'] == 'ResizeByShort':
  50. _process_incompct_args(cfg, ['max_size'], action='raise')
  51. tf = image_common.ResizeByShort(
  52. target_short_edge=cfg['short_size'],
  53. size_divisor=None,
  54. interp='LINEAR')
  55. elif cfg['type'] == 'Padding':
  56. _process_incompct_args(
  57. cfg, ['label_padding_value'], action='ignore')
  58. tf = image_common.Pad(target_size=cfg['target_size'],
  59. val=cfg.get('im_padding_value', 127.5))
  60. else:
  61. raise RuntimeError(f"Unsupported type: {cfg['type']}")
  62. tfs.append(tf)
  63. return tfs