analyse_dataset.py 3.1 KB

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