box_distribution.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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 matplotlib.pyplot as plt
  15. import json
  16. import numpy as np
  17. import argparse
  18. from pycocotools.coco import COCO
  19. from tqdm import tqdm
  20. def median(data):
  21. data.sort()
  22. mid = len(data) // 2
  23. median = (data[mid] + data[~mid]) / 2
  24. return median
  25. def draw_distribution(width, height, out_path):
  26. w_bins = int((max(width) - min(width)) // 10)
  27. h_bins = int((max(height) - min(height)) // 10)
  28. plt.figure()
  29. plt.subplot(221)
  30. plt.hist(width, bins=w_bins, color='green')
  31. plt.xlabel('Width rate *1000')
  32. plt.ylabel('number')
  33. plt.title('Distribution of Width')
  34. plt.subplot(222)
  35. plt.hist(height, bins=h_bins, color='blue')
  36. plt.xlabel('Height rate *1000')
  37. plt.title('Distribution of Height')
  38. plt.savefig(out_path)
  39. print(f'Distribution saved as {out_path}')
  40. plt.show()
  41. def get_ratio_infos(jsonfile, out_img, eval_size, small_stride):
  42. coco = COCO(annotation_file=jsonfile)
  43. allannjson = json.load(open(jsonfile, 'r'))
  44. be_im_id = allannjson['annotations'][0]['image_id']
  45. be_im_w = []
  46. be_im_h = []
  47. ratio_w = []
  48. ratio_h = []
  49. im_wid,im_hei=[],[]
  50. for ann in tqdm(allannjson['annotations']):
  51. if ann['iscrowd']:
  52. continue
  53. x0, y0, w, h = ann['bbox'][:]
  54. if be_im_id == ann['image_id']:
  55. be_im_w.append(w)
  56. be_im_h.append(h)
  57. else:
  58. im_w = coco.imgs[be_im_id]['width']
  59. im_h = coco.imgs[be_im_id]['height']
  60. im_wid.append(im_w)
  61. im_hei.append(im_h)
  62. im_m_w = np.mean(be_im_w)
  63. im_m_h = np.mean(be_im_h)
  64. dis_w = im_m_w / im_w
  65. dis_h = im_m_h / im_h
  66. ratio_w.append(dis_w)
  67. ratio_h.append(dis_h)
  68. be_im_id = ann['image_id']
  69. be_im_w = [w]
  70. be_im_h = [h]
  71. im_w = coco.imgs[be_im_id]['width']
  72. im_h = coco.imgs[be_im_id]['height']
  73. im_wid.append(im_w)
  74. im_hei.append(im_h)
  75. all_im_m_w = np.mean(im_wid)
  76. all_im_m_h = np.mean(im_hei)
  77. im_m_w = np.mean(be_im_w)
  78. im_m_h = np.mean(be_im_h)
  79. dis_w = im_m_w / im_w
  80. dis_h = im_m_h / im_h
  81. ratio_w.append(dis_w)
  82. ratio_h.append(dis_h)
  83. mid_w = median(ratio_w)
  84. mid_h = median(ratio_h)
  85. reg_ratio = []
  86. ratio_all = ratio_h + ratio_w
  87. for r in ratio_all:
  88. if r < 0.2:
  89. reg_ratio.append(r)
  90. elif r < 0.4:
  91. reg_ratio.append(r/2)
  92. else:
  93. reg_ratio.append(r/4)
  94. reg_ratio = sorted(reg_ratio)
  95. max_ratio = reg_ratio[int(0.95*len(reg_ratio))]
  96. reg_max = round(max_ratio*eval_size/small_stride)
  97. ratio_w = [i * 1000 for i in ratio_w]
  98. ratio_h = [i * 1000 for i in ratio_h]
  99. print(f'Suggested reg_range[1] is {reg_max+1}' )
  100. print(f'Mean of all img_w is {all_im_m_w}')
  101. print(f'Mean of all img_h is {all_im_m_h}')
  102. print(f'Median of ratio_w is {mid_w}')
  103. print(f'Median of ratio_h is {mid_h}')
  104. print('all_img with box: ', len(ratio_h))
  105. print('all_ann: ', len(allannjson['annotations']))
  106. draw_distribution(ratio_w, ratio_h, out_img)
  107. def main():
  108. parser = argparse.ArgumentParser()
  109. parser.add_argument(
  110. '--json_path', type=str, default=None, help="Dataset json path.")
  111. parser.add_argument(
  112. '--eval_size', type=int, default=640, help="eval size.")
  113. parser.add_argument(
  114. '--small_stride', type=int, default=8, help="smallest stride.")
  115. parser.add_argument(
  116. '--out_img',
  117. type=str,
  118. default='box_distribution.jpg',
  119. help="Name of distibution img.")
  120. args = parser.parse_args()
  121. get_ratio_infos(args.json_path, args.out_img, args.eval_size, args.small_stride)
  122. if __name__ == "__main__":
  123. main()