log_util.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import numpy as np
  2. import torch
  3. from matplotlib import pyplot as plt
  4. from libs.vision_libs.utils import draw_bounding_boxes
  5. from models.wirenet.postprocess import postprocess
  6. from torchvision import transforms
  7. def show_line(img, pred, epoch, writer):
  8. im = img.permute(1, 2, 0)
  9. writer.add_image("ori", im, epoch, dataformats="HWC")
  10. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), pred[0]["boxes"],
  11. colors="yellow", width=1)
  12. writer.add_image("boxes", boxed_image.permute(1, 2, 0), epoch, dataformats="HWC")
  13. PLTOPTS = {"color": "#33FFFF", "s": 15, "edgecolors": "none", "zorder": 5}
  14. H = pred[1]['wires']
  15. lines = H["lines"][0].cpu().numpy() / 128 * im.shape[:2]
  16. scores = H["score"][0].cpu().numpy()
  17. for i in range(1, len(lines)):
  18. if (lines[i] == lines[0]).all():
  19. lines = lines[:i]
  20. scores = scores[:i]
  21. break
  22. # postprocess lines to remove overlapped lines
  23. diag = (im.shape[0] ** 2 + im.shape[1] ** 2) ** 0.5
  24. nlines, nscores = postprocess(lines, scores, diag * 0.01, 0, False)
  25. for i, t in enumerate([0.8]):
  26. plt.gca().set_axis_off()
  27. plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
  28. plt.margins(0, 0)
  29. for (a, b), s in zip(nlines, nscores):
  30. if s < t:
  31. continue
  32. plt.plot([a[1], b[1]], [a[0], b[0]], c=c(s), linewidth=2, zorder=s)
  33. plt.scatter(a[1], a[0], **PLTOPTS)
  34. plt.scatter(b[1], b[0], **PLTOPTS)
  35. plt.gca().xaxis.set_major_locator(plt.NullLocator())
  36. plt.gca().yaxis.set_major_locator(plt.NullLocator())
  37. plt.imshow(im)
  38. plt.tight_layout()
  39. fig = plt.gcf()
  40. fig.canvas.draw()
  41. image_from_plot = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8).reshape(
  42. fig.canvas.get_width_height()[::-1] + (3,))
  43. plt.close()
  44. img2 = transforms.ToTensor()(image_from_plot)
  45. writer.add_image("output", img2, epoch)