utils.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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(f"Incompatible argument detected: {name}")
  27. else:
  28. raise ValueError(f"Unknown action: {action}")
  29. with codecs.open(config_path, "r", "utf-8") as file:
  30. dic = yaml.load(file, Loader=yaml.FullLoader)
  31. tfs_cfg = dic["Deploy"]["transforms"]
  32. tfs = []
  33. for cfg in tfs_cfg:
  34. if cfg["type"] == "Normalize":
  35. tf = image_common.Normalize(
  36. mean=cfg.get("mean", 0.5), std=cfg.get("std", 0.5)
  37. )
  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. )
  45. elif cfg["type"] == "ResizeByLong":
  46. tf = image_common.ResizeByLong(
  47. target_long_edge=cfg["long_size"], size_divisor=None, interp="LINEAR"
  48. )
  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"], size_divisor=None, interp="LINEAR"
  53. )
  54. elif cfg["type"] == "Padding":
  55. _process_incompct_args(cfg, ["label_padding_value"], action="ignore")
  56. tf = image_common.Pad(
  57. target_size=cfg["target_size"], val=cfg.get("im_padding_value", 127.5)
  58. )
  59. else:
  60. raise RuntimeError(f"Unsupported type: {cfg['type']}")
  61. tfs.append(tf)
  62. return tfs