canvas.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. from math import sqrt
  2. from PyQt4.QtGui import *
  3. from PyQt4.QtCore import *
  4. from shape import Shape
  5. class Canvas(QWidget):
  6. zoomRequest = pyqtSignal(int)
  7. scrollRequest = pyqtSignal(int, int)
  8. epsilon = 9.0 # TODO: Tune value
  9. def __init__(self, *args, **kwargs):
  10. super(Canvas, self).__init__(*args, **kwargs)
  11. self.startLabeling=False # has to click new label buttoon to starting drawing new polygons
  12. self.shapes = []
  13. self.current = None
  14. self.selectedShape=None # save the selected shape here
  15. self.line_color = QColor(0, 0, 255)
  16. self.line = Shape(line_color=self.line_color)
  17. self.scale = 1.0
  18. self.pixmap = None
  19. self.setFocusPolicy(Qt.WheelFocus)
  20. def mouseMoveEvent(self, ev):
  21. """Update line with last point and current coordinates."""
  22. if self.startLabeling and self.current:
  23. pos = self.transformPos(ev.posF())
  24. # Don't allow the user to draw outside of the pixmap area.
  25. # FIXME: Project point to pixmap's edge when getting out too fast.
  26. if self.outOfPixmap(pos):
  27. return ev.ignore()
  28. if len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  29. # Attract line to starting point and colorise to alert the user:
  30. self.line[1] = self.current[0]
  31. self.line.line_color = self.current.line_color
  32. else:
  33. self.line[1] = pos
  34. self.line.line_color = self.line_color
  35. self.repaint()
  36. def mousePressEvent(self, ev):
  37. if ev.button() == 1:
  38. if self.startLabeling:
  39. if self.current:
  40. self.current.addPoint(self.line[1])
  41. self.line[0] = self.current[-1]
  42. if self.current.isClosed():
  43. self.finalise()
  44. self.repaint()
  45. else:
  46. pos = self.transformPos(ev.posF())
  47. self.current = Shape()
  48. self.line.points = [pos, pos]
  49. self.current.addPoint(pos)
  50. self.setMouseTracking(True)
  51. else: # not in adding new label mode
  52. self.selectShape(ev.pos())
  53. def mouseDoubleClickEvent(self, ev):
  54. if self.current and self.startLabeling:
  55. # Add first point in the list so that it is consistent
  56. # with shapes created the normal way.
  57. self.current.addPoint(self.current[0])
  58. self.finalise()
  59. def selectShape(self, point):
  60. """Select the first shape created which contains this point."""
  61. self.deSelectShape()
  62. for shape in self.shapes:
  63. if shape.containsPoint(point):
  64. shape.selected = True
  65. self.selectedShape = shape
  66. return self.repaint()
  67. def deSelectShape(self):
  68. if self.selectedShape:
  69. self.selectedShape.selected = False
  70. self.repaint()
  71. def paintEvent(self, event):
  72. if not self.pixmap:
  73. return super(Canvas, self).paintEvent(event)
  74. p = QPainter()
  75. p.begin(self)
  76. p.setRenderHint(QPainter.Antialiasing)
  77. p.scale(self.scale, self.scale)
  78. p.translate(self.offsetToCenter())
  79. p.drawPixmap(0, 0, self.pixmap)
  80. for shape in self.shapes:
  81. shape.paint(p)
  82. if self.current:
  83. self.current.paint(p)
  84. self.line.paint(p)
  85. p.end()
  86. def transformPos(self, point):
  87. """Convert from widget-logical coordinates to painter-logical coordinates."""
  88. return point / self.scale - self.offsetToCenter()
  89. def offsetToCenter(self):
  90. s = self.scale
  91. area = super(Canvas, self).size()
  92. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  93. aw, ah = area.width(), area.height()
  94. x = (aw-w)/(2*s) if aw > w else 0
  95. y = (ah-h)/(2*s) if ah > h else 0
  96. return QPointF(x, y)
  97. def outOfPixmap(self, p):
  98. w, h = self.pixmap.width(), self.pixmap.height()
  99. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  100. def finalise(self):
  101. assert self.current
  102. self.current.fill = True
  103. self.shapes.append(self.current)
  104. self.current = None
  105. self.startLabeling = False
  106. # TODO: Mouse tracking is still useful for selecting shapes!
  107. self.setMouseTracking(False)
  108. self.repaint()
  109. def closeEnough(self, p1, p2):
  110. #d = distance(p1 - p2)
  111. #m = (p1-p2).manhattanLength()
  112. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  113. return distance(p1 - p2) < self.epsilon
  114. # These two, along with a call to adjustSize are required for the
  115. # scroll area.
  116. def sizeHint(self):
  117. return self.minimumSizeHint()
  118. def minimumSizeHint(self):
  119. if self.pixmap:
  120. return self.scale * self.pixmap.size()
  121. return super(Canvas, self).minimumSizeHint()
  122. def wheelEvent(self, ev):
  123. if ev.orientation() == Qt.Vertical:
  124. mods = ev.modifiers()
  125. if Qt.ControlModifier == int(mods):
  126. self.zoomRequest.emit(ev.delta())
  127. else:
  128. self.scrollRequest.emit(ev.delta(),
  129. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  130. else Qt.Vertical)
  131. else:
  132. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  133. ev.accept()
  134. def keyPressEvent(self, ev):
  135. if ev.key() == Qt.Key_Escape and self.current:
  136. self.current = None
  137. self.setMouseTracking(False)
  138. self.repaint()
  139. def distance(p):
  140. return sqrt(p.x() * p.x() + p.y() * p.y())