1
0

ImageUtils.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright (c) 2023 Felix Kleinsteuber and Computer Vision Group, Friedrich Schiller University Jena
  2. # This file defines helper functions for processing images.
  3. from datetime import datetime
  4. from PIL import Image
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. def get_image_date(img_path: str) -> datetime:
  8. """Returns the date from the image EXIF data.
  9. Args:
  10. img_path (str): path to image
  11. Returns:
  12. datetime: datetime extracted from EXIF data
  13. """
  14. img = Image.open(img_path)
  15. date_raw = img.getexif()[306]
  16. return datetime.strptime(date_raw, "%Y:%m:%d %H:%M:%S")
  17. def display_images(images: list, titles: list, colorbar=False, size=(8, 5), row_size=2, **imshowargs):
  18. """Displays the given images next to each other.
  19. Args:
  20. images (list of np.ndarray): list of image arrays
  21. titles (list of str): list of titles
  22. colorbar (bool, optional): Display colorbars. Defaults to False.
  23. size (tuple of ints, optional): plt size (width, height) per image. Defaults to (8, 5).
  24. row_size (int, optional): Images per row. Defaults to 2.
  25. """
  26. num_imgs = len(images)
  27. num_cols = row_size
  28. num_rows = (num_imgs - 1) // num_cols + 1
  29. plt.figure(figsize=(num_cols * size[0], num_rows * size[1]))
  30. for i, image, title in zip(range(num_imgs), images, titles):
  31. plt.subplot(num_rows, num_cols, i + 1)
  32. plt.imshow(image, **imshowargs)
  33. plt.title(title)
  34. if colorbar:
  35. plt.colorbar()
  36. plt.tight_layout()
  37. plt.show()
  38. def save_image(image, filename: str, title: str, colorbar=False, size=(8, 5), **imshowargs):
  39. """Saves an image to file (using plt.imshow).
  40. Args:
  41. image (np.ndarray): Image.
  42. title (str): Title.
  43. filename (str): Target file name.
  44. colorbar (bool, optional): Display colorbars. Defaults to False.
  45. size (tuple, optional): plt size (width, height). Defaults to (8, 5).
  46. """
  47. plt.ioff()
  48. plt.figure(figsize=size)
  49. plt.imshow(image, **imshowargs)
  50. plt.title(title)
  51. if colorbar:
  52. plt.colorbar()
  53. plt.tight_layout()
  54. plt.savefig(filename, bbox_inches="tight")
  55. def is_daytime(img, threshold=50) -> bool:
  56. """Returns true when the image is taken at daytime.
  57. This is evaluated based on the image statistics.
  58. Args:
  59. img (2d np.array): image
  60. threshold (int, optional): Threshold which controls the bias towards predicting night or day. Defaults to 50.
  61. Returns:
  62. bool: True if day
  63. """
  64. return np.mean([abs(img[:,:,0] - img[:,:,1]), abs(img[:,:,1] - img[:,:,2]), abs(img[:,:,2] - img[:,:,0])]) > threshold