canvas.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. if self.outOfPixmap(pos):
  77. return
  78. self.current = Shape()
  79. self.line.points = [pos, pos]
  80. self.current.addPoint(pos)
  81. self.setMouseTracking(True)
  82. else: # not in adding new label mode
  83. self.selectShape(ev.pos())
  84. self.prevPoint=ev.pos()
  85. def mouseDoubleClickEvent(self, ev):
  86. if self.current and self.startLabeling:
  87. # Add first point in the list so that it is consistent
  88. # with shapes created the normal way.
  89. self.current.addPoint(self.current[0])
  90. self.finalise()
  91. def selectShape(self, point):
  92. """Select the first shape created which contains this point."""
  93. self.deSelectShape()
  94. for shape in self.shapes:
  95. if shape.containsPoint(point):
  96. shape.selected = True
  97. self.selectedShape = shape
  98. return self.repaint()
  99. def deSelectShape(self):
  100. if self.selectedShape:
  101. self.selectedShape.selected = False
  102. self.repaint()
  103. def deleteSelected(self):
  104. if self.selectedShape:
  105. self.shapes.remove(self.selectedShape)
  106. self.selectedShape=None
  107. #print self.selectedShape()
  108. self.repaint()
  109. def paintEvent(self, event):
  110. if not self.pixmap:
  111. return super(Canvas, self).paintEvent(event)
  112. p = QPainter()
  113. p.begin(self)
  114. p.setRenderHint(QPainter.Antialiasing)
  115. p.scale(self.scale, self.scale)
  116. p.translate(self.offsetToCenter())
  117. p.drawPixmap(0, 0, self.pixmap)
  118. for shape in self.shapes:
  119. shape.paint(p)
  120. if self.current:
  121. self.current.paint(p)
  122. self.line.paint(p)
  123. if self.selectedShapeCopy:
  124. self.selectedShapeCopy.paint(p)
  125. p.end()
  126. def transformPos(self, point):
  127. """Convert from widget-logical coordinates to painter-logical coordinates."""
  128. return point / self.scale - self.offsetToCenter()
  129. def offsetToCenter(self):
  130. s = self.scale
  131. area = super(Canvas, self).size()
  132. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  133. aw, ah = area.width(), area.height()
  134. x = (aw-w)/(2*s) if aw > w else 0
  135. y = (ah-h)/(2*s) if ah > h else 0
  136. return QPointF(x, y)
  137. def outOfPixmap(self, p):
  138. w, h = self.pixmap.width(), self.pixmap.height()
  139. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  140. def finalise(self):
  141. assert self.current
  142. self.current.fill = True
  143. self.shapes.append(self.current)
  144. self.current = None
  145. self.startLabeling = False
  146. # TODO: Mouse tracking is still useful for selecting shapes!
  147. self.setMouseTracking(False)
  148. self.repaint()
  149. def closeEnough(self, p1, p2):
  150. #d = distance(p1 - p2)
  151. #m = (p1-p2).manhattanLength()
  152. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  153. return distance(p1 - p2) < self.epsilon
  154. # These two, along with a call to adjustSize are required for the
  155. # scroll area.
  156. def sizeHint(self):
  157. return self.minimumSizeHint()
  158. def minimumSizeHint(self):
  159. if self.pixmap:
  160. return self.scale * self.pixmap.size()
  161. return super(Canvas, self).minimumSizeHint()
  162. def wheelEvent(self, ev):
  163. if ev.orientation() == Qt.Vertical:
  164. mods = ev.modifiers()
  165. if Qt.ControlModifier == int(mods):
  166. self.zoomRequest.emit(ev.delta())
  167. else:
  168. self.scrollRequest.emit(ev.delta(),
  169. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  170. else Qt.Vertical)
  171. else:
  172. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  173. ev.accept()
  174. def keyPressEvent(self, ev):
  175. if ev.key() == Qt.Key_Escape and self.current:
  176. self.current = None
  177. self.setMouseTracking(False)
  178. self.repaint()
  179. def distance(p):
  180. return sqrt(p.x() * p.x() + p.y() * p.y())