image_functions.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # !/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. ################################################################################
  4. #
  5. # Copyright (c) 2024 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ################################################################################
  8. """
  9. Author: PaddlePaddle Authors
  10. """
  11. import cv2
  12. def resize(im, target_size, interp):
  13. """ resize image to target size """
  14. w, h = target_size
  15. im = cv2.resize(im, (w, h), interpolation=interp)
  16. return im
  17. def flip_h(im):
  18. """ flip image horizontally """
  19. if len(im.shape) == 3:
  20. im = im[:, ::-1, :]
  21. elif len(im.shape) == 2:
  22. im = im[:, ::-1]
  23. return im
  24. def flip_v(im):
  25. """ flip image vertically """
  26. if len(im.shape) == 3:
  27. im = im[::-1, :, :]
  28. elif len(im.shape) == 2:
  29. im = im[::-1, :]
  30. return im
  31. def slice(im, coords):
  32. """ slice the image """
  33. x1, y1, x2, y2 = coords
  34. im = im[y1:y2, x1:x2, ...]
  35. return im
  36. def pad(im, pad, val):
  37. """ padding image by value """
  38. if isinstance(pad, int):
  39. pad = [pad] * 4
  40. if len(pad) != 4:
  41. raise ValueError
  42. chns = 1 if im.ndim == 2 else im.shape[2]
  43. im = cv2.copyMakeBorder(im, *pad, cv2.BORDER_CONSTANT, value=(val, ) * chns)
  44. return im