translate.py 2.2 KB

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