canvas.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. newShape = pyqtSignal(QPoint)
  9. epsilon = 9.0 # TODO: Tune value
  10. def __init__(self, *args, **kwargs):
  11. super(Canvas, self).__init__(*args, **kwargs)
  12. self.startLabeling=False # has to click new label buttoon to starting drawing new polygons
  13. self.shapes = []
  14. self.current = None
  15. self.selectedShape=None # save the selected shape here
  16. self.selectedShapeCopy=None
  17. self.line_color = QColor(0, 0, 255)
  18. self.line = Shape(line_color=self.line_color)
  19. self.mouseButtonIsPressed=False #when it is true and shape is selected , move the shape with the mouse move event
  20. self.prevPoint=QPoint()
  21. self.scale = 1.0
  22. self.pixmap = None
  23. self.setFocusPolicy(Qt.WheelFocus)
  24. def mouseMoveEvent(self, ev):
  25. """Update line with last point and current coordinates."""
  26. 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
  27. print ev.button()
  28. if self.selectedShapeCopy:
  29. if self.prevPoint:
  30. point=QPoint(self.prevPoint)
  31. dx= ev.x()-point.x()
  32. dy=ev.y()-point.y()
  33. self.selectedShapeCopy.moveBy(dx,dy)
  34. self.repaint()
  35. self.prevPoint=ev.pos()
  36. elif self.selectedShape:
  37. newShape=Shape()
  38. for point in self.selectedShape.points:
  39. newShape.addPoint(point)
  40. self.selectedShapeCopy=newShape
  41. self.repaint()
  42. return
  43. # Polygon drawing.
  44. if self.current and self.startLabeling:
  45. pos = self.transformPos(ev.posF())
  46. color = self.line_color
  47. if self.outOfPixmap(pos):
  48. # Don't allow the user to draw outside the pixmap.
  49. # Project the point to the pixmap's edges.
  50. pos = self.intersectionPoint(pos)
  51. elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  52. # Attract line to starting point and colorise to alert the user:
  53. # TODO: I would also like to highlight the pixel somehow.
  54. pos = self.current[0]
  55. color = self.current.line_color
  56. self.line[1] = pos
  57. self.line.line_color = color
  58. self.repaint()
  59. return
  60. if self.selectedShape:
  61. if self.prevPoint:
  62. point=QPoint(self.prevPoint)
  63. # print point.x()
  64. dx= ev.x()-point.x()
  65. dy=ev.y()-point.y()
  66. self.selectedShape.moveBy(dx,dy)
  67. self.repaint()
  68. self.prevPoint=ev.pos()
  69. def mousePressEvent(self, ev):
  70. if ev.button() == 1:
  71. if self.startLabeling:
  72. if self.current:
  73. self.current.addPoint(self.line[1])
  74. self.line[0] = self.current[-1]
  75. if self.current.isClosed():
  76. self.finalise(ev)
  77. self.repaint()
  78. else:
  79. pos = self.transformPos(ev.posF())
  80. if self.outOfPixmap(pos):
  81. return
  82. self.current = Shape()
  83. self.line.points = [pos, pos]
  84. self.current.addPoint(pos)
  85. self.setMouseTracking(True)
  86. else: # not in adding new label mode
  87. self.selectShape(ev.pos())
  88. self.prevPoint=ev.pos()
  89. def mouseDoubleClickEvent(self, ev):
  90. if self.current and self.startLabeling:
  91. # Add first point in the list so that it is consistent
  92. # with shapes created the normal way.
  93. self.current.addPoint(self.current[0])
  94. self.finalise(ev)
  95. def selectShape(self, point):
  96. """Select the first shape created which contains this point."""
  97. self.deSelectShape()
  98. for shape in self.shapes:
  99. if shape.containsPoint(point):
  100. shape.selected = True
  101. self.selectedShape = shape
  102. return self.repaint()
  103. def deSelectShape(self):
  104. if self.selectedShape:
  105. self.selectedShape.selected = False
  106. self.repaint()
  107. def deleteSelected(self):
  108. if self.selectedShape:
  109. self.shapes.remove(self.selectedShape)
  110. self.selectedShape=None
  111. #print self.selectedShape()
  112. self.repaint()
  113. def paintEvent(self, event):
  114. if not self.pixmap:
  115. return super(Canvas, self).paintEvent(event)
  116. p = QPainter()
  117. p.begin(self)
  118. p.setRenderHint(QPainter.Antialiasing)
  119. p.scale(self.scale, self.scale)
  120. p.translate(self.offsetToCenter())
  121. p.drawPixmap(0, 0, self.pixmap)
  122. for shape in self.shapes:
  123. shape.paint(p)
  124. if self.current:
  125. self.current.paint(p)
  126. self.line.paint(p)
  127. if self.selectedShapeCopy:
  128. self.selectedShapeCopy.paint(p)
  129. p.end()
  130. def transformPos(self, point):
  131. """Convert from widget-logical coordinates to painter-logical coordinates."""
  132. return point / self.scale - self.offsetToCenter()
  133. def offsetToCenter(self):
  134. s = self.scale
  135. area = super(Canvas, self).size()
  136. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  137. aw, ah = area.width(), area.height()
  138. x = (aw-w)/(2*s) if aw > w else 0
  139. y = (ah-h)/(2*s) if ah > h else 0
  140. return QPointF(x, y)
  141. def outOfPixmap(self, p):
  142. w, h = self.pixmap.width(), self.pixmap.height()
  143. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  144. def finalise(self, ev):
  145. assert self.current
  146. self.current.fill = True
  147. self.shapes.append(self.current)
  148. self.current = None
  149. self.startLabeling = False
  150. # TODO: Mouse tracking is still useful for selecting shapes!
  151. self.setMouseTracking(False)
  152. self.repaint()
  153. self.newShape.emit(self.mapToGlobal(ev.pos()))
  154. def closeEnough(self, p1, p2):
  155. #d = distance(p1 - p2)
  156. #m = (p1-p2).manhattanLength()
  157. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  158. return distance(p1 - p2) < self.epsilon
  159. def intersectionPoint(self, mousePos):
  160. # Cycle through each image edge in clockwise fashion,
  161. # and find the one intersecting the current line segment.
  162. # http://paulbourke.net/geometry/lineline2d/
  163. size = self.pixmap.size()
  164. points = [(0,0),
  165. (size.width(), 0),
  166. (size.width(), size.height()),
  167. (0, size.height())]
  168. x1, y1 = self.current[-1].x(), self.current[-1].y()
  169. x2, y2 = mousePos.x(), mousePos.y()
  170. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  171. x3, y3 = points[i]
  172. x4, y4 = points[(i+1)%4]
  173. if (x, y) == (x1, y1):
  174. # Handle cases where previous point is on one of the edges.
  175. if x3 == x4:
  176. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  177. else: # y3 == y4
  178. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  179. return QPointF(x, y)
  180. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  181. """For each edge formed by `points', yield the intersection
  182. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  183. Also return the distance of `(x2,y2)' to the middle of the
  184. edge along with its index, so that the one closest can be chosen."""
  185. for i in xrange(4):
  186. x3, y3 = points[i]
  187. x4, y4 = points[(i+1) % 4]
  188. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  189. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  190. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  191. if denom == 0:
  192. # This covers two cases:
  193. # nua == nub == 0: Coincident
  194. # otherwise: Parallel
  195. continue
  196. ua, ub = nua / denom, nub / denom
  197. if 0 <= ua <= 1 and 0 <= ub <= 1:
  198. x = x1 + ua * (x2 - x1)
  199. y = y1 + ua * (y2 - y1)
  200. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  201. d = distance(m - QPointF(x2, y2))
  202. yield d, i, (x, y)
  203. # These two, along with a call to adjustSize are required for the
  204. # scroll area.
  205. def sizeHint(self):
  206. return self.minimumSizeHint()
  207. def minimumSizeHint(self):
  208. if self.pixmap:
  209. return self.scale * self.pixmap.size()
  210. return super(Canvas, self).minimumSizeHint()
  211. def wheelEvent(self, ev):
  212. if ev.orientation() == Qt.Vertical:
  213. mods = ev.modifiers()
  214. if Qt.ControlModifier == int(mods):
  215. self.zoomRequest.emit(ev.delta())
  216. else:
  217. self.scrollRequest.emit(ev.delta(),
  218. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  219. else Qt.Vertical)
  220. else:
  221. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  222. ev.accept()
  223. def keyPressEvent(self, ev):
  224. if ev.key() == Qt.Key_Escape and self.current:
  225. self.current = None
  226. self.setMouseTracking(False)
  227. self.repaint()
  228. def setLastLabel(self, text):
  229. assert text
  230. print "Setting shape label to %r" % text
  231. self.shapes[-1].label = text
  232. def undoLastLine(self):
  233. print "Undoing last line"
  234. def deleteLastShape(self):
  235. print "Deleting last shape"
  236. def distance(p):
  237. return sqrt(p.x() * p.x() + p.y() * p.y())