analyse_dataset.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # Copyright (c) 2024 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 platform
  16. from collections import defaultdict
  17. import numpy as np
  18. from .....utils.deps import function_requires_deps, is_dep_available
  19. from .....utils.file_interface import custom_open
  20. from .....utils.fonts import PINGFANG_FONT
  21. if is_dep_available("matplotlib"):
  22. import matplotlib.pyplot as plt
  23. from matplotlib import font_manager
  24. @function_requires_deps("matplotlib")
  25. def deep_analyse(dataset_path, output):
  26. """class analysis for dataset"""
  27. tags = ["train", "val"]
  28. labels_cnt = defaultdict(str)
  29. label_path = os.path.join(dataset_path, "label.txt")
  30. with custom_open(label_path, "r") as f:
  31. lines = f.readlines()
  32. for line in lines:
  33. line = line.strip().split()
  34. labels_cnt[line[0]] = " ".join(line[1:])
  35. for tag in tags:
  36. anno_path = os.path.join(dataset_path, f"{tag}.txt")
  37. classes_num = defaultdict(int)
  38. for i in range(len(labels_cnt)):
  39. classes_num[labels_cnt[str(i)]] = 0
  40. with custom_open(anno_path, "r") as f:
  41. lines = f.readlines()
  42. for line in lines:
  43. line = line.strip().split()
  44. classes_num[labels_cnt[line[1]]] += 1
  45. if tag == "train":
  46. cnts_train = [cat_ids for cat_name, cat_ids in classes_num.items()]
  47. elif tag == "val":
  48. cnts_val = [cat_ids for cat_name, cat_ids in classes_num.items()]
  49. classes = [cat_name for cat_name, cat_ids in classes_num.items()]
  50. sorted_id = sorted(
  51. range(len(cnts_train)), key=lambda k: cnts_train[k], reverse=True
  52. )
  53. cnts_train_sorted = [cnts_train[index] for index in sorted_id]
  54. cnts_val_sorted = [cnts_val[index] for index in sorted_id]
  55. classes_sorted = [classes[index] for index in sorted_id]
  56. x = np.arange(len(classes))
  57. width = 0.5
  58. # bar
  59. os_system = platform.system().lower()
  60. if os_system == "windows":
  61. plt.rcParams["font.sans-serif"] = "FangSong"
  62. else:
  63. font = font_manager.FontProperties(fname=PINGFANG_FONT.path, size=10)
  64. fig, ax = plt.subplots(figsize=(max(8, int(len(classes) / 5)), 5), dpi=300)
  65. ax.bar(x, cnts_train_sorted, width=0.5, label="train")
  66. ax.bar(x + width, cnts_val_sorted, width=0.5, label="val")
  67. plt.xticks(
  68. x + width / 2,
  69. classes_sorted,
  70. rotation=90,
  71. fontproperties=None if os_system == "windows" else font,
  72. )
  73. ax.set_xlabel(
  74. "类别名称", fontproperties=None if os_system == "windows" else font, fontsize=12
  75. )
  76. ax.set_ylabel(
  77. "图片数量", fontproperties=None if os_system == "windows" else font, fontsize=12
  78. )
  79. plt.legend(loc=1)
  80. fig.tight_layout()
  81. file_path = os.path.join(output, "histogram.png")
  82. fig.savefig(file_path, dpi=300)
  83. return {"histogram": os.path.join("check_dataset", "histogram.png")}