analyse_dataset.py 3.0 KB

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