det_drrg_head.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # copyright (c) 2022 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/open-mmlab/mmocr/blob/main/mmocr/models/textdet/dense_heads/drrg_head.py
  17. """
  18. from __future__ import absolute_import
  19. from __future__ import division
  20. from __future__ import print_function
  21. import warnings
  22. import cv2
  23. import numpy as np
  24. import paddle
  25. import paddle.nn as nn
  26. import paddle.nn.functional as F
  27. from .gcn import GCN
  28. from .local_graph import LocalGraphs
  29. from .proposal_local_graph import ProposalLocalGraphs
  30. class DRRGHead(nn.Layer):
  31. def __init__(self,
  32. in_channels,
  33. k_at_hops=(8, 4),
  34. num_adjacent_linkages=3,
  35. node_geo_feat_len=120,
  36. pooling_scale=1.0,
  37. pooling_output_size=(4, 3),
  38. nms_thr=0.3,
  39. min_width=8.0,
  40. max_width=24.0,
  41. comp_shrink_ratio=1.03,
  42. comp_ratio=0.4,
  43. comp_score_thr=0.3,
  44. text_region_thr=0.2,
  45. center_region_thr=0.2,
  46. center_region_area_thr=50,
  47. local_graph_thr=0.7,
  48. **kwargs):
  49. super().__init__()
  50. assert isinstance(in_channels, int)
  51. assert isinstance(k_at_hops, tuple)
  52. assert isinstance(num_adjacent_linkages, int)
  53. assert isinstance(node_geo_feat_len, int)
  54. assert isinstance(pooling_scale, float)
  55. assert isinstance(pooling_output_size, tuple)
  56. assert isinstance(comp_shrink_ratio, float)
  57. assert isinstance(nms_thr, float)
  58. assert isinstance(min_width, float)
  59. assert isinstance(max_width, float)
  60. assert isinstance(comp_ratio, float)
  61. assert isinstance(comp_score_thr, float)
  62. assert isinstance(text_region_thr, float)
  63. assert isinstance(center_region_thr, float)
  64. assert isinstance(center_region_area_thr, int)
  65. assert isinstance(local_graph_thr, float)
  66. self.in_channels = in_channels
  67. self.out_channels = 6
  68. self.downsample_ratio = 1.0
  69. self.k_at_hops = k_at_hops
  70. self.num_adjacent_linkages = num_adjacent_linkages
  71. self.node_geo_feat_len = node_geo_feat_len
  72. self.pooling_scale = pooling_scale
  73. self.pooling_output_size = pooling_output_size
  74. self.comp_shrink_ratio = comp_shrink_ratio
  75. self.nms_thr = nms_thr
  76. self.min_width = min_width
  77. self.max_width = max_width
  78. self.comp_ratio = comp_ratio
  79. self.comp_score_thr = comp_score_thr
  80. self.text_region_thr = text_region_thr
  81. self.center_region_thr = center_region_thr
  82. self.center_region_area_thr = center_region_area_thr
  83. self.local_graph_thr = local_graph_thr
  84. self.out_conv = nn.Conv2D(
  85. in_channels=self.in_channels,
  86. out_channels=self.out_channels,
  87. kernel_size=1,
  88. stride=1,
  89. padding=0)
  90. self.graph_train = LocalGraphs(
  91. self.k_at_hops, self.num_adjacent_linkages, self.node_geo_feat_len,
  92. self.pooling_scale, self.pooling_output_size, self.local_graph_thr)
  93. self.graph_test = ProposalLocalGraphs(
  94. self.k_at_hops, self.num_adjacent_linkages, self.node_geo_feat_len,
  95. self.pooling_scale, self.pooling_output_size, self.nms_thr,
  96. self.min_width, self.max_width, self.comp_shrink_ratio,
  97. self.comp_ratio, self.comp_score_thr, self.text_region_thr,
  98. self.center_region_thr, self.center_region_area_thr)
  99. pool_w, pool_h = self.pooling_output_size
  100. node_feat_len = (pool_w * pool_h) * (
  101. self.in_channels + self.out_channels) + self.node_geo_feat_len
  102. self.gcn = GCN(node_feat_len)
  103. def forward(self, inputs, targets=None):
  104. """
  105. Args:
  106. inputs (Tensor): Shape of :math:`(N, C, H, W)`.
  107. gt_comp_attribs (list[ndarray]): The padded text component
  108. attributes. Shape: (num_component, 8).
  109. Returns:
  110. tuple: Returns (pred_maps, (gcn_pred, gt_labels)).
  111. - | pred_maps (Tensor): Prediction map with shape
  112. :math:`(N, C_{out}, H, W)`.
  113. - | gcn_pred (Tensor): Prediction from GCN module, with
  114. shape :math:`(N, 2)`.
  115. - | gt_labels (Tensor): Ground-truth label with shape
  116. :math:`(N, 8)`.
  117. """
  118. if self.training:
  119. assert targets is not None
  120. gt_comp_attribs = targets[7]
  121. pred_maps = self.out_conv(inputs)
  122. feat_maps = paddle.concat([inputs, pred_maps], axis=1)
  123. node_feats, adjacent_matrices, knn_inds, gt_labels = self.graph_train(
  124. feat_maps, np.stack(gt_comp_attribs))
  125. gcn_pred = self.gcn(node_feats, adjacent_matrices, knn_inds)
  126. return pred_maps, (gcn_pred, gt_labels)
  127. else:
  128. return self.single_test(inputs)
  129. def single_test(self, feat_maps):
  130. r"""
  131. Args:
  132. feat_maps (Tensor): Shape of :math:`(N, C, H, W)`.
  133. Returns:
  134. tuple: Returns (edge, score, text_comps).
  135. - | edge (ndarray): The edge array of shape :math:`(N, 2)`
  136. where each row is a pair of text component indices
  137. that makes up an edge in graph.
  138. - | score (ndarray): The score array of shape :math:`(N,)`,
  139. corresponding to the edge above.
  140. - | text_comps (ndarray): The text components of shape
  141. :math:`(N, 9)` where each row corresponds to one box and
  142. its score: (x1, y1, x2, y2, x3, y3, x4, y4, score).
  143. """
  144. pred_maps = self.out_conv(feat_maps)
  145. feat_maps = paddle.concat([feat_maps, pred_maps], axis=1)
  146. none_flag, graph_data = self.graph_test(pred_maps, feat_maps)
  147. (local_graphs_node_feat, adjacent_matrices, pivots_knn_inds,
  148. pivot_local_graphs, text_comps) = graph_data
  149. if none_flag:
  150. return None, None, None
  151. gcn_pred = self.gcn(local_graphs_node_feat, adjacent_matrices,
  152. pivots_knn_inds)
  153. pred_labels = F.softmax(gcn_pred, axis=1)
  154. edges = []
  155. scores = []
  156. pivot_local_graphs = pivot_local_graphs.squeeze().numpy()
  157. for pivot_ind, pivot_local_graph in enumerate(pivot_local_graphs):
  158. pivot = pivot_local_graph[0]
  159. for k_ind, neighbor_ind in enumerate(pivots_knn_inds[pivot_ind]):
  160. neighbor = pivot_local_graph[neighbor_ind.item()]
  161. edges.append([pivot, neighbor])
  162. scores.append(pred_labels[pivot_ind * pivots_knn_inds.shape[1] +
  163. k_ind, 1].item())
  164. edges = np.asarray(edges)
  165. scores = np.asarray(scores)
  166. return edges, scores, text_comps