ssl_img_aug.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. import math
  15. import cv2
  16. import numpy as np
  17. import random
  18. from PIL import Image
  19. from .rec_img_aug import resize_norm_img
  20. class SSLRotateResize(object):
  21. def __init__(
  22. self, image_shape, padding=False, select_all=True, mode="train", **kwargs
  23. ):
  24. self.image_shape = image_shape
  25. self.padding = padding
  26. self.select_all = select_all
  27. self.mode = mode
  28. def __call__(self, data):
  29. img = data["image"]
  30. data["image_r90"] = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
  31. data["image_r180"] = cv2.rotate(data["image_r90"], cv2.ROTATE_90_CLOCKWISE)
  32. data["image_r270"] = cv2.rotate(data["image_r180"], cv2.ROTATE_90_CLOCKWISE)
  33. images = []
  34. for key in ["image", "image_r90", "image_r180", "image_r270"]:
  35. images.append(
  36. resize_norm_img(
  37. data.pop(key), image_shape=self.image_shape, padding=self.padding
  38. )[0]
  39. )
  40. data["image"] = np.stack(images, axis=0)
  41. data["label"] = np.array(list(range(4)))
  42. if not self.select_all:
  43. data["image"] = data["image"][0::2] # just choose 0 and 180
  44. data["label"] = data["label"][0:2] # label needs to be continuous
  45. if self.mode == "test":
  46. data["image"] = data["image"][0]
  47. data["label"] = data["label"][0]
  48. return data