flip.py 1.6 KB

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