AnnotatedInteractiveImageView.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from pycs.ui.AnnotatedImageView import AnnotatedImageView
  2. class AnnotatedInteractiveImageView(AnnotatedImageView):
  3. def __init__(self, parent, click_handler=None):
  4. super().__init__(parent)
  5. self.__click_handler = click_handler
  6. def mousePressEvent(self, event):
  7. """
  8. handle click event, get point and emit to parent node
  9. :param event:
  10. :return:
  11. """
  12. # do not execute if no click handler is given
  13. if self.__click_handler is None:
  14. return
  15. # get clicked point
  16. pos = event.pos()
  17. point_x, point_y = pos.x() / self.width(), pos.y() / self.height()
  18. # get image and box dimensions
  19. image_width, image_height = self._image.width(), self._image.height()
  20. box_width, box_height = self.width(), self.height()
  21. maximum_width, maximum_height = max(image_width, box_width), max(image_height, box_height)
  22. # determine orientation
  23. # horizontal
  24. if image_width / image_height >= box_width / box_height:
  25. # calculate top margin
  26. image_height, box_height = maximum_width / image_width * image_height, maximum_width / box_width * box_height
  27. top = (box_height - image_height) / 2
  28. # click is inside the image
  29. if top <= point_y * box_height <= box_height - top:
  30. off = top / box_height
  31. rat = 1 - 2 * off
  32. self.__click_handler(point_x, (point_y - off) / rat, event)
  33. # vertical
  34. else:
  35. # calculate left margin
  36. image_width, box_width = maximum_height / image_height * image_width, maximum_height / box_height * box_width
  37. left = (box_width - image_width) / 2
  38. if left <= point_x * box_width <= box_width - left:
  39. off = left / box_width
  40. rat = 1 - 2 * off
  41. self.__click_handler((point_x - off) / rat, point_y, event)