utils.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 ...base.predictor.transforms import image_common
  14. from . import transforms as T
  15. class InnerConfig(object):
  16. """Inner Config
  17. """
  18. def __init__(self, config_path):
  19. self.inner_cfg = self.load(config_path)
  20. def load(self, config_path):
  21. """ load infer config """
  22. with codecs.open(config_path, 'r', 'utf-8') as file:
  23. dic = yaml.load(file, Loader=yaml.FullLoader)
  24. return dic
  25. @property
  26. def pre_transforms(self):
  27. """ read preprocess transforms from config file """
  28. if "RecPreProcess" in list(self.inner_cfg.keys()):
  29. tfs_cfg = self.inner_cfg['RecPreProcess']['transform_ops']
  30. else:
  31. tfs_cfg = self.inner_cfg['PreProcess']['transform_ops']
  32. tfs = []
  33. for cfg in tfs_cfg:
  34. tf_key = list(cfg.keys())[0]
  35. if tf_key == 'NormalizeImage':
  36. tf = image_common.Normalize(
  37. mean=cfg['NormalizeImage'].get("mean",
  38. [0.485, 0.456, 0.406]),
  39. std=cfg['NormalizeImage'].get("std", [0.229, 0.224, 0.225]))
  40. elif tf_key == 'ResizeImage':
  41. if "resize_short" in list(cfg[tf_key].keys()):
  42. tf = image_common.ResizeByShort(
  43. target_short_edge=cfg['ResizeImage'].get("resize_short",
  44. 224),
  45. size_divisor=None,
  46. interp='LINEAR')
  47. else:
  48. tf = image_common.Resize(
  49. target_size=cfg['ResizeImage'].get('size', (224, 224)))
  50. elif tf_key == "CropImage":
  51. tf = image_common.Crop(crop_size=cfg["CropImage"].get('size',
  52. 224))
  53. elif tf_key == "ToCHWImage":
  54. tf = image_common.ToCHWImage()
  55. else:
  56. raise RuntimeError(f"Unsupported type: {tf_key}")
  57. tfs.append(tf)
  58. return tfs
  59. @property
  60. def post_transforms(self):
  61. """ read postprocess transforms from config file """
  62. IGNORE_OPS = ['main_indicator', 'SavePreLabel']
  63. tfs_cfg = self.inner_cfg['PostProcess']
  64. tfs = []
  65. for tf_key in tfs_cfg:
  66. if tf_key == 'Topk':
  67. tf = T.Topk(
  68. topk=tfs_cfg['Topk']['topk'],
  69. class_ids=tfs_cfg['Topk'].get('label_list', None))
  70. elif tf_key in IGNORE_OPS:
  71. continue
  72. else:
  73. raise RuntimeError(f"Unsupported type: {tf_key}")
  74. tfs.append(tf)
  75. return tfs
  76. @property
  77. def labels(self):
  78. """ the labels in inner config """
  79. return self.inner_cfg['PostProcess']['Topk'].get('label_list', None)