translate.py 975 B

12345678910111213141516171819202122232425262728293031323334
  1. import numpy as np
  2. def translate_image(image, x_shift, y_shift):
  3. image_height, image_width = image.shape[:2]
  4. assert abs(x_shift) < image_width
  5. assert abs(y_shift) < image_height
  6. new_image = np.zeros_like(image)
  7. if x_shift < 0:
  8. src_x_start = -x_shift
  9. src_x_end = image_width
  10. dst_x_start = 0
  11. dst_x_end = image_width + x_shift
  12. else:
  13. src_x_start = 0
  14. src_x_end = image_width - x_shift
  15. dst_x_start = x_shift
  16. dst_x_end = image_width
  17. if y_shift < 0:
  18. src_y_start = -y_shift
  19. src_y_end = image_height
  20. dst_y_start = 0
  21. dst_y_end = image_height + y_shift
  22. else:
  23. src_y_start = 0
  24. src_y_end = image_height - y_shift
  25. dst_y_start = y_shift
  26. dst_y_end = image_height
  27. new_image[dst_y_start:dst_y_end, dst_x_start:dst_x_end] = \
  28. image[src_y_start:src_y_end, src_x_start:src_x_end]
  29. return new_image