canvas.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. #
  2. # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
  3. #
  4. # This file is part of Labelme.
  5. #
  6. # Labelme is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # Labelme is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Labelme. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. from PyQt4.QtGui import *
  20. from PyQt4.QtCore import *
  21. #from PyQt4.QtOpenGL import *
  22. from labelme.shape import Shape
  23. from labelme.lib import distance
  24. # TODO:
  25. # - [maybe] Find optimal epsilon value.
  26. CURSOR_DEFAULT = Qt.ArrowCursor
  27. CURSOR_POINT = Qt.PointingHandCursor
  28. CURSOR_DRAW = Qt.CrossCursor
  29. CURSOR_MOVE = Qt.ClosedHandCursor
  30. CURSOR_GRAB = Qt.OpenHandCursor
  31. #class Canvas(QGLWidget):
  32. class Canvas(QWidget):
  33. zoomRequest = pyqtSignal(int)
  34. scrollRequest = pyqtSignal(int, int)
  35. newShape = pyqtSignal()
  36. selectionChanged = pyqtSignal(bool)
  37. shapeMoved = pyqtSignal()
  38. drawingPolygon = pyqtSignal(bool)
  39. CREATE, EDIT = range(2)
  40. epsilon = 11.0
  41. def __init__(self, *args, **kwargs):
  42. super(Canvas, self).__init__(*args, **kwargs)
  43. # Initialise local state.
  44. self.mode = self.EDIT
  45. self.shapes = []
  46. self.current = None
  47. self.selectedShape=None # save the selected shape here
  48. self.selectedShapeCopy=None
  49. self.lineColor = QColor(0, 0, 255)
  50. self.line = Shape(line_color=self.lineColor)
  51. self.prevPoint = QPointF()
  52. self.offsets = QPointF(), QPointF()
  53. self.scale = 1.0
  54. self.pixmap = QPixmap()
  55. self.visible = {}
  56. self._hideBackround = False
  57. self.hideBackround = False
  58. self.hShape = None
  59. self.hVertex = None
  60. self._painter = QPainter()
  61. self._cursor = CURSOR_DEFAULT
  62. # Menus:
  63. self.menus = (QMenu(), QMenu())
  64. # Set widget options.
  65. self.setMouseTracking(True)
  66. self.setFocusPolicy(Qt.WheelFocus)
  67. def enterEvent(self, ev):
  68. self.overrideCursor(self._cursor)
  69. def leaveEvent(self, ev):
  70. self.restoreCursor()
  71. def focusOutEvent(self, ev):
  72. self.restoreCursor()
  73. def isVisible(self, shape):
  74. return self.visible.get(shape, True)
  75. def drawing(self):
  76. return self.mode == self.CREATE
  77. def editing(self):
  78. return self.mode == self.EDIT
  79. def setEditing(self, value=True):
  80. self.mode = self.EDIT if value else self.CREATE
  81. if not value: # Create
  82. self.unHighlight()
  83. self.deSelectShape()
  84. def unHighlight(self):
  85. if self.hShape:
  86. self.hShape.highlightClear()
  87. self.hVertex = self.hShape = None
  88. def selectedVertex(self):
  89. return self.hVertex is not None
  90. def mouseMoveEvent(self, ev):
  91. """Update line with last point and current coordinates."""
  92. pos = self.transformPos(ev.posF())
  93. self.restoreCursor()
  94. # Polygon drawing.
  95. if self.drawing():
  96. self.overrideCursor(CURSOR_DRAW)
  97. if self.current:
  98. color = self.lineColor
  99. if self.outOfPixmap(pos):
  100. # Don't allow the user to draw outside the pixmap.
  101. # Project the point to the pixmap's edges.
  102. pos = self.intersectionPoint(self.current[-1], pos)
  103. elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  104. # Attract line to starting point and colorise to alert the user:
  105. pos = self.current[0]
  106. color = self.current.line_color
  107. self.overrideCursor(CURSOR_POINT)
  108. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  109. self.line[1] = pos
  110. self.line.line_color = color
  111. self.repaint()
  112. self.current.highlightClear()
  113. return
  114. # Polygon copy moving.
  115. if Qt.RightButton & ev.buttons():
  116. if self.selectedShapeCopy and self.prevPoint:
  117. self.overrideCursor(CURSOR_MOVE)
  118. self.boundedMoveShape(self.selectedShapeCopy, pos)
  119. self.repaint()
  120. elif self.selectedShape:
  121. self.selectedShapeCopy = self.selectedShape.copy()
  122. self.repaint()
  123. return
  124. # Polygon/Vertex moving.
  125. if Qt.LeftButton & ev.buttons():
  126. if self.selectedVertex():
  127. self.boundedMoveVertex(pos)
  128. self.shapeMoved.emit()
  129. self.repaint()
  130. elif self.selectedShape and self.prevPoint:
  131. self.overrideCursor(CURSOR_MOVE)
  132. self.boundedMoveShape(self.selectedShape, pos)
  133. self.shapeMoved.emit()
  134. self.repaint()
  135. return
  136. # Just hovering over the canvas, 2 posibilities:
  137. # - Highlight shapes
  138. # - Highlight vertex
  139. # Update shape/vertex fill and tooltip value accordingly.
  140. self.setToolTip("Image")
  141. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  142. # Look for a nearby vertex to highlight. If that fails,
  143. # check if we happen to be inside a shape.
  144. index = shape.nearestVertex(pos, self.epsilon)
  145. if index is not None:
  146. if self.selectedVertex():
  147. self.hShape.highlightClear()
  148. self.hVertex, self.hShape = index, shape
  149. shape.highlightVertex(index, shape.MOVE_VERTEX)
  150. self.overrideCursor(CURSOR_POINT)
  151. self.setToolTip("Click & drag to move point")
  152. self.setStatusTip(self.toolTip())
  153. self.update()
  154. break
  155. elif shape.containsPoint(pos):
  156. if self.selectedVertex():
  157. self.hShape.highlightClear()
  158. self.hVertex, self.hShape = None, shape
  159. self.setToolTip("Click & drag to move shape '%s'" % shape.label)
  160. self.setStatusTip(self.toolTip())
  161. self.overrideCursor(CURSOR_GRAB)
  162. self.update()
  163. break
  164. else: # Nothing found, clear highlights, reset state.
  165. if self.hShape:
  166. self.hShape.highlightClear()
  167. self.update()
  168. self.hVertex, self.hShape = None, None
  169. def mousePressEvent(self, ev):
  170. pos = self.transformPos(ev.posF())
  171. if ev.button() == Qt.LeftButton:
  172. if self.drawing():
  173. if self.current:
  174. self.current.addPoint(self.line[1])
  175. self.line[0] = self.current[-1]
  176. if self.current.isClosed():
  177. self.finalise()
  178. elif not self.outOfPixmap(pos):
  179. self.current = Shape()
  180. self.current.addPoint(pos)
  181. self.line.points = [pos, pos]
  182. self.setHiding()
  183. self.drawingPolygon.emit(True)
  184. self.update()
  185. else:
  186. self.selectShapePoint(pos)
  187. self.prevPoint = pos
  188. self.repaint()
  189. elif ev.button() == Qt.RightButton and self.editing():
  190. self.selectShapePoint(pos)
  191. self.prevPoint = pos
  192. self.repaint()
  193. def mouseReleaseEvent(self, ev):
  194. if ev.button() == Qt.RightButton:
  195. menu = self.menus[bool(self.selectedShapeCopy)]
  196. self.restoreCursor()
  197. if not menu.exec_(self.mapToGlobal(ev.pos()))\
  198. and self.selectedShapeCopy:
  199. # Cancel the move by deleting the shadow copy.
  200. self.selectedShapeCopy = None
  201. self.repaint()
  202. elif ev.button() == Qt.LeftButton and self.selectedShape:
  203. self.overrideCursor(CURSOR_GRAB)
  204. def endMove(self, copy=False):
  205. assert self.selectedShape and self.selectedShapeCopy
  206. shape = self.selectedShapeCopy
  207. #del shape.fill_color
  208. #del shape.line_color
  209. if copy:
  210. self.shapes.append(shape)
  211. self.selectedShape.selected = False
  212. self.selectedShape = shape
  213. self.repaint()
  214. else:
  215. shape.label = self.selectedShape.label
  216. self.deleteSelected()
  217. self.shapes.append(shape)
  218. self.selectedShapeCopy = None
  219. def hideBackroundShapes(self, value):
  220. self.hideBackround = value
  221. if self.selectedShape:
  222. # Only hide other shapes if there is a current selection.
  223. # Otherwise the user will not be able to select a shape.
  224. self.setHiding(True)
  225. self.repaint()
  226. def setHiding(self, enable=True):
  227. self._hideBackround = self.hideBackround if enable else False
  228. def canCloseShape(self):
  229. return self.drawing() and self.current and len(self.current) > 2
  230. def mouseDoubleClickEvent(self, ev):
  231. # We need at least 4 points here, since the mousePress handler
  232. # adds an extra one before this handler is called.
  233. if self.canCloseShape() and len(self.current) > 3:
  234. self.current.popPoint()
  235. self.finalise()
  236. def selectShape(self, shape):
  237. self.deSelectShape()
  238. shape.selected = True
  239. self.selectedShape = shape
  240. self.setHiding()
  241. self.selectionChanged.emit(True)
  242. self.update()
  243. def selectShapePoint(self, point):
  244. """Select the first shape created which contains this point."""
  245. self.deSelectShape()
  246. if self.selectedVertex(): # A vertex is marked for selection.
  247. index, shape = self.hVertex, self.hShape
  248. shape.highlightVertex(index, shape.MOVE_VERTEX)
  249. return
  250. for shape in reversed(self.shapes):
  251. if self.isVisible(shape) and shape.containsPoint(point):
  252. shape.selected = True
  253. self.selectedShape = shape
  254. self.calculateOffsets(shape, point)
  255. self.setHiding()
  256. self.selectionChanged.emit(True)
  257. return
  258. def calculateOffsets(self, shape, point):
  259. rect = shape.boundingRect()
  260. x1 = rect.x() - point.x()
  261. y1 = rect.y() - point.y()
  262. x2 = (rect.x() + rect.width()) - point.x()
  263. y2 = (rect.y() + rect.height()) - point.y()
  264. self.offsets = QPointF(x1, y1), QPointF(x2, y2)
  265. def boundedMoveVertex(self, pos):
  266. index, shape = self.hVertex, self.hShape
  267. point = shape[index]
  268. if self.outOfPixmap(pos):
  269. pos = self.intersectionPoint(point, pos)
  270. shape.moveVertexBy(index, pos - point)
  271. def boundedMoveShape(self, shape, pos):
  272. if self.outOfPixmap(pos):
  273. return False # No need to move
  274. o1 = pos + self.offsets[0]
  275. if self.outOfPixmap(o1):
  276. pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
  277. o2 = pos + self.offsets[1]
  278. if self.outOfPixmap(o2):
  279. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  280. min(0, self.pixmap.height()- o2.y()))
  281. # The next line tracks the new position of the cursor
  282. # relative to the shape, but also results in making it
  283. # a bit "shaky" when nearing the border and allows it to
  284. # go outside of the shape's area for some reason. XXX
  285. #self.calculateOffsets(self.selectedShape, pos)
  286. dp = pos - self.prevPoint
  287. if dp:
  288. shape.moveBy(dp)
  289. self.prevPoint = pos
  290. return True
  291. return False
  292. def deSelectShape(self):
  293. if self.selectedShape:
  294. self.selectedShape.selected = False
  295. self.selectedShape = None
  296. self.setHiding(False)
  297. self.selectionChanged.emit(False)
  298. self.update()
  299. def deleteSelected(self):
  300. if self.selectedShape:
  301. shape = self.selectedShape
  302. self.shapes.remove(self.selectedShape)
  303. self.selectedShape = None
  304. self.update()
  305. return shape
  306. def copySelectedShape(self):
  307. if self.selectedShape:
  308. shape = self.selectedShape.copy()
  309. self.deSelectShape()
  310. self.shapes.append(shape)
  311. shape.selected = True
  312. self.selectedShape = shape
  313. self.boundedShiftShape(shape)
  314. return shape
  315. def boundedShiftShape(self, shape):
  316. # Try to move in one direction, and if it fails in another.
  317. # Give up if both fail.
  318. point = shape[0]
  319. offset = QPointF(2.0, 2.0)
  320. self.calculateOffsets(shape, point)
  321. self.prevPoint = point
  322. if not self.boundedMoveShape(shape, point - offset):
  323. self.boundedMoveShape(shape, point + offset)
  324. def paintEvent(self, event):
  325. if not self.pixmap:
  326. return super(Canvas, self).paintEvent(event)
  327. p = self._painter
  328. p.begin(self)
  329. p.setRenderHint(QPainter.Antialiasing)
  330. p.setRenderHint(QPainter.HighQualityAntialiasing)
  331. p.setRenderHint(QPainter.SmoothPixmapTransform)
  332. p.scale(self.scale, self.scale)
  333. p.translate(self.offsetToCenter())
  334. p.drawPixmap(0, 0, self.pixmap)
  335. Shape.scale = self.scale
  336. for shape in self.shapes:
  337. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  338. shape.fill = shape.selected or shape == self.hShape
  339. shape.paint(p)
  340. if self.current:
  341. self.current.paint(p)
  342. self.line.paint(p)
  343. if self.selectedShapeCopy:
  344. self.selectedShapeCopy.paint(p)
  345. p.end()
  346. def transformPos(self, point):
  347. """Convert from widget-logical coordinates to painter-logical coordinates."""
  348. return point / self.scale - self.offsetToCenter()
  349. def offsetToCenter(self):
  350. s = self.scale
  351. area = super(Canvas, self).size()
  352. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  353. aw, ah = area.width(), area.height()
  354. x = (aw-w)/(2*s) if aw > w else 0
  355. y = (ah-h)/(2*s) if ah > h else 0
  356. return QPointF(x, y)
  357. def outOfPixmap(self, p):
  358. w, h = self.pixmap.width(), self.pixmap.height()
  359. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  360. def finalise(self):
  361. assert self.current
  362. self.current.close()
  363. self.shapes.append(self.current)
  364. self.current = None
  365. self.setHiding(False)
  366. self.newShape.emit()
  367. self.update()
  368. def closeEnough(self, p1, p2):
  369. #d = distance(p1 - p2)
  370. #m = (p1-p2).manhattanLength()
  371. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  372. return distance(p1 - p2) < self.epsilon
  373. def intersectionPoint(self, p1, p2):
  374. # Cycle through each image edge in clockwise fashion,
  375. # and find the one intersecting the current line segment.
  376. # http://paulbourke.net/geometry/lineline2d/
  377. size = self.pixmap.size()
  378. points = [(0,0),
  379. (size.width(), 0),
  380. (size.width(), size.height()),
  381. (0, size.height())]
  382. x1, y1 = p1.x(), p1.y()
  383. x2, y2 = p2.x(), p2.y()
  384. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  385. x3, y3 = points[i]
  386. x4, y4 = points[(i+1)%4]
  387. if (x, y) == (x1, y1):
  388. # Handle cases where previous point is on one of the edges.
  389. if x3 == x4:
  390. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  391. else: # y3 == y4
  392. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  393. return QPointF(x, y)
  394. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  395. """For each edge formed by `points', yield the intersection
  396. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  397. Also return the distance of `(x2,y2)' to the middle of the
  398. edge along with its index, so that the one closest can be chosen."""
  399. for i in xrange(4):
  400. x3, y3 = points[i]
  401. x4, y4 = points[(i+1) % 4]
  402. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  403. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  404. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  405. if denom == 0:
  406. # This covers two cases:
  407. # nua == nub == 0: Coincident
  408. # otherwise: Parallel
  409. continue
  410. ua, ub = nua / denom, nub / denom
  411. if 0 <= ua <= 1 and 0 <= ub <= 1:
  412. x = x1 + ua * (x2 - x1)
  413. y = y1 + ua * (y2 - y1)
  414. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  415. d = distance(m - QPointF(x2, y2))
  416. yield d, i, (x, y)
  417. # These two, along with a call to adjustSize are required for the
  418. # scroll area.
  419. def sizeHint(self):
  420. return self.minimumSizeHint()
  421. def minimumSizeHint(self):
  422. if self.pixmap:
  423. return self.scale * self.pixmap.size()
  424. return super(Canvas, self).minimumSizeHint()
  425. def wheelEvent(self, ev):
  426. if ev.orientation() == Qt.Vertical:
  427. mods = ev.modifiers()
  428. if Qt.ControlModifier == int(mods):
  429. self.zoomRequest.emit(ev.delta())
  430. else:
  431. self.scrollRequest.emit(ev.delta(),
  432. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  433. else Qt.Vertical)
  434. else:
  435. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  436. ev.accept()
  437. def keyPressEvent(self, ev):
  438. key = ev.key()
  439. if key == Qt.Key_Escape and self.current:
  440. self.current = None
  441. self.drawingPolygon.emit(False)
  442. self.update()
  443. elif key == Qt.Key_Return and self.canCloseShape():
  444. self.finalise()
  445. def setLastLabel(self, text):
  446. assert text
  447. self.shapes[-1].label = text
  448. return self.shapes[-1]
  449. def undoLastLine(self):
  450. assert self.shapes
  451. self.current = self.shapes.pop()
  452. self.current.setOpen()
  453. self.line.points = [self.current[-1], self.current[0]]
  454. self.drawingPolygon.emit(True)
  455. def loadPixmap(self, pixmap):
  456. self.pixmap = pixmap
  457. self.shapes = []
  458. self.repaint()
  459. def loadShapes(self, shapes):
  460. self.shapes = list(shapes)
  461. self.current = None
  462. self.repaint()
  463. def setShapeVisible(self, shape, value):
  464. self.visible[shape] = value
  465. self.repaint()
  466. def overrideCursor(self, cursor):
  467. self.restoreCursor()
  468. self._cursor = cursor
  469. QApplication.setOverrideCursor(cursor)
  470. def restoreCursor(self):
  471. QApplication.restoreOverrideCursor()
  472. def resetState(self):
  473. self.restoreCursor()
  474. self.pixmap = None
  475. self.update()