draw_pred_result.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import os
  17. import os.path as osp
  18. import cv2
  19. import numpy as np
  20. from PIL import Image
  21. import matplotlib.pyplot as plt
  22. import matplotlib.patches as patches
  23. def visualize_segmented_result(save_path, image_groundtruth, groundtruth,
  24. image_predict, predict, legend):
  25. tail = save_path.split(".")[-1]
  26. save_path = (save_path[:-len(tail)] + "png")
  27. import matplotlib.patches as mpatches
  28. from matplotlib import use
  29. use('Agg')
  30. if image_groundtruth is not None:
  31. image_groundtruth = image_groundtruth[..., ::-1]
  32. image_predict = image_predict[..., ::-1]
  33. if groundtruth is not None:
  34. groundtruth = groundtruth[..., ::-1]
  35. predict = predict[..., ::-1]
  36. fig = plt.figure()
  37. red_patches = []
  38. for key, value in legend.items():
  39. red_patch = mpatches.Patch(
  40. color=[x / 255.0 for x in value[::-1]], label=key)
  41. red_patches.append(red_patch)
  42. plt.legend(
  43. handles=red_patches, bbox_to_anchor=(1.05, 0), loc=3, borderaxespad=0)
  44. plt.axis('off')
  45. if image_groundtruth is not None and \
  46. groundtruth is not None:
  47. left, bottom, width, height = 0.02, 0.51, 0.38, 0.38
  48. fig.add_axes([left, bottom, width, height])
  49. plt.imshow(image_groundtruth)
  50. plt.axis('off')
  51. plt.title("Ground Truth", loc='left')
  52. left, bottom, width, height = 0.52, 0.51, 0.38, 0.38
  53. fig.add_axes([left, bottom, width, height])
  54. plt.imshow(groundtruth)
  55. plt.axis('off')
  56. left, bottom, width, height = 0.01, 0.5, 0.9, 0.45
  57. fig.add_axes([left, bottom, width, height])
  58. currentAxis = plt.gca()
  59. rect = patches.Rectangle(
  60. (0.0, 0.0), 1.0, 1.0, linewidth=1, edgecolor='k', facecolor='none')
  61. currentAxis.add_patch(rect)
  62. plt.axis('off')
  63. left, bottom, width, height = 0.02, 0.06, 0.38, 0.38
  64. fig.add_axes([left, bottom, width, height])
  65. plt.imshow(image_predict)
  66. plt.axis('off')
  67. plt.title("Prediction", loc='left')
  68. left, bottom, width, height = 0.52, 0.06, 0.38, 0.38
  69. fig.add_axes([left, bottom, width, height])
  70. plt.imshow(predict)
  71. plt.axis('off')
  72. left, bottom, width, height = 0.01, 0.05, 0.9, 0.45
  73. fig.add_axes([left, bottom, width, height])
  74. currentAxis = plt.gca()
  75. rect = patches.Rectangle(
  76. (0.0, 0.0), 1.0, 1.0, linewidth=1, edgecolor='k', facecolor='none')
  77. currentAxis.add_patch(rect)
  78. plt.axis('off')
  79. else:
  80. plt.subplot(1, 2, 1)
  81. plt.imshow(image_predict)
  82. plt.axis('off')
  83. plt.title("Combination ", y=-0.12)
  84. plt.subplot(1, 2, 2)
  85. plt.imshow(predict)
  86. plt.axis('off')
  87. plt.title("Prediction", y=-0.12)
  88. plt.savefig(save_path, dpi=200, bbox_inches='tight')
  89. plt.close()
  90. def visualize_detected_result(save_path, image_groundtruth, image_predict):
  91. tail = save_path.split(".")[-1]
  92. save_path = (save_path[:-len(tail)] + "png")
  93. from matplotlib import use
  94. use('Agg')
  95. if image_groundtruth is not None:
  96. plt.subplot(1, 2, 1)
  97. plt.imshow(cv2.cvtColor(image_groundtruth, cv2.COLOR_BGR2RGB))
  98. plt.axis('off')
  99. plt.title("Ground Truth", y=-0.12)
  100. plt.subplot(1, 2, 2)
  101. plt.imshow(cv2.cvtColor(image_predict, cv2.COLOR_BGR2RGB))
  102. plt.axis('off')
  103. plt.title("Prediction", y=-0.12)
  104. else:
  105. plt.subplot(1, 1, 1)
  106. plt.imshow(cv2.cvtColor(image_predict, cv2.COLOR_BGR2RGB))
  107. plt.axis('off')
  108. plt.title("Prediction", y=-0.12)
  109. plt.tight_layout(pad=1.08)
  110. plt.autoscale()
  111. plt.savefig(save_path, dpi=600, bbox_inches='tight')
  112. plt.close()
  113. def visualize_classified_result(save_path, image_predict, res_info):
  114. from matplotlib import use
  115. use('Agg')
  116. if isinstance(image_predict, str):
  117. img = Image.open(image_predict)
  118. name_part = osp.split(image_predict)
  119. filename = name_part[-1]
  120. foldername = osp.split(name_part[-2])[-1]
  121. tail = filename.split(".")[-1]
  122. filename = (foldername + '_' + filename[:-len(tail)] + "png")
  123. elif isinstance(image_predict, np.ndarray):
  124. img = Image.fromarray(cv2.cvtColor(image_predict, cv2.COLOR_BGR2RGB))
  125. filename = "predict_result.png"
  126. if np.array(img).ndim == 3:
  127. cmap = None
  128. else:
  129. cmap = 'gray'
  130. plt.subplot(1, 2, 1)
  131. plt.imshow(img, cmap=cmap)
  132. plt.axis('off')
  133. if "gt_label" in res_info:
  134. plt.title(
  135. "Test Image, Label: {}".format(res_info["gt_label"]), y=-0.15)
  136. else:
  137. plt.title("Test Image", y=-0.15)
  138. plt.subplot(1, 2, 2)
  139. topk = res_info["topk"]
  140. start_height = (topk + 2) // 2 * 10 + 45
  141. plt.text(
  142. 15, start_height, 'Probability of each class:', va='center', ha='left')
  143. for i in range(topk):
  144. if "gt_label" in res_info:
  145. color = "red" if res_info["label"][i] == res_info[
  146. "gt_label"] else "black"
  147. else:
  148. color = 'black'
  149. if i == 0:
  150. color = "green"
  151. plt.text(
  152. 70,
  153. start_height - (i + 1) * 10,
  154. ' {}: {:.4f}'.format(res_info["label"][i],
  155. res_info["score"][i]),
  156. va='center',
  157. ha='right',
  158. color=color)
  159. if "gt_label" in res_info:
  160. plt.text(
  161. 15,
  162. start_height - (topk + 1) * 10,
  163. 'True Label: {}'.format(res_info["gt_label"]),
  164. va='center',
  165. ha='left',
  166. color="black")
  167. plt.axis('off')
  168. plt.axis([0, 100, 0, 100])
  169. plt.gca().set_aspect('equal', adjustable='box')
  170. plt.tight_layout(pad=0.08)
  171. plt.savefig(osp.join(save_path, filename), dpi=200, bbox_inches='tight')
  172. plt.close()