iaa_augment.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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/iaa_augment.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 imgaug
  24. import imgaug.augmenters as iaa
  25. class AugmenterBuilder(object):
  26. def __init__(self):
  27. pass
  28. def build(self, args, root=True):
  29. if args is None or len(args) == 0:
  30. return None
  31. elif isinstance(args, list):
  32. if root:
  33. sequence = [self.build(value, root=False) for value in args]
  34. return iaa.Sequential(sequence)
  35. else:
  36. return getattr(iaa, args[0])(
  37. *[self.to_tuple_if_list(a) for a in args[1:]])
  38. elif isinstance(args, dict):
  39. cls = getattr(iaa, args['type'])
  40. return cls(**{
  41. k: self.to_tuple_if_list(v)
  42. for k, v in args['args'].items()
  43. })
  44. else:
  45. raise RuntimeError('unknown augmenter arg: ' + str(args))
  46. def to_tuple_if_list(self, obj):
  47. if isinstance(obj, list):
  48. return tuple(obj)
  49. return obj
  50. class IaaAugment():
  51. def __init__(self, augmenter_args=None, **kwargs):
  52. if augmenter_args is None:
  53. augmenter_args = [{
  54. 'type': 'Fliplr',
  55. 'args': {
  56. 'p': 0.5
  57. }
  58. }, {
  59. 'type': 'Affine',
  60. 'args': {
  61. 'rotate': [-10, 10]
  62. }
  63. }, {
  64. 'type': 'Resize',
  65. 'args': {
  66. 'size': [0.5, 3]
  67. }
  68. }]
  69. self.augmenter = AugmenterBuilder().build(augmenter_args)
  70. def __call__(self, data):
  71. image = data['image']
  72. shape = image.shape
  73. if self.augmenter:
  74. aug = self.augmenter.to_deterministic()
  75. data['image'] = aug.augment_image(image)
  76. data = self.may_augment_annotation(aug, data, shape)
  77. return data
  78. def may_augment_annotation(self, aug, data, shape):
  79. if aug is None:
  80. return data
  81. line_polys = []
  82. for poly in data['polys']:
  83. new_poly = self.may_augment_poly(aug, shape, poly)
  84. line_polys.append(new_poly)
  85. data['polys'] = np.array(line_polys)
  86. return data
  87. def may_augment_poly(self, aug, img_shape, poly):
  88. keypoints = [imgaug.Keypoint(p[0], p[1]) for p in poly]
  89. keypoints = aug.augment_keypoints(
  90. [imgaug.KeypointsOnImage(
  91. keypoints, shape=img_shape)])[0].keypoints
  92. poly = [(p.x, p.y) for p in keypoints]
  93. return poly