canvas.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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.selectedShapeCopy=None
  16. self.line_color = QColor(0, 0, 255)
  17. self.line = Shape(line_color=self.line_color)
  18. self.mouseButtonIsPressed=False #when it is true and shape is selected , move the shape with the mouse move event
  19. self.prevPoint=QPoint()
  20. self.scale = 1.0
  21. self.pixmap = None
  22. self.setFocusPolicy(Qt.WheelFocus)
  23. def mouseMoveEvent(self, ev):
  24. """Update line with last point and current coordinates."""
  25. if (ev.buttons() & 2): # wont work , as ev.buttons doesn't work well , or I haven't known how to use it :) to use right click
  26. print ev.button()
  27. if self.selectedShapeCopy:
  28. if self.prevPoint:
  29. point=QPoint(self.prevPoint)
  30. dx= ev.x()-point.x()
  31. dy=ev.y()-point.y()
  32. self.selectedShapeCopy.moveBy(dx,dy)
  33. self.repaint()
  34. self.prevPoint=ev.pos()
  35. elif self.selectedShape:
  36. newShape=Shape()
  37. for point in self.selectedShape.points:
  38. newShape.addPoint(point)
  39. self.selectedShapeCopy=newShape
  40. self.repaint()
  41. return
  42. if self.current and self.startLabeling:
  43. pos = self.transformPos(ev.posF())
  44. # Don't allow the user to draw outside of the pixmap area.
  45. # FIXME: Project point to pixmap's edge when getting out too fast
  46. if self.outOfPixmap(pos):
  47. return ev.ignore()
  48. if len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  49. # Attract line to starting point and colorise to alert the user:
  50. self.line[1] = self.current[0]
  51. self.line.line_color = self.current.line_color
  52. else:
  53. self.line[1] = pos
  54. self.line.line_color = self.line_color
  55. return self.repaint()
  56. if self.selectedShape:
  57. if self.prevPoint:
  58. point=QPoint(self.prevPoint)
  59. # print point.x()
  60. dx= ev.x()-point.x()
  61. dy=ev.y()-point.y()
  62. self.selectedShape.moveBy(dx,dy)
  63. self.repaint()
  64. self.prevPoint=ev.pos()
  65. def mousePressEvent(self, ev):
  66. if ev.button() == 1:
  67. if self.startLabeling:
  68. if self.current:
  69. self.current.addPoint(self.line[1])
  70. self.line[0] = self.current[-1]
  71. if self.current.isClosed():
  72. self.finalise()
  73. self.repaint()
  74. else:
  75. pos = self.transformPos(ev.posF())
  76. self.current = Shape()
  77. self.line.points = [pos, pos]
  78. self.current.addPoint(pos)
  79. self.setMouseTracking(True)
  80. else: # not in adding new label mode
  81. self.selectShape(ev.pos())
  82. self.prevPoint=ev.pos()
  83. def mouseDoubleClickEvent(self, ev):
  84. if self.current and self.startLabeling:
  85. # Add first point in the list so that it is consistent
  86. # with shapes created the normal way.
  87. self.current.addPoint(self.current[0])
  88. self.finalise()
  89. def selectShape(self, point):
  90. """Select the first shape created which contains this point."""
  91. self.deSelectShape()
  92. for shape in self.shapes:
  93. if shape.containsPoint(point):
  94. shape.selected = True
  95. self.selectedShape = shape
  96. return self.repaint()
  97. def deSelectShape(self):
  98. if self.selectedShape:
  99. self.selectedShape.selected = False
  100. self.repaint()
  101. def deleteSelected(self):
  102. if self.selectedShape:
  103. self.shapes.remove(self.selectedShape)
  104. self.selectedShape=None
  105. #print self.selectedShape()
  106. self.repaint()
  107. def paintEvent(self, event):
  108. if not self.pixmap:
  109. return super(Canvas, self).paintEvent(event)
  110. p = QPainter()
  111. p.begin(self)
  112. p.setRenderHint(QPainter.Antialiasing)
  113. p.scale(self.scale, self.scale)
  114. p.translate(self.offsetToCenter())
  115. p.drawPixmap(0, 0, self.pixmap)
  116. for shape in self.shapes:
  117. shape.paint(p)
  118. if self.current:
  119. self.current.paint(p)
  120. self.line.paint(p)
  121. if self.selectedShapeCopy:
  122. self.selectedShapeCopy.paint(p)
  123. p.end()
  124. def transformPos(self, point):
  125. """Convert from widget-logical coordinates to painter-logical coordinates."""
  126. return point / self.scale - self.offsetToCenter()
  127. def offsetToCenter(self):
  128. s = self.scale
  129. area = super(Canvas, self).size()
  130. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  131. aw, ah = area.width(), area.height()
  132. x = (aw-w)/(2*s) if aw > w else 0
  133. y = (ah-h)/(2*s) if ah > h else 0
  134. return QPointF(x, y)
  135. def outOfPixmap(self, p):
  136. w, h = self.pixmap.width(), self.pixmap.height()
  137. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  138. def finalise(self):
  139. assert self.current
  140. self.current.fill = True
  141. self.shapes.append(self.current)
  142. self.current = None
  143. self.startLabeling = False
  144. # TODO: Mouse tracking is still useful for selecting shapes!
  145. self.setMouseTracking(False)
  146. self.repaint()
  147. def closeEnough(self, p1, p2):
  148. #d = distance(p1 - p2)
  149. #m = (p1-p2).manhattanLength()
  150. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  151. return distance(p1 - p2) < self.epsilon
  152. # These two, along with a call to adjustSize are required for the
  153. # scroll area.
  154. def sizeHint(self):
  155. return self.minimumSizeHint()
  156. def minimumSizeHint(self):
  157. if self.pixmap:
  158. return self.scale * self.pixmap.size()
  159. return super(Canvas, self).minimumSizeHint()
  160. def wheelEvent(self, ev):
  161. if ev.orientation() == Qt.Vertical:
  162. mods = ev.modifiers()
  163. if Qt.ControlModifier == int(mods):
  164. self.zoomRequest.emit(ev.delta())
  165. else:
  166. self.scrollRequest.emit(ev.delta(),
  167. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  168. else Qt.Vertical)
  169. else:
  170. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  171. ev.accept()
  172. def keyPressEvent(self, ev):
  173. if ev.key() == Qt.Key_Escape and self.current:
  174. self.current = None
  175. self.setMouseTracking(False)
  176. self.repaint()
  177. def distance(p):
  178. return sqrt(p.x() * p.x() + p.y() * p.y())