flip.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import khandy
  2. import numpy as np
  3. def flip_image(image, direction='h', copy=True):
  4. """
  5. References:
  6. np.flipud, np.fliplr, np.flip
  7. cv2.flip
  8. tf.image.flip_up_down
  9. tf.image.flip_left_right
  10. """
  11. assert khandy.is_numpy_image(image)
  12. assert direction in ['x', 'h', 'horizontal',
  13. 'y', 'v', 'vertical',
  14. 'o', 'b', 'both']
  15. if copy:
  16. image = image.copy()
  17. if direction in ['o', 'b', 'both', 'x', 'h', 'horizontal']:
  18. image = np.fliplr(image)
  19. if direction in ['o', 'b', 'both', 'y', 'v', 'vertical']:
  20. image = np.flipud(image)
  21. return image
  22. def transpose_image(image, copy=True):
  23. """Transpose image.
  24. References:
  25. np.transpose
  26. cv2.transpose
  27. tf.image.transpose
  28. """
  29. assert khandy.is_numpy_image(image)
  30. if copy:
  31. image = image.copy()
  32. if image.ndim == 2:
  33. transpose_axes = (1, 0)
  34. else:
  35. transpose_axes = (1, 0, 2)
  36. image = np.transpose(image, transpose_axes)
  37. return image
  38. def rot90_image(image, n=1, copy=True):
  39. """Rotate image counter-clockwise by 90 degrees.
  40. References:
  41. np.rot90
  42. cv2.rotate
  43. tf.image.rot90
  44. """
  45. assert khandy.is_numpy_image(image)
  46. if copy:
  47. image = image.copy()
  48. if image.ndim == 2:
  49. transpose_axes = (1, 0)
  50. else:
  51. transpose_axes = (1, 0, 2)
  52. n = n % 4
  53. if n == 0:
  54. return image[:]
  55. elif n == 1:
  56. image = np.transpose(image, transpose_axes)
  57. image = np.flipud(image)
  58. elif n == 2:
  59. image = np.fliplr(np.flipud(image))
  60. else:
  61. image = np.transpose(image, transpose_axes)
  62. image = np.fliplr(image)
  63. return image