funcs.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. 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 w == im.shape[1] and h == im.shape[0]:
  31. return im
  32. if backend.lower() == "pil":
  33. resize_function = _pil_resize
  34. else:
  35. resize_function = _cv2_resize
  36. if backend.lower() != "cv2":
  37. logging.warning(
  38. f"Unknown backend {backend}. Defaulting to cv2 for resizing."
  39. )
  40. im = resize_function(im, (w, h), interp)
  41. return im
  42. def _cv2_resize(src, size, resample):
  43. return cv2.resize(src, size, interpolation=resample)
  44. def _pil_resize(src, size, resample):
  45. if isinstance(src, np.ndarray):
  46. pil_img = Image.fromarray(src)
  47. else:
  48. pil_img = src
  49. pil_img = pil_img.resize(size, resample)
  50. return np.asarray(pil_img)
  51. def flip_h(im):
  52. """flip image horizontally"""
  53. return cv2.flip(im, 1)
  54. def flip_v(im):
  55. """flip image vertically"""
  56. return cv2.flip(im, 0)
  57. def slice(im, coords):
  58. """slice the image"""
  59. x1, y1, x2, y2 = coords
  60. im = im[y1:y2, x1:x2, ...]
  61. return im
  62. def pad(im, pad, val):
  63. """padding image by value"""
  64. if isinstance(pad, int):
  65. pad = [pad] * 4
  66. if len(pad) != 4:
  67. raise ValueError
  68. if all(x == 0 for x in pad):
  69. return im
  70. chns = 1 if im.ndim == 2 else im.shape[2]
  71. im = cv2.copyMakeBorder(im, *pad, cv2.BORDER_CONSTANT, value=(val,) * chns)
  72. return im