utils.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # copyright (c) 2020 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 os
  15. import os.path as osp
  16. from PIL import Image
  17. import numpy as np
  18. import json
  19. class MyEncoder(json.JSONEncoder):
  20. # 调整json文件存储形式
  21. def default(self, obj):
  22. if isinstance(obj, np.integer):
  23. return int(obj)
  24. elif isinstance(obj, np.floating):
  25. return float(obj)
  26. elif isinstance(obj, np.ndarray):
  27. return obj.tolist()
  28. else:
  29. return super(MyEncoder, self).default(obj)
  30. def list_files(dirname):
  31. """ 列出目录下所有文件(包括所属的一级子目录下文件)
  32. Args:
  33. dirname: 目录路径
  34. """
  35. def filter_file(f):
  36. if f.startswith('.'):
  37. return True
  38. return False
  39. all_files = list()
  40. dirs = list()
  41. for f in os.listdir(dirname):
  42. if filter_file(f):
  43. continue
  44. if osp.isdir(osp.join(dirname, f)):
  45. dirs.append(f)
  46. else:
  47. all_files.append(f)
  48. for d in dirs:
  49. for f in os.listdir(osp.join(dirname, d)):
  50. if filter_file(f):
  51. continue
  52. if osp.isdir(osp.join(dirname, d, f)):
  53. continue
  54. all_files.append(osp.join(d, f))
  55. return all_files
  56. def is_pic(filename):
  57. """ 判断文件是否为图片格式
  58. Args:
  59. filename: 文件路径
  60. """
  61. suffixes = {'JPEG', 'jpeg', 'JPG', 'jpg', 'BMP', 'bmp', 'PNG', 'png'}
  62. suffix = filename.strip().split('.')[-1]
  63. if suffix not in suffixes:
  64. return False
  65. return True
  66. def replace_ext(filename, new_ext):
  67. """ 替换文件后缀
  68. Args:
  69. filename: 文件路径
  70. new_ext: 需要替换的新的后缀
  71. """
  72. items = filename.split(".")
  73. items[-1] = new_ext
  74. new_filename = ".".join(items)
  75. return new_filename
  76. def read_seg_ann(pngfile):
  77. """ 解析语义分割的标注png图片
  78. Args:
  79. pngfile: 包含标注信息的png图片路径
  80. """
  81. grt = np.asarray(Image.open(pngfile))
  82. labels = list(np.unique(grt))
  83. if 255 in labels:
  84. labels.remove(255)
  85. return labels