hide_and_seek.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # Copyright (c) 2021 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. # This code is based on https://github.com/kkanshul/Hide-and-Seek
  15. import numpy as np
  16. import random
  17. class HideAndSeek(object):
  18. def __init__(self):
  19. # possible grid size, 0 means no hiding
  20. self.grid_sizes = [0, 16, 32, 44, 56]
  21. # hiding probability
  22. self.hide_prob = 0.5
  23. def __call__(self, img):
  24. # randomly choose one grid size
  25. grid_size = np.random.choice(self.grid_sizes)
  26. _, h, w = img.shape
  27. # hide the patches
  28. if grid_size == 0:
  29. return img
  30. for x in range(0, w, grid_size):
  31. for y in range(0, h, grid_size):
  32. x_end = min(w, x + grid_size)
  33. y_end = min(h, y + grid_size)
  34. if (random.random() <= self.hide_prob):
  35. img[:, x:x_end, y:y_end] = 0
  36. return img