funcs.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 resize(im, target_size, interp):
  16. """resize image to target size"""
  17. w, h = target_size
  18. im = cv2.resize(im, (w, h), interpolation=interp)
  19. return im
  20. def flip_h(im):
  21. """flip image horizontally"""
  22. if len(im.shape) == 3:
  23. im = im[:, ::-1, :]
  24. elif len(im.shape) == 2:
  25. im = im[:, ::-1]
  26. return im
  27. def flip_v(im):
  28. """flip image vertically"""
  29. if len(im.shape) == 3:
  30. im = im[::-1, :, :]
  31. elif len(im.shape) == 2:
  32. im = im[::-1, :]
  33. return im
  34. def slice(im, coords):
  35. """slice the image"""
  36. x1, y1, x2, y2 = coords
  37. im = im[y1:y2, x1:x2, ...]
  38. return im
  39. def pad(im, pad, val):
  40. """padding image by value"""
  41. if isinstance(pad, int):
  42. pad = [pad] * 4
  43. if len(pad) != 4:
  44. raise ValueError
  45. chns = 1 if im.ndim == 2 else im.shape[2]
  46. im = cv2.copyMakeBorder(im, *pad, cv2.BORDER_CONSTANT, value=(val,) * chns)
  47. return im