funcs.py 2.5 KB

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