funcs.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. def check_image_size(input_):
  16. """check image size"""
  17. if not (
  18. isinstance(input_, (list, tuple))
  19. and len(input_) == 2
  20. and isinstance(input_[0], int)
  21. and isinstance(input_[1], int)
  22. ):
  23. raise TypeError(f"{input_} cannot represent a valid image size.")
  24. def resize(im, target_size, interp):
  25. """resize image to target size"""
  26. w, h = target_size
  27. im = cv2.resize(im, (w, h), interpolation=interp)
  28. return im
  29. def flip_h(im):
  30. """flip image horizontally"""
  31. if len(im.shape) == 3:
  32. im = im[:, ::-1, :]
  33. elif len(im.shape) == 2:
  34. im = im[:, ::-1]
  35. return im
  36. def flip_v(im):
  37. """flip image vertically"""
  38. if len(im.shape) == 3:
  39. im = im[::-1, :, :]
  40. elif len(im.shape) == 2:
  41. im = im[::-1, :]
  42. return im
  43. def slice(im, coords):
  44. """slice the image"""
  45. x1, y1, x2, y2 = coords
  46. im = im[y1:y2, x1:x2, ...]
  47. return im
  48. def pad(im, pad, val):
  49. """padding image by value"""
  50. if isinstance(pad, int):
  51. pad = [pad] * 4
  52. if len(pad) != 4:
  53. raise ValueError
  54. chns = 1 if im.ndim == 2 else im.shape[2]
  55. im = cv2.copyMakeBorder(im, *pad, cv2.BORDER_CONSTANT, value=(val,) * chns)
  56. return im