funcs.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 PIL import Image
  16. from .....utils import logging
  17. from .....utils.deps import function_requires_deps, is_dep_available
  18. if is_dep_available("opencv-contrib-python"):
  19. import cv2
  20. def check_image_size(input_):
  21. """check image size"""
  22. if not (
  23. isinstance(input_, (list, tuple))
  24. and len(input_) == 2
  25. and isinstance(input_[0], int)
  26. and isinstance(input_[1], int)
  27. ):
  28. raise TypeError(f"{input_} cannot represent a valid image size.")
  29. def resize(im, target_size, interp, backend="cv2"):
  30. """resize image to target size"""
  31. w, h = target_size
  32. if w == im.shape[1] and h == im.shape[0]:
  33. return im
  34. if backend.lower() == "pil":
  35. resize_function = _pil_resize
  36. else:
  37. resize_function = _cv2_resize
  38. if backend.lower() != "cv2":
  39. logging.warning(
  40. f"Unknown backend {backend}. Defaulting to cv2 for resizing."
  41. )
  42. im = resize_function(im, (w, h), interp)
  43. return im
  44. @function_requires_deps("opencv-contrib-python")
  45. def _cv2_resize(src, size, resample):
  46. return cv2.resize(src, size, interpolation=resample)
  47. def _pil_resize(src, size, resample):
  48. if isinstance(src, np.ndarray):
  49. pil_img = Image.fromarray(src)
  50. else:
  51. pil_img = src
  52. pil_img = pil_img.resize(size, resample)
  53. return np.asarray(pil_img)
  54. @function_requires_deps("opencv-contrib-python")
  55. def flip_h(im):
  56. """flip image horizontally"""
  57. return cv2.flip(im, 1)
  58. @function_requires_deps("opencv-contrib-python")
  59. def flip_v(im):
  60. """flip image vertically"""
  61. return cv2.flip(im, 0)
  62. def slice(im, coords):
  63. """slice the image"""
  64. x1, y1, x2, y2 = coords
  65. im = im[y1:y2, x1:x2, ...]
  66. return im
  67. @function_requires_deps("opencv-contrib-python")
  68. def pad(im, pad, val):
  69. """padding image by value"""
  70. if isinstance(pad, int):
  71. pad = [pad] * 4
  72. if len(pad) != 4:
  73. raise ValueError
  74. if all(x == 0 for x in pad):
  75. return im
  76. chns = 1 if im.ndim == 2 else im.shape[2]
  77. im = cv2.copyMakeBorder(im, *pad, cv2.BORDER_CONSTANT, value=(val,) * chns)
  78. return im