make_shrink_map.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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/WenmuZhou/DBNet.pytorch/blob/master/data_loader/modules/make_shrink_map.py
  17. """
  18. from __future__ import absolute_import
  19. from __future__ import division
  20. from __future__ import print_function
  21. from __future__ import unicode_literals
  22. import numpy as np
  23. import cv2
  24. from shapely.geometry import Polygon
  25. import pyclipper
  26. __all__ = ['MakeShrinkMap']
  27. class MakeShrinkMap(object):
  28. r'''
  29. Making binary mask from detection data with ICDAR format.
  30. Typically following the process of class `MakeICDARData`.
  31. '''
  32. def __init__(self, min_text_size=8, shrink_ratio=0.4, **kwargs):
  33. self.min_text_size = min_text_size
  34. self.shrink_ratio = shrink_ratio
  35. def __call__(self, data):
  36. image = data['image']
  37. text_polys = data['polys']
  38. ignore_tags = data['ignore_tags']
  39. h, w = image.shape[:2]
  40. text_polys, ignore_tags = self.validate_polygons(text_polys,
  41. ignore_tags, h, w)
  42. gt = np.zeros((h, w), dtype=np.float32)
  43. mask = np.ones((h, w), dtype=np.float32)
  44. for i in range(len(text_polys)):
  45. polygon = text_polys[i]
  46. height = max(polygon[:, 1]) - min(polygon[:, 1])
  47. width = max(polygon[:, 0]) - min(polygon[:, 0])
  48. if ignore_tags[i] or min(height, width) < self.min_text_size:
  49. cv2.fillPoly(mask,
  50. polygon.astype(np.int32)[np.newaxis, :, :], 0)
  51. ignore_tags[i] = True
  52. else:
  53. polygon_shape = Polygon(polygon)
  54. subject = [tuple(l) for l in polygon]
  55. padding = pyclipper.PyclipperOffset()
  56. padding.AddPath(subject, pyclipper.JT_ROUND,
  57. pyclipper.ET_CLOSEDPOLYGON)
  58. shrinked = []
  59. # Increase the shrink ratio every time we get multiple polygon returned back
  60. possible_ratios = np.arange(self.shrink_ratio, 1,
  61. self.shrink_ratio)
  62. np.append(possible_ratios, 1)
  63. # print(possible_ratios)
  64. for ratio in possible_ratios:
  65. # print(f"Change shrink ratio to {ratio}")
  66. distance = polygon_shape.area * (
  67. 1 - np.power(ratio, 2)) / polygon_shape.length
  68. shrinked = padding.Execute(-distance)
  69. if len(shrinked) == 1:
  70. break
  71. if shrinked == []:
  72. cv2.fillPoly(mask,
  73. polygon.astype(np.int32)[np.newaxis, :, :], 0)
  74. ignore_tags[i] = True
  75. continue
  76. for each_shirnk in shrinked:
  77. shirnk = np.array(each_shirnk).reshape(-1, 2)
  78. cv2.fillPoly(gt, [shirnk.astype(np.int32)], 1)
  79. data['shrink_map'] = gt
  80. data['shrink_mask'] = mask
  81. return data
  82. def validate_polygons(self, polygons, ignore_tags, h, w):
  83. '''
  84. polygons (numpy.array, required): of shape (num_instances, num_points, 2)
  85. '''
  86. if len(polygons) == 0:
  87. return polygons, ignore_tags
  88. assert len(polygons) == len(ignore_tags)
  89. for polygon in polygons:
  90. polygon[:, 0] = np.clip(polygon[:, 0], 0, w - 1)
  91. polygon[:, 1] = np.clip(polygon[:, 1], 0, h - 1)
  92. for i in range(len(polygons)):
  93. area = self.polygon_area(polygons[i])
  94. if abs(area) < 1:
  95. ignore_tags[i] = True
  96. if area > 0:
  97. polygons[i] = polygons[i][::-1, :]
  98. return polygons, ignore_tags
  99. def polygon_area(self, polygon):
  100. """
  101. compute polygon area
  102. """
  103. area = 0
  104. q = polygon[-1]
  105. for p in polygon:
  106. area += p[0] * q[1] - p[1] * q[0]
  107. q = p
  108. return area / 2.0