iaa_augment.py 3.2 KB

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