pse_postprocess.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # copyright (c) 2021 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/whai362/PSENet/blob/python3/models/head/psenet_head.py
  17. """
  18. from __future__ import absolute_import
  19. from __future__ import division
  20. from __future__ import print_function
  21. import numpy as np
  22. import cv2
  23. import paddle
  24. from paddle.nn import functional as F
  25. from ppocr.postprocess.pse_postprocess.pse import pse
  26. class PSEPostProcess(object):
  27. """
  28. The post process for PSE.
  29. """
  30. def __init__(self,
  31. thresh=0.5,
  32. box_thresh=0.85,
  33. min_area=16,
  34. box_type='quad',
  35. scale=4,
  36. **kwargs):
  37. assert box_type in ['quad', 'poly'], 'Only quad and poly is supported'
  38. self.thresh = thresh
  39. self.box_thresh = box_thresh
  40. self.min_area = min_area
  41. self.box_type = box_type
  42. self.scale = scale
  43. def __call__(self, outs_dict, shape_list):
  44. pred = outs_dict['maps']
  45. if not isinstance(pred, paddle.Tensor):
  46. pred = paddle.to_tensor(pred)
  47. pred = F.interpolate(
  48. pred, scale_factor=4 // self.scale, mode='bilinear')
  49. score = F.sigmoid(pred[:, 0, :, :])
  50. kernels = (pred > self.thresh).astype('float32')
  51. text_mask = kernels[:, 0, :, :]
  52. text_mask = paddle.unsqueeze(text_mask, axis=1)
  53. kernels[:, 0:, :, :] = kernels[:, 0:, :, :] * text_mask
  54. score = score.numpy()
  55. kernels = kernels.numpy().astype(np.uint8)
  56. boxes_batch = []
  57. for batch_index in range(pred.shape[0]):
  58. boxes, scores = self.boxes_from_bitmap(score[batch_index],
  59. kernels[batch_index],
  60. shape_list[batch_index])
  61. boxes_batch.append({'points': boxes, 'scores': scores})
  62. return boxes_batch
  63. def boxes_from_bitmap(self, score, kernels, shape):
  64. label = pse(kernels, self.min_area)
  65. return self.generate_box(score, label, shape)
  66. def generate_box(self, score, label, shape):
  67. src_h, src_w, ratio_h, ratio_w = shape
  68. label_num = np.max(label) + 1
  69. boxes = []
  70. scores = []
  71. for i in range(1, label_num):
  72. ind = label == i
  73. points = np.array(np.where(ind)).transpose((1, 0))[:, ::-1]
  74. if points.shape[0] < self.min_area:
  75. label[ind] = 0
  76. continue
  77. score_i = np.mean(score[ind])
  78. if score_i < self.box_thresh:
  79. label[ind] = 0
  80. continue
  81. if self.box_type == 'quad':
  82. rect = cv2.minAreaRect(points)
  83. bbox = cv2.boxPoints(rect)
  84. elif self.box_type == 'poly':
  85. box_height = np.max(points[:, 1]) + 10
  86. box_width = np.max(points[:, 0]) + 10
  87. mask = np.zeros((box_height, box_width), np.uint8)
  88. mask[points[:, 1], points[:, 0]] = 255
  89. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
  90. cv2.CHAIN_APPROX_SIMPLE)
  91. bbox = np.squeeze(contours[0], 1)
  92. else:
  93. raise NotImplementedError
  94. bbox[:, 0] = np.clip(np.round(bbox[:, 0] / ratio_w), 0, src_w)
  95. bbox[:, 1] = np.clip(np.round(bbox[:, 1] / ratio_h), 0, src_h)
  96. boxes.append(bbox)
  97. scores.append(score_i)
  98. return boxes, scores