warp_image.py 1.5 KB

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