warp_image.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Copyright (c) 2024 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. import cv2
  15. import numpy as np
  16. def rotate_image(image, angle):
  17. if angle < 0 or angle >= 360:
  18. raise ValueError("`angle` should be in range [0, 360)")
  19. if angle < 1e-7:
  20. return image
  21. # Should we align corners?
  22. h, w = image.shape[:2]
  23. center = (w / 2, h / 2)
  24. scale = 1.0
  25. mat = cv2.getRotationMatrix2D(center, angle, scale)
  26. cos = np.abs(mat[0, 0])
  27. sin = np.abs(mat[0, 1])
  28. new_w = int((h * sin) + (w * cos))
  29. new_h = int((h * cos) + (w * sin))
  30. mat[0, 2] += (new_w - w) / 2
  31. mat[1, 2] += (new_h - h) / 2
  32. dst_size = (new_w, new_h)
  33. rotated = cv2.warpAffine(
  34. image,
  35. mat,
  36. dst_size,
  37. flags=cv2.INTER_CUBIC,
  38. )
  39. return rotated