rec_resnet_aster.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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,
  26. out_planes,
  27. kernel_size=3,
  28. stride=stride,
  29. padding=1,
  30. bias_attr=False)
  31. def conv1x1(in_planes, out_planes, stride=1):
  32. """1x1 convolution"""
  33. return nn.Conv2D(
  34. in_planes, out_planes, kernel_size=1, stride=stride, bias_attr=False)
  35. def get_sinusoid_encoding(n_position, feat_dim, wave_length=10000):
  36. # [n_position]
  37. positions = paddle.arange(0, n_position)
  38. # [feat_dim]
  39. dim_range = paddle.arange(0, feat_dim)
  40. dim_range = paddle.pow(wave_length, 2 * (dim_range // 2) / feat_dim)
  41. # [n_position, feat_dim]
  42. angles = paddle.unsqueeze(
  43. positions, axis=1) / paddle.unsqueeze(
  44. dim_range, axis=0)
  45. angles = paddle.cast(angles, "float32")
  46. angles[:, 0::2] = paddle.sin(angles[:, 0::2])
  47. angles[:, 1::2] = paddle.cos(angles[:, 1::2])
  48. return angles
  49. class AsterBlock(nn.Layer):
  50. def __init__(self, inplanes, planes, stride=1, downsample=None):
  51. super(AsterBlock, self).__init__()
  52. self.conv1 = conv1x1(inplanes, planes, stride)
  53. self.bn1 = nn.BatchNorm2D(planes)
  54. self.relu = nn.ReLU()
  55. self.conv2 = conv3x3(planes, planes)
  56. self.bn2 = nn.BatchNorm2D(planes)
  57. self.downsample = downsample
  58. self.stride = stride
  59. def forward(self, x):
  60. residual = x
  61. out = self.conv1(x)
  62. out = self.bn1(out)
  63. out = self.relu(out)
  64. out = self.conv2(out)
  65. out = self.bn2(out)
  66. if self.downsample is not None:
  67. residual = self.downsample(x)
  68. out += residual
  69. out = self.relu(out)
  70. return out
  71. class ResNet_ASTER(nn.Layer):
  72. """For aster or crnn"""
  73. def __init__(self, with_lstm=True, n_group=1, in_channels=3):
  74. super(ResNet_ASTER, self).__init__()
  75. self.with_lstm = with_lstm
  76. self.n_group = n_group
  77. self.layer0 = nn.Sequential(
  78. nn.Conv2D(
  79. in_channels,
  80. 32,
  81. kernel_size=(3, 3),
  82. stride=1,
  83. padding=1,
  84. bias_attr=False),
  85. nn.BatchNorm2D(32),
  86. nn.ReLU())
  87. self.inplanes = 32
  88. self.layer1 = self._make_layer(32, 3, [2, 2]) # [16, 50]
  89. self.layer2 = self._make_layer(64, 4, [2, 2]) # [8, 25]
  90. self.layer3 = self._make_layer(128, 6, [2, 1]) # [4, 25]
  91. self.layer4 = self._make_layer(256, 6, [2, 1]) # [2, 25]
  92. self.layer5 = self._make_layer(512, 3, [2, 1]) # [1, 25]
  93. if with_lstm:
  94. self.rnn = nn.LSTM(512, 256, direction="bidirect", num_layers=2)
  95. self.out_channels = 2 * 256
  96. else:
  97. self.out_channels = 512
  98. def _make_layer(self, planes, blocks, stride):
  99. downsample = None
  100. if stride != [1, 1] or self.inplanes != planes:
  101. downsample = nn.Sequential(
  102. conv1x1(self.inplanes, planes, stride), nn.BatchNorm2D(planes))
  103. layers = []
  104. layers.append(AsterBlock(self.inplanes, planes, stride, downsample))
  105. self.inplanes = planes
  106. for _ in range(1, blocks):
  107. layers.append(AsterBlock(self.inplanes, planes))
  108. return nn.Sequential(*layers)
  109. def forward(self, x):
  110. x0 = self.layer0(x)
  111. x1 = self.layer1(x0)
  112. x2 = self.layer2(x1)
  113. x3 = self.layer3(x2)
  114. x4 = self.layer4(x3)
  115. x5 = self.layer5(x4)
  116. cnn_feat = x5.squeeze(2) # [N, c, w]
  117. cnn_feat = paddle.transpose(cnn_feat, perm=[0, 2, 1])
  118. if self.with_lstm:
  119. rnn_feat, _ = self.rnn(cnn_feat)
  120. return rnn_feat
  121. else:
  122. return cnn_feat