analyse_dataset.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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, dataset_type="ShiTuRec"):
  28. """class analysis for dataset"""
  29. tags = ["train", "gallery", "query"]
  30. tags_info = dict()
  31. for tag in tags:
  32. anno_path = os.path.join(dataset_path, f"{tag}.txt")
  33. with custom_open(anno_path, "r") as f:
  34. lines = f.readlines()
  35. lines = [line.strip("\n").split(" ") for line in lines]
  36. num_images = len(lines)
  37. num_labels = len(set([int(line[1]) for line in lines]))
  38. tags_info[tag] = {
  39. "num_images": num_images,
  40. "num_labels": num_labels,
  41. }
  42. categories = list(tags_info.keys())
  43. num_images = [tags_info[category]['num_images'] for category in categories]
  44. num_labels = [tags_info[category]['num_labels'] for category in categories]
  45. # bar
  46. os_system = platform.system().lower()
  47. if os_system == "windows":
  48. plt.rcParams["font.sans-serif"] = "FangSong"
  49. else:
  50. font = font_manager.FontProperties(fname=PINGFANG_FONT_FILE_PATH, size=10)
  51. x = np.arange(len(categories)) # 标签位置
  52. width = 0.35 # 每个条形的宽度
  53. fig, ax = plt.subplots()
  54. rects1 = ax.bar(x - width/2, num_images, width, label="Num Images")
  55. rects2 = ax.bar(x + width/2, num_labels, width, label="Num Classes")
  56. # 添加一些文本标签
  57. ax.set_xlabel("集合", fontproperties=None if os_system == "windows" else font)
  58. ax.set_ylabel("数量", fontproperties=None if os_system == "windows" else font)
  59. ax.set_title("不同集合的图片和类别数量", fontproperties=None if os_system == "windows" else font)
  60. ax.set_xticks(x, fontproperties=None if os_system == "windows" else font)
  61. ax.set_xticklabels(categories)
  62. ax.legend()
  63. # 在条形图上添加数值标签
  64. def autolabel(rects):
  65. """Attach a text label above each bar in *rects*, displaying its height."""
  66. for rect in rects:
  67. height = rect.get_height()
  68. ax.annotate('{}'.format(height),
  69. xy=(rect.get_x() + rect.get_width() / 2, height),
  70. xytext=(0, 3), # 3 points vertical offset
  71. textcoords="offset points",
  72. ha="center", va="bottom")
  73. autolabel(rects1)
  74. autolabel(rects2)
  75. fig.tight_layout()
  76. file_path = os.path.join(output, "histogram.png")
  77. fig.savefig(file_path, dpi=300)
  78. return {"histogram": os.path.join("check_dataset", "histogram.png")}