pse_postprocess.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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__(
  31. self,
  32. thresh=0.5,
  33. box_thresh=0.85,
  34. min_area=16,
  35. box_type="quad",
  36. scale=4,
  37. **kwargs,
  38. ):
  39. assert box_type in ["quad", "poly"], "Only quad and poly is supported"
  40. self.thresh = thresh
  41. self.box_thresh = box_thresh
  42. self.min_area = min_area
  43. self.box_type = box_type
  44. self.scale = scale
  45. def __call__(self, outs_dict, shape_list):
  46. pred = outs_dict["maps"]
  47. if not isinstance(pred, paddle.Tensor):
  48. pred = paddle.to_tensor(pred)
  49. pred = F.interpolate(pred, scale_factor=4 // self.scale, mode="bilinear")
  50. score = F.sigmoid(pred[:, 0, :, :])
  51. kernels = (pred > self.thresh).astype("float32")
  52. text_mask = kernels[:, 0, :, :]
  53. text_mask = paddle.unsqueeze(text_mask, axis=1)
  54. kernels[:, 0:, :, :] = kernels[:, 0:, :, :] * text_mask
  55. score = score.numpy()
  56. kernels = kernels.numpy().astype(np.uint8)
  57. boxes_batch = []
  58. for batch_index in range(pred.shape[0]):
  59. boxes, scores = self.boxes_from_bitmap(
  60. score[batch_index], kernels[batch_index], shape_list[batch_index]
  61. )
  62. boxes_batch.append({"points": boxes, "scores": scores})
  63. return boxes_batch
  64. def boxes_from_bitmap(self, score, kernels, shape):
  65. label = pse(kernels, self.min_area)
  66. return self.generate_box(score, label, shape)
  67. def generate_box(self, score, label, shape):
  68. src_h, src_w, ratio_h, ratio_w = shape
  69. label_num = np.max(label) + 1
  70. boxes = []
  71. scores = []
  72. for i in range(1, label_num):
  73. ind = label == i
  74. points = np.array(np.where(ind)).transpose((1, 0))[:, ::-1]
  75. if points.shape[0] < self.min_area:
  76. label[ind] = 0
  77. continue
  78. score_i = np.mean(score[ind])
  79. if score_i < self.box_thresh:
  80. label[ind] = 0
  81. continue
  82. if self.box_type == "quad":
  83. rect = cv2.minAreaRect(points)
  84. bbox = cv2.boxPoints(rect)
  85. elif self.box_type == "poly":
  86. box_height = np.max(points[:, 1]) + 10
  87. box_width = np.max(points[:, 0]) + 10
  88. mask = np.zeros((box_height, box_width), np.uint8)
  89. mask[points[:, 1], points[:, 0]] = 255
  90. contours, _ = cv2.findContours(
  91. mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
  92. )
  93. bbox = np.squeeze(contours[0], 1)
  94. else:
  95. raise NotImplementedError
  96. bbox[:, 0] = np.clip(np.round(bbox[:, 0] / ratio_w), 0, src_w)
  97. bbox[:, 1] = np.clip(np.round(bbox[:, 1] / ratio_h), 0, src_h)
  98. boxes.append(bbox)
  99. scores.append(score_i)
  100. return boxes, scores