get_center_image.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # main imports
  2. import os, sys
  3. import argparse
  4. import numpy as np
  5. # image processing
  6. from PIL import Image
  7. def reduce_image(image, size):
  8. """Reduce image from its center
  9. Arguments:
  10. image {PIL} -- PIL image expected
  11. size {tuple(int,int)} -- tuple of 2 elements int (width, height)
  12. """
  13. image = np.array(image)
  14. width, heigth, _ = image.shape
  15. n_w, n_h = size # new expected size
  16. # get center of image
  17. middle_w = int(width / 2)
  18. middle_h = int(heigth / 2)
  19. # start coordinates
  20. s_w = middle_w - int(n_w / 2)
  21. s_h = middle_h - int(n_h / 2)
  22. # end coordinates
  23. e_w = middle_w + int(n_w / 2)
  24. e_h = middle_h + int(n_h / 2)
  25. return image[s_w:e_w, s_h:e_h]
  26. def main():
  27. """
  28. main function which is ran when launching script
  29. """
  30. parser = argparse.ArgumentParser(description="Reduce an image from its center coordinate")
  31. parser.add_argument('--image', type=str, help='image to convert')
  32. parser.add_argument('--size', type=str, help='size of expected output image (width, height)')
  33. parser.add_argument('--output', type=str, help='output image filename')
  34. args = parser.parse_args()
  35. p_image = args.image
  36. p_size = list(map(int, args.size.split(',')))
  37. p_output = args.output
  38. image = Image.open(p_image)
  39. # get reduced image
  40. reduced = reduce_image(image, p_size)
  41. # save image
  42. reduced = Image.fromarray(reduced)
  43. reduced.save(p_output)
  44. if __name__ == "__main__":
  45. main()