gridmask_utils.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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 print_function
  16. from __future__ import division
  17. import numpy as np
  18. from PIL import Image
  19. class Gridmask(object):
  20. def __init__(self,
  21. use_h=True,
  22. use_w=True,
  23. rotate=1,
  24. offset=False,
  25. ratio=0.5,
  26. mode=1,
  27. prob=0.7,
  28. upper_iter=360000):
  29. super(Gridmask, self).__init__()
  30. self.use_h = use_h
  31. self.use_w = use_w
  32. self.rotate = rotate
  33. self.offset = offset
  34. self.ratio = ratio
  35. self.mode = mode
  36. self.prob = prob
  37. self.st_prob = prob
  38. self.upper_iter = upper_iter
  39. def __call__(self, x, curr_iter):
  40. self.prob = self.st_prob * min(1, 1.0 * curr_iter / self.upper_iter)
  41. if np.random.rand() > self.prob:
  42. return x
  43. h, w, _ = x.shape
  44. hh = int(1.5 * h)
  45. ww = int(1.5 * w)
  46. d = np.random.randint(2, h)
  47. self.l = min(max(int(d * self.ratio + 0.5), 1), d - 1)
  48. mask = np.ones((hh, ww), np.float32)
  49. st_h = np.random.randint(d)
  50. st_w = np.random.randint(d)
  51. if self.use_h:
  52. for i in range(hh // d):
  53. s = d * i + st_h
  54. t = min(s + self.l, hh)
  55. mask[s:t, :] *= 0
  56. if self.use_w:
  57. for i in range(ww // d):
  58. s = d * i + st_w
  59. t = min(s + self.l, ww)
  60. mask[:, s:t] *= 0
  61. r = np.random.randint(self.rotate)
  62. mask = Image.fromarray(np.uint8(mask))
  63. mask = mask.rotate(r)
  64. mask = np.asarray(mask)
  65. mask = mask[(hh - h) // 2:(hh - h) // 2 + h, (ww - w) // 2:(ww - w) //
  66. 2 + w].astype(np.float32)
  67. if self.mode == 1:
  68. mask = 1 - mask
  69. mask = np.expand_dims(mask, axis=-1)
  70. if self.offset:
  71. offset = (2 * (np.random.rand(h, w) - 0.5)).astype(np.float32)
  72. x = (x * mask + offset * (1 - mask)).astype(x.dtype)
  73. else:
  74. x = (x * mask).astype(x.dtype)
  75. return x