loss_utils.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #
  2. # Copyright (C) 2023, Inria
  3. # GRAPHDECO research group, https://team.inria.fr/graphdeco
  4. # All rights reserved.
  5. #
  6. # This software is free for non-commercial, research and evaluation use
  7. # under the terms of the LICENSE.md file.
  8. #
  9. # For inquiries contact george.drettakis@inria.fr
  10. #
  11. import torch
  12. import torch.nn.functional as F
  13. from torch.autograd import Variable
  14. from math import exp
  15. def l1_loss(network_output, gt):
  16. return torch.abs((network_output - gt)).mean()
  17. def l2_loss(network_output, gt):
  18. return ((network_output - gt) ** 2).mean()
  19. def gaussian(window_size, sigma):
  20. gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
  21. return gauss / gauss.sum()
  22. def create_window(window_size, channel):
  23. _1D_window = gaussian(window_size, 1.5).unsqueeze(1)
  24. _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
  25. window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())
  26. return window
  27. def ssim(img1, img2, window_size=11, size_average=True):
  28. channel = img1.size(-3)
  29. window = create_window(window_size, channel)
  30. if img1.is_cuda:
  31. window = window.cuda(img1.get_device())
  32. window = window.type_as(img1)
  33. return _ssim(img1, img2, window, window_size, channel, size_average)
  34. def _ssim(img1, img2, window, window_size, channel, size_average=True):
  35. mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)
  36. mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)
  37. mu1_sq = mu1.pow(2)
  38. mu2_sq = mu2.pow(2)
  39. mu1_mu2 = mu1 * mu2
  40. sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq
  41. sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq
  42. sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2
  43. C1 = 0.01 ** 2
  44. C2 = 0.03 ** 2
  45. ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
  46. if size_average:
  47. return ssim_map.mean()
  48. else:
  49. return ssim_map.mean(1).mean(1).mean(1)