canvas.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. from qtpy import QtCore
  2. from qtpy import QtGui
  3. from qtpy import QtWidgets
  4. from labelme import QT5
  5. from labelme.shape import Shape
  6. import labelme.utils
  7. # TODO(unknown):
  8. # - [maybe] Find optimal epsilon value.
  9. CURSOR_DEFAULT = QtCore.Qt.ArrowCursor
  10. CURSOR_POINT = QtCore.Qt.PointingHandCursor
  11. CURSOR_DRAW = QtCore.Qt.CrossCursor
  12. CURSOR_MOVE = QtCore.Qt.ClosedHandCursor
  13. CURSOR_GRAB = QtCore.Qt.OpenHandCursor
  14. class Canvas(QtWidgets.QWidget):
  15. zoomRequest = QtCore.Signal(int, QtCore.QPoint)
  16. scrollRequest = QtCore.Signal(int, int)
  17. newShape = QtCore.Signal()
  18. selectionChanged = QtCore.Signal(bool)
  19. shapeMoved = QtCore.Signal()
  20. drawingPolygon = QtCore.Signal(bool)
  21. edgeSelected = QtCore.Signal(bool)
  22. CREATE, EDIT = 0, 1
  23. # polygon, rectangle, line, or point
  24. _createMode = 'polygon'
  25. _fill_drawing = False
  26. def __init__(self, *args, **kwargs):
  27. self.epsilon = kwargs.pop('epsilon', 11.0)
  28. super(Canvas, self).__init__(*args, **kwargs)
  29. # Initialise local state.
  30. self.mode = self.EDIT
  31. self.shapes = []
  32. self.shapesBackups = []
  33. self.current = None
  34. self.selectedShape = None # save the selected shape here
  35. self.selectedShapeCopy = None
  36. self.lineColor = QtGui.QColor(0, 0, 255)
  37. # self.line represents:
  38. # - createMode == 'polygon': edge from last point to current
  39. # - createMode == 'rectangle': diagonal line of the rectangle
  40. # - createMode == 'line': the line
  41. # - createMode == 'point': the point
  42. self.line = Shape(line_color=self.lineColor)
  43. self.prevPoint = QtCore.QPoint()
  44. self.prevMovePoint = QtCore.QPoint()
  45. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  46. self.scale = 1.0
  47. self.pixmap = QtGui.QPixmap()
  48. self.visible = {}
  49. self._hideBackround = False
  50. self.hideBackround = False
  51. self.hShape = None
  52. self.hVertex = None
  53. self.hEdge = None
  54. self.movingShape = False
  55. self._painter = QtGui.QPainter()
  56. self._cursor = CURSOR_DEFAULT
  57. # Menus:
  58. self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
  59. # Set widget options.
  60. self.setMouseTracking(True)
  61. self.setFocusPolicy(QtCore.Qt.WheelFocus)
  62. def fillDrawing(self):
  63. return self._fill_drawing
  64. def setFillDrawing(self, value):
  65. self._fill_drawing = value
  66. @property
  67. def createMode(self):
  68. return self._createMode
  69. @createMode.setter
  70. def createMode(self, value):
  71. if value not in ['polygon', 'rectangle', 'line', 'point']:
  72. raise ValueError('Unsupported createMode: %s' % value)
  73. self._createMode = value
  74. def storeShapes(self):
  75. shapesBackup = []
  76. for shape in self.shapes:
  77. shapesBackup.append(shape.copy())
  78. if len(self.shapesBackups) >= 10:
  79. self.shapesBackups = self.shapesBackups[-9:]
  80. self.shapesBackups.append(shapesBackup)
  81. @property
  82. def isShapeRestorable(self):
  83. if len(self.shapesBackups) < 2:
  84. return False
  85. return True
  86. def restoreShape(self):
  87. if not self.isShapeRestorable:
  88. return
  89. self.shapesBackups.pop() # latest
  90. shapesBackup = self.shapesBackups.pop()
  91. self.shapes = shapesBackup
  92. self.storeShapes()
  93. self.repaint()
  94. def enterEvent(self, ev):
  95. self.overrideCursor(self._cursor)
  96. def leaveEvent(self, ev):
  97. self.restoreCursor()
  98. def focusOutEvent(self, ev):
  99. self.restoreCursor()
  100. def isVisible(self, shape):
  101. return self.visible.get(shape, True)
  102. def drawing(self):
  103. return self.mode == self.CREATE
  104. def editing(self):
  105. return self.mode == self.EDIT
  106. def setEditing(self, value=True):
  107. self.mode = self.EDIT if value else self.CREATE
  108. if not value: # Create
  109. self.unHighlight()
  110. self.deSelectShape()
  111. def unHighlight(self):
  112. if self.hShape:
  113. self.hShape.highlightClear()
  114. self.hVertex = self.hShape = None
  115. def selectedVertex(self):
  116. return self.hVertex is not None
  117. def mouseMoveEvent(self, ev):
  118. """Update line with last point and current coordinates."""
  119. if QT5:
  120. pos = self.transformPos(ev.pos())
  121. else:
  122. pos = self.transformPos(ev.posF())
  123. self.prevMovePoint = pos
  124. self.restoreCursor()
  125. # Polygon drawing.
  126. if self.drawing():
  127. self.line.shape_type = self.createMode
  128. self.overrideCursor(CURSOR_DRAW)
  129. if not self.current:
  130. return
  131. color = self.lineColor
  132. if self.outOfPixmap(pos):
  133. # Don't allow the user to draw outside the pixmap.
  134. # Project the point to the pixmap's edges.
  135. pos = self.intersectionPoint(self.current[-1], pos)
  136. elif len(self.current) > 1 and \
  137. self.closeEnough(pos, self.current[0]):
  138. # Attract line to starting point and
  139. # colorise to alert the user.
  140. pos = self.current[0]
  141. color = self.current.line_color
  142. self.overrideCursor(CURSOR_POINT)
  143. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  144. if self.createMode == 'polygon':
  145. self.line[0] = self.current[-1]
  146. self.line[1] = pos
  147. elif self.createMode == 'rectangle':
  148. self.line.points = [self.current[0], pos]
  149. self.line.close()
  150. elif self.createMode == 'line':
  151. self.line.points = [self.current[0], pos]
  152. self.line.close()
  153. elif self.createMode == 'point':
  154. self.line.points = [self.current[0]]
  155. self.line.close()
  156. self.line.line_color = color
  157. self.repaint()
  158. self.current.highlightClear()
  159. return
  160. # Polygon copy moving.
  161. if QtCore.Qt.RightButton & ev.buttons():
  162. if self.selectedShapeCopy and self.prevPoint:
  163. self.overrideCursor(CURSOR_MOVE)
  164. self.boundedMoveShape(self.selectedShapeCopy, pos)
  165. self.repaint()
  166. elif self.selectedShape:
  167. self.selectedShapeCopy = self.selectedShape.copy()
  168. self.repaint()
  169. return
  170. # Polygon/Vertex moving.
  171. self.movingShape = False
  172. if QtCore.Qt.LeftButton & ev.buttons():
  173. if self.selectedVertex():
  174. self.boundedMoveVertex(pos)
  175. self.repaint()
  176. self.movingShape = True
  177. elif self.selectedShape and self.prevPoint:
  178. self.overrideCursor(CURSOR_MOVE)
  179. self.boundedMoveShape(self.selectedShape, pos)
  180. self.repaint()
  181. self.movingShape = True
  182. return
  183. # Just hovering over the canvas, 2 posibilities:
  184. # - Highlight shapes
  185. # - Highlight vertex
  186. # Update shape/vertex fill and tooltip value accordingly.
  187. self.setToolTip("Image")
  188. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  189. # Look for a nearby vertex to highlight. If that fails,
  190. # check if we happen to be inside a shape.
  191. index = shape.nearestVertex(pos, self.epsilon)
  192. index_edge = shape.nearestEdge(pos, self.epsilon)
  193. if index is not None:
  194. if self.selectedVertex():
  195. self.hShape.highlightClear()
  196. self.hVertex = index
  197. self.hShape = shape
  198. self.hEdge = index_edge
  199. shape.highlightVertex(index, shape.MOVE_VERTEX)
  200. self.overrideCursor(CURSOR_POINT)
  201. self.setToolTip("Click & drag to move point")
  202. self.setStatusTip(self.toolTip())
  203. self.update()
  204. break
  205. elif shape.containsPoint(pos):
  206. if self.selectedVertex():
  207. self.hShape.highlightClear()
  208. self.hVertex = None
  209. self.hShape = shape
  210. self.hEdge = index_edge
  211. self.setToolTip(
  212. "Click & drag to move shape '%s'" % shape.label)
  213. self.setStatusTip(self.toolTip())
  214. self.overrideCursor(CURSOR_GRAB)
  215. self.update()
  216. break
  217. else: # Nothing found, clear highlights, reset state.
  218. if self.hShape:
  219. self.hShape.highlightClear()
  220. self.update()
  221. self.hVertex, self.hShape, self.hEdge = None, None, None
  222. self.edgeSelected.emit(self.hEdge is not None)
  223. def addPointToEdge(self):
  224. if (self.hShape is None and
  225. self.hEdge is None and
  226. self.prevMovePoint is None):
  227. return
  228. shape = self.hShape
  229. index = self.hEdge
  230. point = self.prevMovePoint
  231. shape.insertPoint(index, point)
  232. shape.highlightVertex(index, shape.MOVE_VERTEX)
  233. self.hShape = shape
  234. self.hVertex = index
  235. self.hEdge = None
  236. def mousePressEvent(self, ev):
  237. if QT5:
  238. pos = self.transformPos(ev.pos())
  239. else:
  240. pos = self.transformPos(ev.posF())
  241. if ev.button() == QtCore.Qt.LeftButton:
  242. if self.drawing():
  243. if self.current:
  244. # Add point to existing shape.
  245. if self.createMode == 'polygon':
  246. self.current.addPoint(self.line[1])
  247. self.line[0] = self.current[-1]
  248. if self.current.isClosed():
  249. self.finalise()
  250. elif self.createMode in ['rectangle', 'line']:
  251. assert len(self.current.points) == 1
  252. self.current.points = self.line.points
  253. self.finalise()
  254. elif not self.outOfPixmap(pos):
  255. # Create new shape.
  256. self.current = Shape(shape_type=self.createMode)
  257. self.current.addPoint(pos)
  258. if self.createMode == 'point':
  259. self.finalise()
  260. else:
  261. self.line.points = [pos, pos]
  262. self.setHiding()
  263. self.drawingPolygon.emit(True)
  264. self.update()
  265. else:
  266. self.selectShapePoint(pos)
  267. self.prevPoint = pos
  268. self.repaint()
  269. elif ev.button() == QtCore.Qt.RightButton and self.editing():
  270. self.selectShapePoint(pos)
  271. self.prevPoint = pos
  272. self.repaint()
  273. def mouseReleaseEvent(self, ev):
  274. if ev.button() == QtCore.Qt.RightButton:
  275. menu = self.menus[bool(self.selectedShapeCopy)]
  276. self.restoreCursor()
  277. if not menu.exec_(self.mapToGlobal(ev.pos()))\
  278. and self.selectedShapeCopy:
  279. # Cancel the move by deleting the shadow copy.
  280. self.selectedShapeCopy = None
  281. self.repaint()
  282. elif ev.button() == QtCore.Qt.LeftButton and self.selectedShape:
  283. self.overrideCursor(CURSOR_GRAB)
  284. if self.movingShape:
  285. self.storeShapes()
  286. self.shapeMoved.emit()
  287. def endMove(self, copy=False):
  288. assert self.selectedShape and self.selectedShapeCopy
  289. shape = self.selectedShapeCopy
  290. # del shape.fill_color
  291. # del shape.line_color
  292. if copy:
  293. self.shapes.append(shape)
  294. self.selectedShape.selected = False
  295. self.selectedShape = shape
  296. self.repaint()
  297. else:
  298. shape.label = self.selectedShape.label
  299. self.deleteSelected()
  300. self.shapes.append(shape)
  301. self.storeShapes()
  302. self.selectedShapeCopy = None
  303. def hideBackroundShapes(self, value):
  304. self.hideBackround = value
  305. if self.selectedShape:
  306. # Only hide other shapes if there is a current selection.
  307. # Otherwise the user will not be able to select a shape.
  308. self.setHiding(True)
  309. self.repaint()
  310. def setHiding(self, enable=True):
  311. self._hideBackround = self.hideBackround if enable else False
  312. def canCloseShape(self):
  313. return self.drawing() and self.current and len(self.current) > 2
  314. def mouseDoubleClickEvent(self, ev):
  315. # We need at least 4 points here, since the mousePress handler
  316. # adds an extra one before this handler is called.
  317. if self.canCloseShape() and len(self.current) > 3:
  318. self.current.popPoint()
  319. self.finalise()
  320. def selectShape(self, shape):
  321. self.deSelectShape()
  322. shape.selected = True
  323. self.selectedShape = shape
  324. self.setHiding()
  325. self.selectionChanged.emit(True)
  326. self.update()
  327. def selectShapePoint(self, point):
  328. """Select the first shape created which contains this point."""
  329. self.deSelectShape()
  330. if self.selectedVertex(): # A vertex is marked for selection.
  331. index, shape = self.hVertex, self.hShape
  332. shape.highlightVertex(index, shape.MOVE_VERTEX)
  333. return
  334. for shape in reversed(self.shapes):
  335. if self.isVisible(shape) and shape.containsPoint(point):
  336. shape.selected = True
  337. self.selectedShape = shape
  338. self.calculateOffsets(shape, point)
  339. self.setHiding()
  340. self.selectionChanged.emit(True)
  341. return
  342. def calculateOffsets(self, shape, point):
  343. rect = shape.boundingRect()
  344. x1 = rect.x() - point.x()
  345. y1 = rect.y() - point.y()
  346. x2 = (rect.x() + rect.width()) - point.x()
  347. y2 = (rect.y() + rect.height()) - point.y()
  348. self.offsets = QtCore.QPoint(x1, y1), QtCore.QPoint(x2, y2)
  349. def boundedMoveVertex(self, pos):
  350. index, shape = self.hVertex, self.hShape
  351. point = shape[index]
  352. if self.outOfPixmap(pos):
  353. pos = self.intersectionPoint(point, pos)
  354. shape.moveVertexBy(index, pos - point)
  355. def boundedMoveShape(self, shape, pos):
  356. if self.outOfPixmap(pos):
  357. return False # No need to move
  358. o1 = pos + self.offsets[0]
  359. if self.outOfPixmap(o1):
  360. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  361. o2 = pos + self.offsets[1]
  362. if self.outOfPixmap(o2):
  363. pos += QtCore.QPoint(min(0, self.pixmap.width() - o2.x()),
  364. min(0, self.pixmap.height() - o2.y()))
  365. # XXX: The next line tracks the new position of the cursor
  366. # relative to the shape, but also results in making it
  367. # a bit "shaky" when nearing the border and allows it to
  368. # go outside of the shape's area for some reason.
  369. # self.calculateOffsets(self.selectedShape, pos)
  370. dp = pos - self.prevPoint
  371. if dp:
  372. shape.moveBy(dp)
  373. self.prevPoint = pos
  374. return True
  375. return False
  376. def deSelectShape(self):
  377. if self.selectedShape:
  378. self.selectedShape.selected = False
  379. self.selectedShape = None
  380. self.setHiding(False)
  381. self.selectionChanged.emit(False)
  382. self.update()
  383. def deleteSelected(self):
  384. if self.selectedShape:
  385. shape = self.selectedShape
  386. self.shapes.remove(self.selectedShape)
  387. self.storeShapes()
  388. self.selectedShape = None
  389. self.update()
  390. return shape
  391. def copySelectedShape(self):
  392. if self.selectedShape:
  393. shape = self.selectedShape.copy()
  394. self.deSelectShape()
  395. self.shapes.append(shape)
  396. self.storeShapes()
  397. shape.selected = True
  398. self.selectedShape = shape
  399. self.boundedShiftShape(shape)
  400. return shape
  401. def boundedShiftShape(self, shape):
  402. # Try to move in one direction, and if it fails in another.
  403. # Give up if both fail.
  404. point = shape[0]
  405. offset = QtCore.QPoint(2.0, 2.0)
  406. self.calculateOffsets(shape, point)
  407. self.prevPoint = point
  408. if not self.boundedMoveShape(shape, point - offset):
  409. self.boundedMoveShape(shape, point + offset)
  410. def paintEvent(self, event):
  411. if not self.pixmap:
  412. return super(Canvas, self).paintEvent(event)
  413. p = self._painter
  414. p.begin(self)
  415. p.setRenderHint(QtGui.QPainter.Antialiasing)
  416. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  417. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  418. p.scale(self.scale, self.scale)
  419. p.translate(self.offsetToCenter())
  420. p.drawPixmap(0, 0, self.pixmap)
  421. Shape.scale = self.scale
  422. for shape in self.shapes:
  423. if (shape.selected or not self._hideBackround) and \
  424. self.isVisible(shape):
  425. shape.fill = shape.selected or shape == self.hShape
  426. shape.paint(p)
  427. if self.current:
  428. self.current.paint(p)
  429. self.line.paint(p)
  430. if self.selectedShapeCopy:
  431. self.selectedShapeCopy.paint(p)
  432. if (self.fillDrawing() and self.createMode == 'polygon' and
  433. self.current is not None and len(self.current.points) >= 2):
  434. drawing_shape = self.current.copy()
  435. drawing_shape.addPoint(self.line[1])
  436. drawing_shape.fill = True
  437. drawing_shape.fill_color.setAlpha(64)
  438. drawing_shape.paint(p)
  439. p.end()
  440. def transformPos(self, point):
  441. """Convert from widget-logical coordinates to painter-logical ones."""
  442. return point / self.scale - self.offsetToCenter()
  443. def offsetToCenter(self):
  444. s = self.scale
  445. area = super(Canvas, self).size()
  446. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  447. aw, ah = area.width(), area.height()
  448. x = (aw - w) / (2 * s) if aw > w else 0
  449. y = (ah - h) / (2 * s) if ah > h else 0
  450. return QtCore.QPoint(x, y)
  451. def outOfPixmap(self, p):
  452. w, h = self.pixmap.width(), self.pixmap.height()
  453. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  454. def finalise(self):
  455. assert self.current
  456. self.current.close()
  457. self.shapes.append(self.current)
  458. self.storeShapes()
  459. self.current = None
  460. self.setHiding(False)
  461. self.newShape.emit()
  462. self.update()
  463. def closeEnough(self, p1, p2):
  464. # d = distance(p1 - p2)
  465. # m = (p1-p2).manhattanLength()
  466. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  467. return labelme.utils.distance(p1 - p2) < self.epsilon
  468. def intersectionPoint(self, p1, p2):
  469. # Cycle through each image edge in clockwise fashion,
  470. # and find the one intersecting the current line segment.
  471. # http://paulbourke.net/geometry/lineline2d/
  472. size = self.pixmap.size()
  473. points = [(0, 0),
  474. (size.width(), 0),
  475. (size.width(), size.height()),
  476. (0, size.height())]
  477. x1, y1 = p1.x(), p1.y()
  478. x2, y2 = p2.x(), p2.y()
  479. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  480. x3, y3 = points[i]
  481. x4, y4 = points[(i + 1) % 4]
  482. if (x, y) == (x1, y1):
  483. # Handle cases where previous point is on one of the edges.
  484. if x3 == x4:
  485. return QtCore.QPoint(x3, min(max(0, y2), max(y3, y4)))
  486. else: # y3 == y4
  487. return QtCore.QPoint(min(max(0, x2), max(x3, x4)), y3)
  488. return QtCore.QPoint(x, y)
  489. def intersectingEdges(self, point1, point2, points):
  490. """Find intersecting edges.
  491. For each edge formed by `points', yield the intersection
  492. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  493. Also return the distance of `(x2,y2)' to the middle of the
  494. edge along with its index, so that the one closest can be chosen.
  495. """
  496. (x1, y1) = point1
  497. (x2, y2) = point2
  498. for i in range(4):
  499. x3, y3 = points[i]
  500. x4, y4 = points[(i + 1) % 4]
  501. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  502. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  503. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  504. if denom == 0:
  505. # This covers two cases:
  506. # nua == nub == 0: Coincident
  507. # otherwise: Parallel
  508. continue
  509. ua, ub = nua / denom, nub / denom
  510. if 0 <= ua <= 1 and 0 <= ub <= 1:
  511. x = x1 + ua * (x2 - x1)
  512. y = y1 + ua * (y2 - y1)
  513. m = QtCore.QPoint((x3 + x4) / 2, (y3 + y4) / 2)
  514. d = labelme.utils.distance(m - QtCore.QPoint(x2, y2))
  515. yield d, i, (x, y)
  516. # These two, along with a call to adjustSize are required for the
  517. # scroll area.
  518. def sizeHint(self):
  519. return self.minimumSizeHint()
  520. def minimumSizeHint(self):
  521. if self.pixmap:
  522. return self.scale * self.pixmap.size()
  523. return super(Canvas, self).minimumSizeHint()
  524. def wheelEvent(self, ev):
  525. if QT5:
  526. mods = ev.modifiers()
  527. delta = ev.angleDelta()
  528. if QtCore.Qt.ControlModifier == int(mods):
  529. # with Ctrl/Command key
  530. # zoom
  531. self.zoomRequest.emit(delta.y(), ev.pos())
  532. else:
  533. # scroll
  534. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  535. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  536. else:
  537. if ev.orientation() == QtCore.Qt.Vertical:
  538. mods = ev.modifiers()
  539. if QtCore.Qt.ControlModifier == int(mods):
  540. # with Ctrl/Command key
  541. self.zoomRequest.emit(ev.delta(), ev.pos())
  542. else:
  543. self.scrollRequest.emit(
  544. ev.delta(),
  545. QtCore.Qt.Horizontal
  546. if (QtCore.Qt.ShiftModifier == int(mods))
  547. else QtCore.Qt.Vertical)
  548. else:
  549. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  550. ev.accept()
  551. def keyPressEvent(self, ev):
  552. key = ev.key()
  553. if key == QtCore.Qt.Key_Escape and self.current:
  554. self.current = None
  555. self.drawingPolygon.emit(False)
  556. self.update()
  557. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  558. self.finalise()
  559. def setLastLabel(self, text):
  560. assert text
  561. self.shapes[-1].label = text
  562. self.shapesBackups.pop()
  563. self.storeShapes()
  564. return self.shapes[-1]
  565. def undoLastLine(self):
  566. assert self.shapes
  567. self.current = self.shapes.pop()
  568. self.current.setOpen()
  569. if self.createMode == 'polygon':
  570. self.line.points = [self.current[-1], self.current[0]]
  571. elif self.createMode in ['rectangle', 'line']:
  572. self.current.points = self.current.points[0:1]
  573. elif self.createMode == 'point':
  574. self.current = None
  575. self.drawingPolygon.emit(True)
  576. def undoLastPoint(self):
  577. if not self.current or self.current.isClosed():
  578. return
  579. self.current.popPoint()
  580. if len(self.current) > 0:
  581. self.line[0] = self.current[-1]
  582. else:
  583. self.current = None
  584. self.drawingPolygon.emit(False)
  585. self.repaint()
  586. def loadPixmap(self, pixmap):
  587. self.pixmap = pixmap
  588. self.shapes = []
  589. self.repaint()
  590. def loadShapes(self, shapes):
  591. self.shapes = list(shapes)
  592. self.storeShapes()
  593. self.current = None
  594. self.repaint()
  595. def setShapeVisible(self, shape, value):
  596. self.visible[shape] = value
  597. self.repaint()
  598. def overrideCursor(self, cursor):
  599. self.restoreCursor()
  600. self._cursor = cursor
  601. QtWidgets.QApplication.setOverrideCursor(cursor)
  602. def restoreCursor(self):
  603. QtWidgets.QApplication.restoreOverrideCursor()
  604. def resetState(self):
  605. self.restoreCursor()
  606. self.pixmap = None
  607. self.shapesBackups = []
  608. self.update()