canvas.py 9.5 KB

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