refinenet.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """
  2. Copyright (c) 2019-present NAVER Corp.
  3. MIT License
  4. """
  5. # -*- coding: utf-8 -*-
  6. import torch
  7. import torch.nn as nn
  8. import torch.nn.functional as F
  9. from torch.autograd import Variable
  10. from .basenet.vgg16_bn import init_weights
  11. from .utils import copyStateDict
  12. class RefineNet(nn.Module):
  13. def __init__(self):
  14. super(RefineNet, self).__init__()
  15. self.last_conv = nn.Sequential(
  16. nn.Conv2d(34, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True),
  17. nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True),
  18. nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True)
  19. )
  20. self.aspp1 = nn.Sequential(
  21. nn.Conv2d(64, 128, kernel_size=3, dilation=6, padding=6), nn.BatchNorm2d(128), nn.ReLU(inplace=True),
  22. nn.Conv2d(128, 128, kernel_size=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True),
  23. nn.Conv2d(128, 1, kernel_size=1)
  24. )
  25. self.aspp2 = nn.Sequential(
  26. nn.Conv2d(64, 128, kernel_size=3, dilation=12, padding=12), nn.BatchNorm2d(128), nn.ReLU(inplace=True),
  27. nn.Conv2d(128, 128, kernel_size=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True),
  28. nn.Conv2d(128, 1, kernel_size=1)
  29. )
  30. self.aspp3 = nn.Sequential(
  31. nn.Conv2d(64, 128, kernel_size=3, dilation=18, padding=18), nn.BatchNorm2d(128), nn.ReLU(inplace=True),
  32. nn.Conv2d(128, 128, kernel_size=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True),
  33. nn.Conv2d(128, 1, kernel_size=1)
  34. )
  35. self.aspp4 = nn.Sequential(
  36. nn.Conv2d(64, 128, kernel_size=3, dilation=24, padding=24), nn.BatchNorm2d(128), nn.ReLU(inplace=True),
  37. nn.Conv2d(128, 128, kernel_size=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True),
  38. nn.Conv2d(128, 1, kernel_size=1)
  39. )
  40. init_weights(self.last_conv.modules())
  41. init_weights(self.aspp1.modules())
  42. init_weights(self.aspp2.modules())
  43. init_weights(self.aspp3.modules())
  44. init_weights(self.aspp4.modules())
  45. def forward(self, y, upconv4):
  46. refine = torch.cat([y.permute(0,3,1,2), upconv4], dim=1)
  47. refine = self.last_conv(refine)
  48. aspp1 = self.aspp1(refine)
  49. aspp2 = self.aspp2(refine)
  50. aspp3 = self.aspp3(refine)
  51. aspp4 = self.aspp4(refine)
  52. #out = torch.add([aspp1, aspp2, aspp3, aspp4], dim=1)
  53. out = aspp1 + aspp2 + aspp3 + aspp4
  54. return out.permute(0, 2, 3, 1) # , refine.permute(0,2,3,1)
  55. def init_refiner_model(chekpoint_path: str, device: torch.device) -> RefineNet:
  56. refine_net = RefineNet()
  57. refine_net.load_state_dict(copyStateDict(torch.load(chekpoint_path, map_location=torch.device('cpu'))))
  58. refine_net = refine_net.to(device)
  59. refine_net.eval()
  60. return refine_net