cal_tp_fp.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # coding: utf8
  2. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # 环境变量配置,用于控制是否使用GPU
  16. # 说明文档:https://paddlex.readthedocs.io/zh_CN/develop/appendix/parameters.html#gpu
  17. import argparse
  18. import os
  19. os.environ['CUDA_VISIBLE_DEVICES'] = '0'
  20. import os.path as osp
  21. import numpy as np
  22. import matplotlib
  23. matplotlib.use('Agg')
  24. import matplotlib.pyplot as plt
  25. import paddlex as pdx
  26. def cal_image_level_recall_rate(model, dataset_dir):
  27. """计算置信度(Score)在[0, 1]内以间隔0.01递增取值时,模型在有目标的图像上的图片级召回率。
  28. 图片级召回率:只要在有目标的图片上检测出目标(不论框的个数),该图片被认为召回,
  29. 批量有目标图片中被召回的图片所占的比例,即为图片级别的召回率。
  30. Args:
  31. model (PaddleX model object): 已加载的PaddleX模型。
  32. dataset_dir (str):数据集路径。
  33. Returns:
  34. numpy.array: 形状为101x1的数组,对应置信度从0到1按0.01递增取值时,计算所得图片级别的召回率。
  35. """
  36. print(
  37. "Begin to calculate image-level recall rate of positive images. Please wait for a moment..."
  38. )
  39. file_list = osp.join(dataset_dir, 'val_list.txt')
  40. tp = np.zeros((101, 1))
  41. positive_num = 0
  42. with open(file_list, 'r') as fr:
  43. while True:
  44. line = fr.readline()
  45. if not line:
  46. break
  47. img_file, xml_file = [osp.join(dataset_dir, x) \
  48. for x in line.strip().split()[:2]]
  49. if not osp.exists(img_file):
  50. continue
  51. if not osp.exists(xml_file):
  52. continue
  53. positive_num += 1
  54. results = model.predict(img_file)
  55. scores = list()
  56. for res in results:
  57. scores.append(res['score'])
  58. if len(scores) > 0:
  59. tp[0:int(np.round(max(scores) / 0.01)), 0] += 1
  60. tp = tp / positive_num
  61. return tp
  62. def cal_image_level_false_positive_rate(model, negative_dir):
  63. """计算置信度(Score)在[0, 1]内以间隔0.01递增取值时,模型在无目标的图像上的图片级误检率。
  64. 图片级误检率:只要在无目标的图片上检测出目标(不论框的个数),该图片被认为误检,
  65. 批量无目标图片中被误检的图片所占的比例,即为图片级别的误检率。
  66. Args:
  67. model (PaddleX model object): 已加载的PaddleX模型。
  68. negative_dir (str):无目标图片的文件夹路径。
  69. Returns:
  70. numpy.array: 形状为101x1的数组,对应置信度从0到1按0.01递增取值时,计算所得图片级别的误检率。
  71. """
  72. print(
  73. "Begin to calculate image-level false positive rate of negative(background) images. Please wait for a moment..."
  74. )
  75. fp = np.zeros((101, 1))
  76. negative_num = 0
  77. for file in os.listdir(negative_dir):
  78. file = osp.join(negative_dir, file)
  79. results = model.predict(file)
  80. negative_num += 1
  81. scores = list()
  82. for res in results:
  83. scores.append(res['score'])
  84. if len(scores) > 0:
  85. fp[0:int(np.round(max(scores) / 0.01)), 0] += 1
  86. fp = fp / negative_num
  87. return fp
  88. def result2textfile(tp_list, fp_list, save_dir):
  89. """将不同置信度阈值下的图片级召回率和图片级误检率保存为文本文件。
  90. 文本文件中内容按照| 置信度阈值 | 图片级召回率 | 图片级误检率 |的格式保存。
  91. Args:
  92. tp_list (numpy.array): 形状为101x1的数组,对应置信度从0到1按0.01递增取值时,计算所得图片级别的召回率。
  93. fp_list (numpy.array): 形状为101x1的数组,对应置信度从0到1按0.01递增取值时,计算所得图片级别的误检率。
  94. save_dir (str): 文本文件的保存路径。
  95. """
  96. tp_fp_list_file = osp.join(save_dir, 'tp_fp_list.txt')
  97. with open(tp_fp_list_file, 'w') as f:
  98. f.write("| score | recall rate | false-positive rate |\n")
  99. f.write("| -- | -- | -- |\n")
  100. for i in range(100):
  101. f.write("| {:2f} | {:2f} | {:2f} |\n".format(0.01 * i, tp_list[
  102. i, 0], fp_list[i, 0]))
  103. print("The numerical score-recall_rate-false_positive_rate is saved as {}".
  104. format(tp_fp_list_file))
  105. def result2imagefile(tp_list, fp_list, save_dir):
  106. """将不同置信度阈值下的图片级召回率和图片级误检率保存为图片。
  107. 图片中左子图横坐标表示不同置信度阈值下计算得到的图片级召回率,纵坐标表示各图片级召回率对应的图片级误检率。
  108. 右边子图横坐标表示图片级召回率,纵坐标表示各图片级召回率对应的置信度阈值。
  109. Args:
  110. tp_list (numpy.array): 形状为101x1的数组,对应置信度从0到1按0.01递增取值时,计算所得图片级别的召回率。
  111. fp_list (numpy.array): 形状为101x1的数组,对应置信度从0到1按0.01递增取值时,计算所得图片级别的误检率。
  112. save_dir (str): 文本文件的保存路径。
  113. """
  114. plt.subplot(1, 2, 1)
  115. plt.title("image-level false_positive-recall")
  116. plt.xlabel("recall")
  117. plt.ylabel("false_positive")
  118. plt.xlim(0, 1)
  119. plt.ylim(0, 1)
  120. plt.grid(linestyle='--', linewidth=1)
  121. plt.plot([0, 1], [0, 1], 'r--', linewidth=1)
  122. my_x_ticks = np.arange(0, 1, 0.1)
  123. my_y_ticks = np.arange(0, 1, 0.1)
  124. plt.xticks(my_x_ticks, fontsize=5)
  125. plt.yticks(my_y_ticks, fontsize=5)
  126. plt.plot(tp_list, fp_list, color='b', label="image level", linewidth=1)
  127. plt.legend(loc="lower left", fontsize=5)
  128. plt.subplot(1, 2, 2)
  129. plt.title("score-recall")
  130. plt.xlabel('recall')
  131. plt.ylabel('score')
  132. plt.xlim(0, 1)
  133. plt.ylim(0, 1)
  134. plt.grid(linestyle='--', linewidth=1)
  135. plt.xticks(my_x_ticks, fontsize=5)
  136. plt.yticks(my_y_ticks, fontsize=5)
  137. plt.plot(
  138. tp_list,
  139. np.arange(0, 1.01, 0.01),
  140. color='b',
  141. label="image level",
  142. linewidth=1)
  143. plt.legend(loc="lower left", fontsize=5)
  144. tp_fp_chart_file = os.path.join(save_dir, "image-level_tp_fp.png")
  145. plt.savefig(tp_fp_chart_file, dpi=800)
  146. plt.close()
  147. print(
  148. "The diagrammatic score-recall_rate-false_positive_rate is saved as {}".
  149. format(tp_fp_chart_file))
  150. if __name__ == '__main__':
  151. parser = argparse.ArgumentParser(description=__doc__)
  152. parser.add_argument(
  153. "--model_dir",
  154. default="./output/faster_rcnn_r50_vd_dcn/best_model/",
  155. type=str,
  156. help="The model directory path.")
  157. parser.add_argument(
  158. "--dataset_dir",
  159. default="./aluminum_inspection",
  160. type=str,
  161. help="The VOC-format dataset directory path.")
  162. parser.add_argument(
  163. "--background_image_dir",
  164. default="./aluminum_inspection/val_wu_xia_ci",
  165. type=str,
  166. help="The directory path of background images.")
  167. parser.add_argument(
  168. "--save_dir",
  169. default="./visualize/faster_rcnn_r50_vd_dcn",
  170. type=str,
  171. help="The directory path of result.")
  172. args = parser.parse_args()
  173. if not osp.exists(args.save_dir):
  174. os.makedirs(args.save_dir)
  175. model = pdx.load_model(args.model_dir)
  176. tp_list = cal_image_level_recall_rate(model, args.dataset_dir)
  177. fp_list = cal_image_level_false_positive_rate(model,
  178. args.background_image_dir)
  179. result2textfile(tp_list, fp_list, args.save_dir)
  180. result2imagefile(tp_list, fp_list, args.save_dir)