analyse_dataset.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 platform
  16. from collections import defaultdict
  17. from pathlib import Path
  18. import matplotlib.pyplot as plt
  19. import numpy as np
  20. from matplotlib import font_manager
  21. from pycocotools.coco import COCO
  22. from .....utils.fonts import PINGFANG_FONT_FILE_PATH
  23. def deep_analyse(dataset_dir, output):
  24. """class analysis for dataset"""
  25. tags = ['train', 'val']
  26. all_instances = 0
  27. for tag in tags:
  28. annotations_path = os.path.abspath(
  29. os.path.join(dataset_dir, f'annotations/instance_{tag}.json'))
  30. labels_cnt = defaultdict(list)
  31. coco = COCO(annotations_path)
  32. cat_ids = coco.getCatIds()
  33. for cat_id in cat_ids:
  34. cat_name = coco.loadCats(ids=cat_id)[0]["name"]
  35. labels_cnt[cat_name] = labels_cnt[cat_name] + coco.getAnnIds(
  36. catIds=cat_id)
  37. all_instances += len(labels_cnt[cat_name])
  38. if tag == 'train':
  39. cnts_train = [
  40. len(cat_ids) for cat_name, cat_ids in labels_cnt.items()
  41. ]
  42. elif tag == 'val':
  43. cnts_val = [
  44. len(cat_ids) for cat_name, cat_ids in labels_cnt.items()
  45. ]
  46. classes = [cat_name for cat_name, cat_ids in labels_cnt.items()]
  47. sorted_id = sorted(
  48. range(len(cnts_train)), key=lambda k: cnts_train[k], reverse=True)
  49. cnts_train_sorted = sorted(cnts_train, reverse=True)
  50. cnts_val_sorted = [cnts_val[index] for index in sorted_id]
  51. classes_sorted = [classes[index] for index in sorted_id]
  52. x = np.arange(len(classes))
  53. width = 0.5
  54. # bar
  55. os_system = platform.system().lower()
  56. if os_system == "windows":
  57. plt.rcParams['font.sans-serif'] = 'FangSong'
  58. else:
  59. font = font_manager.FontProperties(fname=PINGFANG_FONT_FILE_PATH)
  60. fig, ax = plt.subplots(figsize=(max(8, int(len(classes) / 5)), 5), dpi=120)
  61. ax.bar(x, cnts_train_sorted, width=0.5, label='train')
  62. ax.bar(x + width, cnts_val_sorted, width=0.5, label='val')
  63. plt.xticks(
  64. x + width / 2,
  65. classes_sorted,
  66. rotation=90,
  67. fontproperties=None if os_system == "windows" else font)
  68. ax.set_ylabel('Counts')
  69. plt.legend()
  70. fig.tight_layout()
  71. fig_path = os.path.join(output, "histogram.png")
  72. fig.savefig(fig_path)
  73. return {"histogram": os.path.join("check_dataset", "histogram.png")}