utils.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # !/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. ################################################################################
  4. #
  5. # Copyright (c) 2024 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ################################################################################
  8. """
  9. Author: PaddlePaddle Authors
  10. """
  11. import codecs
  12. import yaml
  13. from ....utils import logging
  14. from ...base.predictor.transforms import image_common
  15. def read_pre_transforms_from_file(config_path):
  16. """ read_pre_transforms_from_file """
  17. def _process_incompct_args(cfg, arg_names, action):
  18. for name in arg_names:
  19. if name in cfg:
  20. if action == 'ignore':
  21. logging.warning(f"Ignoring incompatible argument: {name}")
  22. elif action == 'raise':
  23. raise RuntimeError(
  24. f"Incompatible argument detected: {name}")
  25. else:
  26. raise ValueError(f"Unknown action: {action}")
  27. with codecs.open(config_path, 'r', 'utf-8') as file:
  28. dic = yaml.load(file, Loader=yaml.FullLoader)
  29. tfs_cfg = dic['Deploy']['transforms']
  30. tfs = []
  31. for cfg in tfs_cfg:
  32. if cfg['type'] == 'Normalize':
  33. tf = image_common.Normalize(
  34. mean=cfg.get('mean', 0.5), std=cfg.get('std', 0.5))
  35. elif cfg['type'] == 'Resize':
  36. tf = image_common.Resize(
  37. target_size=cfg.get('target_size', (512, 512)),
  38. keep_ratio=cfg.get('keep_ratio', False),
  39. size_divisor=cfg.get('size_divisor', None),
  40. interp=cfg.get('interp', 'LINEAR'))
  41. elif cfg['type'] == 'ResizeByLong':
  42. tf = image_common.ResizeByLong(
  43. target_long_edge=cfg['long_size'],
  44. size_divisor=None,
  45. interp='LINEAR')
  46. elif cfg['type'] == 'ResizeByShort':
  47. _process_incompct_args(cfg, ['max_size'], action='raise')
  48. tf = image_common.ResizeByShort(
  49. target_short_edge=cfg['short_size'],
  50. size_divisor=None,
  51. interp='LINEAR')
  52. elif cfg['type'] == 'Padding':
  53. _process_incompct_args(
  54. cfg, ['label_padding_value'], action='ignore')
  55. tf = image_common.Pad(target_size=cfg['target_size'],
  56. val=cfg.get('im_padding_value', 127.5))
  57. else:
  58. raise RuntimeError(f"Unsupported type: {cfg['type']}")
  59. tfs.append(tf)
  60. return tfs