craft.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 basenet.vgg16_bn import vgg16_bn, init_weights
  10. class double_conv(nn.Module):
  11. def __init__(self, in_ch, mid_ch, out_ch):
  12. super(double_conv, self).__init__()
  13. self.conv = nn.Sequential(
  14. nn.Conv2d(in_ch + mid_ch, mid_ch, kernel_size=1),
  15. nn.BatchNorm2d(mid_ch),
  16. nn.ReLU(inplace=True),
  17. nn.Conv2d(mid_ch, out_ch, kernel_size=3, padding=1),
  18. nn.BatchNorm2d(out_ch),
  19. nn.ReLU(inplace=True)
  20. )
  21. def forward(self, x):
  22. x = self.conv(x)
  23. return x
  24. class CRAFT(nn.Module):
  25. def __init__(self, pretrained=False, freeze=False):
  26. super(CRAFT, self).__init__()
  27. """ Base network """
  28. self.basenet = vgg16_bn(pretrained, freeze)
  29. """ U network """
  30. self.upconv1 = double_conv(1024, 512, 256)
  31. self.upconv2 = double_conv(512, 256, 128)
  32. self.upconv3 = double_conv(256, 128, 64)
  33. self.upconv4 = double_conv(128, 64, 32)
  34. num_class = 2
  35. self.conv_cls = nn.Sequential(
  36. nn.Conv2d(32, 32, kernel_size=3, padding=1), nn.ReLU(inplace=True),
  37. nn.Conv2d(32, 32, kernel_size=3, padding=1), nn.ReLU(inplace=True),
  38. nn.Conv2d(32, 16, kernel_size=3, padding=1), nn.ReLU(inplace=True),
  39. nn.Conv2d(16, 16, kernel_size=1), nn.ReLU(inplace=True),
  40. nn.Conv2d(16, num_class, kernel_size=1),
  41. )
  42. init_weights(self.upconv1.modules())
  43. init_weights(self.upconv2.modules())
  44. init_weights(self.upconv3.modules())
  45. init_weights(self.upconv4.modules())
  46. init_weights(self.conv_cls.modules())
  47. def forward(self, x):
  48. """ Base network """
  49. sources = self.basenet(x)
  50. """ U network """
  51. y = torch.cat([sources[0], sources[1]], dim=1)
  52. y = self.upconv1(y)
  53. y = F.interpolate(y, size=sources[2].size()[2:], mode='bilinear', align_corners=False)
  54. y = torch.cat([y, sources[2]], dim=1)
  55. y = self.upconv2(y)
  56. y = F.interpolate(y, size=sources[3].size()[2:], mode='bilinear', align_corners=False)
  57. y = torch.cat([y, sources[3]], dim=1)
  58. y = self.upconv3(y)
  59. y = F.interpolate(y, size=sources[4].size()[2:], mode='bilinear', align_corners=False)
  60. y = torch.cat([y, sources[4]], dim=1)
  61. feature = self.upconv4(y)
  62. y = self.conv_cls(feature)
  63. return y.permute(0,2,3,1), feature
  64. if __name__ == '__main__':
  65. model = CRAFT(pretrained=True).cuda()
  66. output, _ = model(torch.randn(1, 3, 768, 768).cuda())
  67. print(output.shape)