ImageAnnotator.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import ipywidgets as widgets
  2. from IPython.display import display
  3. from py.Session import Session
  4. from py.ImageClassifier import AbstractImageClassifier
  5. import numpy as np
  6. class ImageAnnotator():
  7. def __init__(self, classifier: AbstractImageClassifier, session: Session, initial_scores = [], initial_annotations = [], load_from = None):
  8. self.scores = initial_scores
  9. self.annotations = initial_annotations
  10. self.score = -1
  11. self.classifier = classifier
  12. self.session = session
  13. if load_from is not None:
  14. data = np.load(load_from, allow_pickle=True)
  15. self.annotations = data[0]
  16. self.scores = data[1]
  17. normal_btn = widgets.Button(description = "Normal")
  18. anomalous_btn = widgets.Button(description = "Anomalous")
  19. self.button_box = widgets.HBox([normal_btn, anomalous_btn])
  20. self.output = widgets.Output(layout={"height": "400px"})
  21. display(self.button_box, self.output)
  22. normal_btn.on_click(self.mark_as_normal)
  23. anomalous_btn.on_click(self.mark_as_anomalous)
  24. self.next_image()
  25. def mark_as_normal(self, _):
  26. with self.output:
  27. print("Marking as normal...")
  28. self.annotations.append(True)
  29. self.scores.append(self.score)
  30. self.next_image()
  31. def mark_as_anomalous(self, _):
  32. with self.output:
  33. print("Marking as anomalous...")
  34. self.annotations.append(False)
  35. self.scores.append(self.score)
  36. self.next_image()
  37. def next_image(self):
  38. img = self.session.get_random_motion_image(day_only=True)
  39. self.score = self.classifier.evaluate(img)
  40. self.output.clear_output()
  41. with self.output:
  42. display(img.to_ipython_image())
  43. print(f"score = {self.score}")
  44. def save(self, filename: str):
  45. np.save(filename, [self.annotations, self.scores])