utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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 os
  15. import os.path as osp
  16. from PIL import Image
  17. import numpy as np
  18. def list_files(dirname):
  19. """ 列出目录下所有文件(包括所属的一级子目录下文件)
  20. Args:
  21. dirname: 目录路径
  22. """
  23. def filter_file(f):
  24. if f.startswith('.'):
  25. return True
  26. return False
  27. all_files = list()
  28. dirs = list()
  29. for f in os.listdir(dirname):
  30. if filter_file(f):
  31. continue
  32. if osp.isdir(osp.join(dirname, f)):
  33. dirs.append(f)
  34. else:
  35. all_files.append(f)
  36. for d in dirs:
  37. for f in os.listdir(osp.join(dirname, d)):
  38. if filter_file(f):
  39. continue
  40. if osp.isdir(osp.join(dirname, d, f)):
  41. continue
  42. all_files.append(osp.join(d, f))
  43. return all_files
  44. def replace_ext(filename, new_ext):
  45. """ 替换文件后缀
  46. Args:
  47. filename: 文件路径
  48. new_ext: 需要替换的新的后缀
  49. """
  50. items = filename.split(".")
  51. items[-1] = new_ext
  52. new_filename = ".".join(items)
  53. return new_filename
  54. def read_seg_ann(pngfile):
  55. """ 解析语义分割的标注png图片
  56. Args:
  57. pngfile: 包含标注信息的png图片路径
  58. """
  59. grt = np.asarray(Image.open(pngfile))
  60. labels = list(np.unique(grt))
  61. if 255 in labels:
  62. labels.remove(255)
  63. return labels