log_util.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import io
  2. import os
  3. import numpy as np
  4. import torch
  5. from PIL import Image
  6. from matplotlib import pyplot as plt
  7. from libs.vision_libs.utils import draw_bounding_boxes
  8. from models.wirenet.postprocess import postprocess
  9. from torchvision import transforms
  10. import matplotlib as mpl
  11. from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
  12. from io import BytesIO
  13. from PIL import Image
  14. cmap = plt.get_cmap("jet")
  15. norm = mpl.colors.Normalize(vmin=0.4, vmax=1.0)
  16. sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
  17. sm.set_array([])
  18. def c(x):
  19. return sm.to_rgba(x)
  20. def imshow(im):
  21. plt.close()
  22. plt.tight_layout()
  23. plt.imshow(im)
  24. plt.colorbar(sm, fraction=0.046)
  25. plt.xlim([0, im.shape[0]])
  26. plt.ylim([im.shape[0], 0])
  27. def save_last_model(model, save_path, epoch, optimizer=None):
  28. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  29. checkpoint = {
  30. 'epoch': epoch,
  31. 'model_state_dict': model.state_dict(),
  32. }
  33. if optimizer is not None:
  34. checkpoint['optimizer_state_dict'] = optimizer.state_dict()
  35. torch.save(checkpoint, save_path)
  36. def save_best_model(model, save_path, epoch, current_loss, best_loss, optimizer=None):
  37. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  38. if current_loss <= best_loss:
  39. checkpoint = {
  40. 'epoch': epoch,
  41. 'model_state_dict': model.state_dict(),
  42. 'loss': current_loss
  43. }
  44. if optimizer is not None:
  45. checkpoint['optimizer_state_dict'] = optimizer.state_dict()
  46. torch.save(checkpoint, save_path)
  47. print(f"Saved best model at epoch {epoch} with loss {current_loss:.4f}")
  48. return current_loss
  49. return best_loss
  50. # def show_line(img, pred, epoch, writer):
  51. # fig = plt.figure(figsize=(15, 15))
  52. #
  53. # # ... your plotting code here ...
  54. #
  55. # # Save the figure to a BytesIO buffer
  56. # buf = BytesIO()
  57. # plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
  58. # buf.seek(0)
  59. #
  60. # # Load the image from the buffer and convert to numpy array
  61. # image = Image.open(buf)
  62. # image_from_plot = np.array(image)[..., :3] # Keep RGB channels if there's an alpha
  63. #
  64. # # Close the figure to free memory
  65. # plt.close(fig)
  66. #
  67. # # Log the image to TensorBoard or other logger
  68. # writer.add_image('validate', image_from_plot, epoch, dataformats='HWC')
  69. def show_line(img, pred, epoch, writer):
  70. im = img.permute(1, 2, 0)
  71. writer.add_image("z-ori", im, epoch, dataformats="HWC")
  72. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), pred[0]["boxes"],
  73. colors="yellow", width=1)
  74. writer.add_image("z-boxes", boxed_image.permute(1, 2, 0), epoch, dataformats="HWC")
  75. PLTOPTS = {"color": "#33FFFF", "s": 15, "edgecolors": "none", "zorder": 5}
  76. # print(f'pred[1]:{pred[1]}')
  77. H = pred[-1]['wires']
  78. lines = H["lines"][0].cpu().numpy() / 128 * im.shape[:2]
  79. scores = H["score"][0].cpu().numpy()
  80. for i in range(1, len(lines)):
  81. if (lines[i] == lines[0]).all():
  82. lines = lines[:i]
  83. scores = scores[:i]
  84. break
  85. # postprocess lines to remove overlapped lines
  86. diag = (im.shape[0] ** 2 + im.shape[1] ** 2) ** 0.5
  87. nlines, nscores = postprocess(lines, scores, diag * 0.01, 0, False)
  88. for i, t in enumerate([0.85]):
  89. plt.gca().set_axis_off()
  90. plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
  91. plt.margins(0, 0)
  92. for (a, b), s in zip(nlines, nscores):
  93. if s < t:
  94. continue
  95. plt.plot([a[1], b[1]], [a[0], b[0]], c=c(s), linewidth=2, zorder=s)
  96. plt.scatter(a[1], a[0], **PLTOPTS)
  97. plt.scatter(b[1], b[0], **PLTOPTS)
  98. plt.gca().xaxis.set_major_locator(plt.NullLocator())
  99. plt.gca().yaxis.set_major_locator(plt.NullLocator())
  100. plt.imshow(im)
  101. plt.tight_layout()
  102. fig = plt.gcf()
  103. fig.canvas.draw()
  104. width, height = fig.get_size_inches() * fig.get_dpi() # 获取图像尺寸
  105. tmp_img=fig.canvas.tostring_argb()
  106. tmp_img_np=np.frombuffer(tmp_img, dtype=np.uint8)
  107. tmp_img_np=tmp_img_np.reshape(int(height), int(width), 4)
  108. img_rgb = tmp_img_np[:, :, 1:] # 提取RGB部分,忽略Alpha通道
  109. # image_from_plot = np.frombuffer(tmp_img[:,:,1:], dtype=np.uint8).reshape(
  110. # fig.canvas.get_width_height()[::-1] + (3,))
  111. # plt.close()
  112. img2 = transforms.ToTensor()(img_rgb)
  113. writer.add_image("z-output", img2, epoch)