translate.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import numpy as np
  2. def translate_image(image, x_shift, y_shift, border_value=0):
  3. """Translate an image.
  4. Args:
  5. image (ndarray): Image to be translated with format (h, w) or (h, w, c).
  6. x_shift (int): The offset used for translate in horizontal
  7. direction. right is the positive direction.
  8. y_shift (int): The offset used for translate in vertical
  9. direction. down is the positive direction.
  10. border_value (int | tuple[int]): Value used in case of a
  11. constant border.
  12. Returns:
  13. ndarray: The translated image.
  14. """
  15. assert image.ndim in [2, 3]
  16. assert isinstance(x_shift, int)
  17. assert isinstance(y_shift, int)
  18. image_height, image_width = image.shape[:2]
  19. channels = 1 if image.ndim == 2 else image.shape[2]
  20. if isinstance(border_value, (int, float)):
  21. dst_image = np.full_like(image, border_value)
  22. elif isinstance(border_value, tuple):
  23. assert len(border_value) == channels, \
  24. 'Expected the num of elements in tuple equals the channels' \
  25. 'of input image. Found {} vs {}'.format(
  26. len(border_value), channels)
  27. if channels == 1:
  28. dst_image = np.full_like(image, border_value[0])
  29. else:
  30. border_value = np.asarray(border_value, dtype=image.dtype)
  31. dst_image = np.empty_like(image)
  32. dst_image[:] = border_value
  33. else:
  34. raise ValueError(
  35. 'Invalid type {} for `border_value`.'.format(type(border_value)))
  36. if (abs(x_shift) >= image_width) or (abs(y_shift) >= image_height):
  37. return dst_image
  38. src_x_begin = max(-x_shift, 0)
  39. src_x_end = min(image_width - x_shift, image_width)
  40. dst_x_begin = max(x_shift, 0)
  41. dst_x_end = min(image_width + x_shift, image_width)
  42. src_y_begin = max(-y_shift, 0)
  43. src_y_end = min(image_height - y_shift, image_height)
  44. dst_y_begin = max(y_shift, 0)
  45. dst_y_end = min(image_height + y_shift, image_height)
  46. dst_image[dst_y_begin:dst_y_end, dst_x_begin:dst_x_end] = \
  47. image[src_y_begin:src_y_end, src_x_begin:src_x_end]
  48. return dst_image