ImageUtils.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from datetime import datetime
  2. from PIL import Image
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. def get_image_date(img_path: str) -> datetime:
  6. """Returns the date from the image EXIF data.
  7. Args:
  8. img_path (str): path to image
  9. Returns:
  10. datetime: datetime extracted from EXIF data
  11. """
  12. img = Image.open(img_path)
  13. date_raw = img.getexif()[306]
  14. return datetime.strptime(date_raw, "%Y:%m:%d %H:%M:%S")
  15. def display_images(images: list, titles: list, colorbar=False, size=(8, 5), row_size=2, **imshowargs):
  16. """Displays the given images next to each other.
  17. Args:
  18. images (list of np.ndarray): list of image arrays
  19. titles (list of str): list of titles
  20. colorbar (bool, optional): Display colorbars. Defaults to False.
  21. size (tuple of ints, optional): plt size (width, height) per image. Defaults to (8, 5).
  22. row_size (int, optional): Images per row. Defaults to 2.
  23. """
  24. num_imgs = len(images)
  25. num_cols = row_size
  26. num_rows = (num_imgs - 1) // num_cols + 1
  27. plt.figure(figsize=(num_cols * size[0], num_rows * size[1]))
  28. for i, image, title in zip(range(num_imgs), images, titles):
  29. plt.subplot(num_rows, num_cols, i + 1)
  30. plt.imshow(image, **imshowargs)
  31. plt.title(title)
  32. if colorbar:
  33. plt.colorbar()
  34. plt.tight_layout()
  35. plt.show()
  36. def save_image(image, filename: str, title: str, colorbar=False, size=(8, 5), **imshowargs):
  37. """Saves an image to file (using plt.imshow).
  38. Args:
  39. image (np.ndarray): Image.
  40. title (str): Title.
  41. filename (str): Target file name.
  42. colorbar (bool, optional): Display colorbars. Defaults to False.
  43. size (tuple, optional): plt size (width, height). Defaults to (8, 5).
  44. """
  45. plt.ioff()
  46. plt.figure(figsize=size)
  47. plt.imshow(image, **imshowargs)
  48. plt.title(title)
  49. if colorbar:
  50. plt.colorbar()
  51. plt.tight_layout()
  52. plt.savefig(filename, bbox_inches="tight")
  53. def is_daytime(img, threshold=50) -> bool:
  54. return np.mean([abs(img[:,:,0] - img[:,:,1]), abs(img[:,:,1] - img[:,:,2]), abs(img[:,:,2] - img[:,:,0])]) > threshold