analyse_dataset.py 3.4 KB

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