DetDbHead.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4. import torch
  5. from torch import nn
  6. class Head(nn.Module):
  7. def __init__(self, in_channels):
  8. super().__init__()
  9. self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=in_channels // 4, kernel_size=3, padding=1,
  10. bias=False)
  11. # self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=in_channels // 4, kernel_size=5, padding=2,
  12. # bias=False)
  13. self.conv_bn1 = nn.BatchNorm2d(in_channels // 4)
  14. self.relu = nn.ReLU(inplace=True)
  15. self.conv2 = nn.ConvTranspose2d(in_channels=in_channels // 4, out_channels=in_channels // 4, kernel_size=2,
  16. stride=2)
  17. self.conv_bn2 = nn.BatchNorm2d(in_channels // 4)
  18. self.conv3 = nn.ConvTranspose2d(in_channels=in_channels // 4, out_channels=1, kernel_size=2, stride=2)
  19. def forward(self, x):
  20. x = self.conv1(x)
  21. x = self.conv_bn1(x)
  22. x = self.relu(x)
  23. x = self.conv2(x)
  24. x = self.conv_bn2(x)
  25. x = self.relu(x)
  26. x = self.conv3(x)
  27. x = torch.sigmoid(x)
  28. return x
  29. def weights_init(m):
  30. import torch.nn.init as init
  31. if isinstance(m, nn.Conv2d):
  32. init.kaiming_normal_(m.weight.data)
  33. if m.bias is not None:
  34. init.normal_(m.bias.data)
  35. elif isinstance(m, nn.ConvTranspose2d):
  36. init.kaiming_normal_(m.weight.data)
  37. if m.bias is not None:
  38. init.normal_(m.bias.data)
  39. elif isinstance(m, nn.BatchNorm2d):
  40. init.normal_(m.weight.data, mean=1, std=0.02)
  41. init.constant_(m.bias.data, 0)
  42. class DBHead(nn.Module):
  43. """
  44. Differentiable Binarization (DB) for text detection:
  45. see https://arxiv.org/abs/1911.08947
  46. args:
  47. params(dict): super parameters for build DB network
  48. """
  49. def __init__(self, in_channels, k=50):
  50. super().__init__()
  51. self.k = k
  52. self.binarize = Head(in_channels)
  53. self.thresh = Head(in_channels)
  54. self.binarize.apply(weights_init)
  55. self.thresh.apply(weights_init)
  56. def step_function(self, x, y):
  57. return torch.reciprocal(1 + torch.exp(-self.k * (x - y)))
  58. def forward(self, x):
  59. shrink_maps = self.binarize(x)
  60. if not self.training:
  61. return shrink_maps
  62. threshold_maps = self.thresh(x)
  63. binary_maps = self.step_function(shrink_maps, threshold_maps)
  64. y = torch.cat((shrink_maps, threshold_maps, binary_maps), dim=1)
  65. return y