flip.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. tf.image.rot90
  40. """
  41. if copy:
  42. image = image.copy()
  43. if image.ndim == 2:
  44. transpose_axes = (1, 0)
  45. else:
  46. transpose_axes = (1, 0, 2)
  47. n = n % 4
  48. if n == 0:
  49. return image
  50. elif n == 1:
  51. image = np.transpose(image, transpose_axes)
  52. image = np.flipud(image)
  53. elif n == 2:
  54. image = np.fliplr(np.flipud(image))
  55. else:
  56. image = np.transpose(image, transpose_axes)
  57. image = np.fliplr(image)
  58. return image