rec_resnet_aster.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This code is refer from:
  16. https://github.com/ayumiymk/aster.pytorch/blob/master/lib/models/resnet_aster.py
  17. """
  18. import paddle
  19. import paddle.nn as nn
  20. import sys
  21. import math
  22. def conv3x3(in_planes, out_planes, stride=1):
  23. """3x3 convolution with padding"""
  24. return nn.Conv2D(
  25. in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias_attr=False
  26. )
  27. def conv1x1(in_planes, out_planes, stride=1):
  28. """1x1 convolution"""
  29. return nn.Conv2D(
  30. in_planes, out_planes, kernel_size=1, stride=stride, bias_attr=False
  31. )
  32. def get_sinusoid_encoding(n_position, feat_dim, wave_length=10000):
  33. # [n_position]
  34. positions = paddle.arange(0, n_position)
  35. # [feat_dim]
  36. dim_range = paddle.arange(0, feat_dim)
  37. dim_range = paddle.pow(wave_length, 2 * (dim_range // 2) / feat_dim)
  38. # [n_position, feat_dim]
  39. angles = paddle.unsqueeze(positions, axis=1) / paddle.unsqueeze(dim_range, axis=0)
  40. angles = paddle.cast(angles, "float32")
  41. angles[:, 0::2] = paddle.sin(angles[:, 0::2])
  42. angles[:, 1::2] = paddle.cos(angles[:, 1::2])
  43. return angles
  44. class AsterBlock(nn.Layer):
  45. def __init__(self, inplanes, planes, stride=1, downsample=None):
  46. super(AsterBlock, self).__init__()
  47. self.conv1 = conv1x1(inplanes, planes, stride)
  48. self.bn1 = nn.BatchNorm2D(planes)
  49. self.relu = nn.ReLU()
  50. self.conv2 = conv3x3(planes, planes)
  51. self.bn2 = nn.BatchNorm2D(planes)
  52. self.downsample = downsample
  53. self.stride = stride
  54. def forward(self, x):
  55. residual = x
  56. out = self.conv1(x)
  57. out = self.bn1(out)
  58. out = self.relu(out)
  59. out = self.conv2(out)
  60. out = self.bn2(out)
  61. if self.downsample is not None:
  62. residual = self.downsample(x)
  63. out += residual
  64. out = self.relu(out)
  65. return out
  66. class ResNet_ASTER(nn.Layer):
  67. """For aster or crnn"""
  68. def __init__(self, with_lstm=True, n_group=1, in_channels=3):
  69. super(ResNet_ASTER, self).__init__()
  70. self.with_lstm = with_lstm
  71. self.n_group = n_group
  72. self.layer0 = nn.Sequential(
  73. nn.Conv2D(
  74. in_channels,
  75. 32,
  76. kernel_size=(3, 3),
  77. stride=1,
  78. padding=1,
  79. bias_attr=False,
  80. ),
  81. nn.BatchNorm2D(32),
  82. nn.ReLU(),
  83. )
  84. self.inplanes = 32
  85. self.layer1 = self._make_layer(32, 3, [2, 2]) # [16, 50]
  86. self.layer2 = self._make_layer(64, 4, [2, 2]) # [8, 25]
  87. self.layer3 = self._make_layer(128, 6, [2, 1]) # [4, 25]
  88. self.layer4 = self._make_layer(256, 6, [2, 1]) # [2, 25]
  89. self.layer5 = self._make_layer(512, 3, [2, 1]) # [1, 25]
  90. if with_lstm:
  91. self.rnn = nn.LSTM(512, 256, direction="bidirect", num_layers=2)
  92. self.out_channels = 2 * 256
  93. else:
  94. self.out_channels = 512
  95. def _make_layer(self, planes, blocks, stride):
  96. downsample = None
  97. if stride != [1, 1] or self.inplanes != planes:
  98. downsample = nn.Sequential(
  99. conv1x1(self.inplanes, planes, stride), nn.BatchNorm2D(planes)
  100. )
  101. layers = []
  102. layers.append(AsterBlock(self.inplanes, planes, stride, downsample))
  103. self.inplanes = planes
  104. for _ in range(1, blocks):
  105. layers.append(AsterBlock(self.inplanes, planes))
  106. return nn.Sequential(*layers)
  107. def forward(self, x):
  108. x0 = self.layer0(x)
  109. x1 = self.layer1(x0)
  110. x2 = self.layer2(x1)
  111. x3 = self.layer3(x2)
  112. x4 = self.layer4(x3)
  113. x5 = self.layer5(x4)
  114. cnn_feat = x5.squeeze(2) # [N, c, w]
  115. cnn_feat = paddle.transpose(cnn_feat, perm=[0, 2, 1])
  116. if self.with_lstm:
  117. rnn_feat, _ = self.rnn(cnn_feat)
  118. return rnn_feat
  119. else:
  120. return cnn_feat