canvas.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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(list)
  19. shapeMoved = QtCore.Signal()
  20. drawingPolygon = QtCore.Signal(bool)
  21. vertexSelected = QtCore.Signal(bool)
  22. CREATE, EDIT = 0, 1
  23. CREATE, EDIT = 0, 1
  24. # polygon, rectangle, line, or point
  25. _createMode = "polygon"
  26. _fill_drawing = False
  27. def __init__(self, *args, **kwargs):
  28. self.epsilon = kwargs.pop("epsilon", 10.0)
  29. self.double_click = kwargs.pop("double_click", "close")
  30. if self.double_click not in [None, "close"]:
  31. raise ValueError(
  32. "Unexpected value for double_click event: {}".format(
  33. self.double_click
  34. )
  35. )
  36. self.num_backups = kwargs.pop("num_backups", 10)
  37. super(Canvas, self).__init__(*args, **kwargs)
  38. # Initialise local state.
  39. self.mode = self.EDIT
  40. self.shapes = []
  41. self.shapesBackups = []
  42. self.current = None
  43. self.selectedShapes = [] # save the selected shapes here
  44. self.selectedShapesCopy = []
  45. # self.line represents:
  46. # - createMode == 'polygon': edge from last point to current
  47. # - createMode == 'rectangle': diagonal line of the rectangle
  48. # - createMode == 'line': the line
  49. # - createMode == 'point': the point
  50. self.line = Shape()
  51. self.prevPoint = QtCore.QPoint()
  52. self.prevMovePoint = QtCore.QPoint()
  53. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  54. self.scale = 1.0
  55. self.pixmap = QtGui.QPixmap()
  56. self.visible = {}
  57. self._hideBackround = False
  58. self.hideBackround = False
  59. self.hShape = None
  60. self.prevhShape = None
  61. self.hVertex = None
  62. self.prevhVertex = None
  63. self.hEdge = None
  64. self.prevhEdge = None
  65. self.movingShape = False
  66. self.snapping = True
  67. self.hShapeIsSelected = False
  68. self._painter = QtGui.QPainter()
  69. self._cursor = CURSOR_DEFAULT
  70. # Menus:
  71. # 0: right-click without selection and dragging of shapes
  72. # 1: right-click with selection and dragging of shapes
  73. self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
  74. # Set widget options.
  75. self.setMouseTracking(True)
  76. self.setFocusPolicy(QtCore.Qt.WheelFocus)
  77. def fillDrawing(self):
  78. return self._fill_drawing
  79. def setFillDrawing(self, value):
  80. self._fill_drawing = value
  81. @property
  82. def createMode(self):
  83. return self._createMode
  84. @createMode.setter
  85. def createMode(self, value):
  86. if value not in [
  87. "polygon",
  88. "rectangle",
  89. "circle",
  90. "line",
  91. "point",
  92. "linestrip",
  93. ]:
  94. raise ValueError("Unsupported createMode: %s" % value)
  95. self._createMode = value
  96. def storeShapes(self):
  97. shapesBackup = []
  98. for shape in self.shapes:
  99. shapesBackup.append(shape.copy())
  100. if len(self.shapesBackups) > self.num_backups:
  101. self.shapesBackups = self.shapesBackups[-self.num_backups - 1 :]
  102. self.shapesBackups.append(shapesBackup)
  103. @property
  104. def isShapeRestorable(self):
  105. # We save the state AFTER each edit (not before) so for an
  106. # edit to be undoable, we expect the CURRENT and the PREVIOUS state
  107. # to be in the undo stack.
  108. if len(self.shapesBackups) < 2:
  109. return False
  110. return True
  111. def restoreShape(self):
  112. # This does _part_ of the job of restoring shapes.
  113. # The complete process is also done in app.py::undoShapeEdit
  114. # and app.py::loadShapes and our own Canvas::loadShapes function.
  115. if not self.isShapeRestorable:
  116. return
  117. self.shapesBackups.pop() # latest
  118. # The application will eventually call Canvas.loadShapes which will
  119. # push this right back onto the stack.
  120. shapesBackup = self.shapesBackups.pop()
  121. self.shapes = shapesBackup
  122. self.selectedShapes = []
  123. for shape in self.shapes:
  124. shape.selected = False
  125. self.update()
  126. def enterEvent(self, ev):
  127. self.overrideCursor(self._cursor)
  128. def leaveEvent(self, ev):
  129. self.unHighlight()
  130. self.restoreCursor()
  131. def focusOutEvent(self, ev):
  132. self.restoreCursor()
  133. def isVisible(self, shape):
  134. return self.visible.get(shape, True)
  135. def drawing(self):
  136. return self.mode == self.CREATE
  137. def editing(self):
  138. return self.mode == self.EDIT
  139. def setEditing(self, value=True):
  140. self.mode = self.EDIT if value else self.CREATE
  141. if not value: # Create
  142. self.unHighlight()
  143. self.deSelectShape()
  144. def unHighlight(self):
  145. if self.hShape:
  146. self.hShape.highlightClear()
  147. self.update()
  148. self.prevhShape = self.hShape
  149. self.prevhVertex = self.hVertex
  150. self.prevhEdge = self.hEdge
  151. self.hShape = self.hVertex = self.hEdge = None
  152. def selectedVertex(self):
  153. return self.hVertex is not None
  154. def selectedEdge(self):
  155. return self.hEdge is not None
  156. def mouseMoveEvent(self, ev):
  157. """Update line with last point and current coordinates."""
  158. try:
  159. if QT5:
  160. pos = self.transformPos(ev.localPos())
  161. else:
  162. pos = self.transformPos(ev.posF())
  163. except AttributeError:
  164. return
  165. self.prevMovePoint = pos
  166. self.restoreCursor()
  167. # Polygon drawing.
  168. if self.drawing():
  169. self.line.shape_type = self.createMode
  170. self.overrideCursor(CURSOR_DRAW)
  171. if not self.current:
  172. return
  173. if self.outOfPixmap(pos):
  174. # Don't allow the user to draw outside the pixmap.
  175. # Project the point to the pixmap's edges.
  176. pos = self.intersectionPoint(self.current[-1], pos)
  177. elif (
  178. self.snapping
  179. and len(self.current) > 1
  180. and self.createMode == "polygon"
  181. and self.closeEnough(pos, self.current[0])
  182. ):
  183. # Attract line to starting point and
  184. # colorise to alert the user.
  185. pos = self.current[0]
  186. self.overrideCursor(CURSOR_POINT)
  187. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  188. if self.createMode in ["polygon", "linestrip"]:
  189. self.line[0] = self.current[-1]
  190. self.line[1] = pos
  191. elif self.createMode == "rectangle":
  192. self.line.points = [self.current[0], pos]
  193. self.line.close()
  194. elif self.createMode == "circle":
  195. self.line.points = [self.current[0], pos]
  196. self.line.shape_type = "circle"
  197. elif self.createMode == "line":
  198. self.line.points = [self.current[0], pos]
  199. self.line.close()
  200. elif self.createMode == "point":
  201. self.line.points = [self.current[0]]
  202. self.line.close()
  203. self.repaint()
  204. self.current.highlightClear()
  205. return
  206. # Polygon copy moving.
  207. if QtCore.Qt.RightButton & ev.buttons():
  208. if self.selectedShapesCopy and self.prevPoint:
  209. self.overrideCursor(CURSOR_MOVE)
  210. self.boundedMoveShapes(self.selectedShapesCopy, pos)
  211. self.repaint()
  212. elif self.selectedShapes:
  213. self.selectedShapesCopy = [
  214. s.copy() for s in self.selectedShapes
  215. ]
  216. self.repaint()
  217. return
  218. # Polygon/Vertex moving.
  219. if QtCore.Qt.LeftButton & ev.buttons():
  220. if self.selectedVertex():
  221. self.boundedMoveVertex(pos)
  222. self.repaint()
  223. self.movingShape = True
  224. elif self.selectedShapes and self.prevPoint:
  225. self.overrideCursor(CURSOR_MOVE)
  226. self.boundedMoveShapes(self.selectedShapes, pos)
  227. self.repaint()
  228. self.movingShape = True
  229. return
  230. # Just hovering over the canvas, 2 possibilities:
  231. # - Highlight shapes
  232. # - Highlight vertex
  233. # Update shape/vertex fill and tooltip value accordingly.
  234. self.setToolTip(self.tr("Image"))
  235. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  236. # Look for a nearby vertex to highlight. If that fails,
  237. # check if we happen to be inside a shape.
  238. index = shape.nearestVertex(pos, self.epsilon / self.scale)
  239. index_edge = shape.nearestEdge(pos, self.epsilon / self.scale)
  240. if index is not None:
  241. if self.selectedVertex():
  242. self.hShape.highlightClear()
  243. self.prevhVertex = self.hVertex = index
  244. self.prevhShape = self.hShape = shape
  245. self.prevhEdge = self.hEdge
  246. self.hEdge = None
  247. shape.highlightVertex(index, shape.MOVE_VERTEX)
  248. self.overrideCursor(CURSOR_POINT)
  249. self.setToolTip(self.tr("Click & drag to move point"))
  250. self.setStatusTip(self.toolTip())
  251. self.update()
  252. break
  253. elif index_edge is not None and shape.canAddPoint():
  254. if self.selectedVertex():
  255. self.hShape.highlightClear()
  256. self.prevhVertex = self.hVertex
  257. self.hVertex = None
  258. self.prevhShape = self.hShape = shape
  259. self.prevhEdge = self.hEdge = index_edge
  260. self.overrideCursor(CURSOR_POINT)
  261. self.setToolTip(self.tr("Click to create point"))
  262. self.setStatusTip(self.toolTip())
  263. self.update()
  264. break
  265. elif shape.containsPoint(pos):
  266. if self.selectedVertex():
  267. self.hShape.highlightClear()
  268. self.prevhVertex = self.hVertex
  269. self.hVertex = None
  270. self.prevhShape = self.hShape = shape
  271. self.prevhEdge = self.hEdge
  272. self.hEdge = None
  273. self.setToolTip(
  274. self.tr("Click & drag to move shape '%s'") % shape.label
  275. )
  276. self.setStatusTip(self.toolTip())
  277. self.overrideCursor(CURSOR_GRAB)
  278. self.update()
  279. break
  280. else: # Nothing found, clear highlights, reset state.
  281. self.unHighlight()
  282. self.vertexSelected.emit(self.hVertex is not None)
  283. def addPointToEdge(self):
  284. shape = self.prevhShape
  285. index = self.prevhEdge
  286. point = self.prevMovePoint
  287. if shape is None or index is None or point is None:
  288. return
  289. shape.insertPoint(index, point)
  290. shape.highlightVertex(index, shape.MOVE_VERTEX)
  291. self.hShape = shape
  292. self.hVertex = index
  293. self.hEdge = None
  294. self.movingShape = True
  295. def removeSelectedPoint(self):
  296. shape = self.prevhShape
  297. index = self.prevhVertex
  298. if shape is None or index is None:
  299. return
  300. shape.removePoint(index)
  301. shape.highlightClear()
  302. self.hShape = shape
  303. self.prevhVertex = None
  304. self.movingShape = True # Save changes
  305. def mousePressEvent(self, ev):
  306. if QT5:
  307. pos = self.transformPos(ev.localPos())
  308. else:
  309. pos = self.transformPos(ev.posF())
  310. if ev.button() == QtCore.Qt.LeftButton:
  311. if self.drawing():
  312. if self.current:
  313. # Add point to existing shape.
  314. if self.createMode == "polygon":
  315. self.current.addPoint(self.line[1])
  316. self.line[0] = self.current[-1]
  317. if self.current.isClosed():
  318. self.finalise()
  319. elif self.createMode in ["rectangle", "circle", "line"]:
  320. assert len(self.current.points) == 1
  321. self.current.points = self.line.points
  322. self.finalise()
  323. elif self.createMode == "linestrip":
  324. self.current.addPoint(self.line[1])
  325. self.line[0] = self.current[-1]
  326. if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
  327. self.finalise()
  328. elif not self.outOfPixmap(pos):
  329. # Create new shape.
  330. self.current = Shape(shape_type=self.createMode)
  331. self.current.addPoint(pos)
  332. if self.createMode == "point":
  333. self.finalise()
  334. else:
  335. if self.createMode == "circle":
  336. self.current.shape_type = "circle"
  337. self.line.points = [pos, pos]
  338. self.setHiding()
  339. self.drawingPolygon.emit(True)
  340. self.update()
  341. elif self.editing():
  342. if self.selectedEdge():
  343. self.addPointToEdge()
  344. elif (
  345. self.selectedVertex()
  346. and int(ev.modifiers()) == QtCore.Qt.ShiftModifier
  347. ):
  348. # Delete point if: left-click + SHIFT on a point
  349. self.removeSelectedPoint()
  350. group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
  351. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  352. self.prevPoint = pos
  353. self.repaint()
  354. elif ev.button() == QtCore.Qt.RightButton and self.editing():
  355. group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
  356. if not self.selectedShapes or (
  357. self.hShape is not None
  358. and self.hShape not in self.selectedShapes
  359. ):
  360. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  361. self.repaint()
  362. self.prevPoint = pos
  363. def mouseReleaseEvent(self, ev):
  364. if ev.button() == QtCore.Qt.RightButton:
  365. menu = self.menus[len(self.selectedShapesCopy) > 0]
  366. self.restoreCursor()
  367. if (
  368. not menu.exec_(self.mapToGlobal(ev.pos()))
  369. and self.selectedShapesCopy
  370. ):
  371. # Cancel the move by deleting the shadow copy.
  372. self.selectedShapesCopy = []
  373. self.repaint()
  374. elif ev.button() == QtCore.Qt.LeftButton:
  375. if self.editing():
  376. if (
  377. self.hShape is not None
  378. and self.hShapeIsSelected
  379. and not self.movingShape
  380. ):
  381. self.selectionChanged.emit(
  382. [x for x in self.selectedShapes if x != self.hShape]
  383. )
  384. if self.movingShape and self.hShape:
  385. index = self.shapes.index(self.hShape)
  386. if (
  387. self.shapesBackups[-1][index].points
  388. != self.shapes[index].points
  389. ):
  390. self.storeShapes()
  391. self.shapeMoved.emit()
  392. self.movingShape = False
  393. def endMove(self, copy):
  394. assert self.selectedShapes and self.selectedShapesCopy
  395. assert len(self.selectedShapesCopy) == len(self.selectedShapes)
  396. if copy:
  397. for i, shape in enumerate(self.selectedShapesCopy):
  398. self.shapes.append(shape)
  399. self.selectedShapes[i].selected = False
  400. self.selectedShapes[i] = shape
  401. else:
  402. for i, shape in enumerate(self.selectedShapesCopy):
  403. self.selectedShapes[i].points = shape.points
  404. self.selectedShapesCopy = []
  405. self.repaint()
  406. self.storeShapes()
  407. return True
  408. def hideBackroundShapes(self, value):
  409. self.hideBackround = value
  410. if self.selectedShapes:
  411. # Only hide other shapes if there is a current selection.
  412. # Otherwise the user will not be able to select a shape.
  413. self.setHiding(True)
  414. self.update()
  415. def setHiding(self, enable=True):
  416. self._hideBackround = self.hideBackround if enable else False
  417. def canCloseShape(self):
  418. return self.drawing() and self.current and len(self.current) > 2
  419. def mouseDoubleClickEvent(self, ev):
  420. # We need at least 4 points here, since the mousePress handler
  421. # adds an extra one before this handler is called.
  422. if (
  423. self.double_click == "close"
  424. and self.canCloseShape()
  425. and len(self.current) > 3
  426. ):
  427. self.current.popPoint()
  428. self.finalise()
  429. def selectShapes(self, shapes):
  430. self.setHiding()
  431. self.selectionChanged.emit(shapes)
  432. self.update()
  433. def selectShapePoint(self, point, multiple_selection_mode):
  434. """Select the first shape created which contains this point."""
  435. if self.selectedVertex(): # A vertex is marked for selection.
  436. index, shape = self.hVertex, self.hShape
  437. shape.highlightVertex(index, shape.MOVE_VERTEX)
  438. else:
  439. for shape in reversed(self.shapes):
  440. if self.isVisible(shape) and shape.containsPoint(point):
  441. self.calculateOffsets(shape, point)
  442. self.setHiding()
  443. if shape not in self.selectedShapes:
  444. if multiple_selection_mode:
  445. self.selectionChanged.emit(
  446. self.selectedShapes + [shape]
  447. )
  448. else:
  449. self.selectionChanged.emit([shape])
  450. self.hShapeIsSelected = False
  451. else:
  452. self.hShapeIsSelected = True
  453. return
  454. self.deSelectShape()
  455. def calculateOffsets(self, shape, point):
  456. rect = shape.boundingRect()
  457. x1 = rect.x() - point.x()
  458. y1 = rect.y() - point.y()
  459. x2 = (rect.x() + rect.width() - 1) - point.x()
  460. y2 = (rect.y() + rect.height() - 1) - point.y()
  461. self.offsets = QtCore.QPoint(x1, y1), QtCore.QPoint(x2, y2)
  462. def boundedMoveVertex(self, pos):
  463. index, shape = self.hVertex, self.hShape
  464. point = shape[index]
  465. if self.outOfPixmap(pos):
  466. pos = self.intersectionPoint(point, pos)
  467. shape.moveVertexBy(index, pos - point)
  468. def boundedMoveShapes(self, shapes, pos):
  469. if self.outOfPixmap(pos):
  470. return False # No need to move
  471. o1 = pos + self.offsets[0]
  472. if self.outOfPixmap(o1):
  473. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  474. o2 = pos + self.offsets[1]
  475. if self.outOfPixmap(o2):
  476. pos += QtCore.QPoint(
  477. min(0, self.pixmap.width() - o2.x()),
  478. min(0, self.pixmap.height() - o2.y()),
  479. )
  480. # XXX: The next line tracks the new position of the cursor
  481. # relative to the shape, but also results in making it
  482. # a bit "shaky" when nearing the border and allows it to
  483. # go outside of the shape's area for some reason.
  484. # self.calculateOffsets(self.selectedShapes, pos)
  485. dp = pos - self.prevPoint
  486. if dp:
  487. for shape in shapes:
  488. shape.moveBy(dp)
  489. self.prevPoint = pos
  490. return True
  491. return False
  492. def deSelectShape(self):
  493. if self.selectedShapes:
  494. self.setHiding(False)
  495. self.selectionChanged.emit([])
  496. self.hShapeIsSelected = False
  497. self.update()
  498. def deleteSelected(self):
  499. deleted_shapes = []
  500. if self.selectedShapes:
  501. for shape in self.selectedShapes:
  502. self.shapes.remove(shape)
  503. deleted_shapes.append(shape)
  504. self.storeShapes()
  505. self.selectedShapes = []
  506. self.update()
  507. return deleted_shapes
  508. def deleteShape(self, shape):
  509. if shape in self.selectedShapes:
  510. self.selectedShapes.remove(shape)
  511. if shape in self.shapes:
  512. self.shapes.remove(shape)
  513. self.storeShapes()
  514. self.update()
  515. def duplicateSelectedShapes(self):
  516. if self.selectedShapes:
  517. self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
  518. self.boundedShiftShapes(self.selectedShapesCopy)
  519. self.endMove(copy=True)
  520. return self.selectedShapes
  521. def boundedShiftShapes(self, shapes):
  522. # Try to move in one direction, and if it fails in another.
  523. # Give up if both fail.
  524. point = shapes[0][0]
  525. offset = QtCore.QPoint(2.0, 2.0)
  526. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  527. self.prevPoint = point
  528. if not self.boundedMoveShapes(shapes, point - offset):
  529. self.boundedMoveShapes(shapes, point + offset)
  530. def paintEvent(self, event):
  531. if not self.pixmap:
  532. return super(Canvas, self).paintEvent(event)
  533. p = self._painter
  534. p.begin(self)
  535. p.setRenderHint(QtGui.QPainter.Antialiasing)
  536. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  537. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  538. p.scale(self.scale, self.scale)
  539. p.translate(self.offsetToCenter())
  540. p.drawPixmap(0, 0, self.pixmap)
  541. Shape.scale = self.scale
  542. for shape in self.shapes:
  543. if (shape.selected or not self._hideBackround) and self.isVisible(
  544. shape
  545. ):
  546. shape.fill = shape.selected or shape == self.hShape
  547. shape.paint(p)
  548. if self.current:
  549. self.current.paint(p)
  550. self.line.paint(p)
  551. if self.selectedShapesCopy:
  552. for s in self.selectedShapesCopy:
  553. s.paint(p)
  554. if (
  555. self.fillDrawing()
  556. and self.createMode == "polygon"
  557. and self.current is not None
  558. and len(self.current.points) >= 2
  559. ):
  560. drawing_shape = self.current.copy()
  561. drawing_shape.addPoint(self.line[1])
  562. drawing_shape.fill = True
  563. drawing_shape.paint(p)
  564. p.end()
  565. def transformPos(self, point):
  566. """Convert from widget-logical coordinates to painter-logical ones."""
  567. return point / self.scale - self.offsetToCenter()
  568. def offsetToCenter(self):
  569. s = self.scale
  570. area = super(Canvas, self).size()
  571. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  572. aw, ah = area.width(), area.height()
  573. x = (aw - w) / (2 * s) if aw > w else 0
  574. y = (ah - h) / (2 * s) if ah > h else 0
  575. return QtCore.QPoint(x, y)
  576. def outOfPixmap(self, p):
  577. w, h = self.pixmap.width(), self.pixmap.height()
  578. return not (0 <= p.x() <= w - 1 and 0 <= p.y() <= h - 1)
  579. def finalise(self):
  580. assert self.current
  581. self.current.close()
  582. self.shapes.append(self.current)
  583. self.storeShapes()
  584. self.current = None
  585. self.setHiding(False)
  586. self.newShape.emit()
  587. self.update()
  588. def closeEnough(self, p1, p2):
  589. # d = distance(p1 - p2)
  590. # m = (p1-p2).manhattanLength()
  591. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  592. # divide by scale to allow more precision when zoomed in
  593. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  594. def intersectionPoint(self, p1, p2):
  595. # Cycle through each image edge in clockwise fashion,
  596. # and find the one intersecting the current line segment.
  597. # http://paulbourke.net/geometry/lineline2d/
  598. size = self.pixmap.size()
  599. points = [
  600. (0, 0),
  601. (size.width() - 1, 0),
  602. (size.width() - 1, size.height() - 1),
  603. (0, size.height() - 1),
  604. ]
  605. # x1, y1 should be in the pixmap, x2, y2 should be out of the pixmap
  606. x1 = min(max(p1.x(), 0), size.width() - 1)
  607. y1 = min(max(p1.y(), 0), size.height() - 1)
  608. x2, y2 = p2.x(), p2.y()
  609. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  610. x3, y3 = points[i]
  611. x4, y4 = points[(i + 1) % 4]
  612. if (x, y) == (x1, y1):
  613. # Handle cases where previous point is on one of the edges.
  614. if x3 == x4:
  615. return QtCore.QPoint(x3, min(max(0, y2), max(y3, y4)))
  616. else: # y3 == y4
  617. return QtCore.QPoint(min(max(0, x2), max(x3, x4)), y3)
  618. return QtCore.QPoint(x, y)
  619. def intersectingEdges(self, point1, point2, points):
  620. """Find intersecting edges.
  621. For each edge formed by `points', yield the intersection
  622. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  623. Also return the distance of `(x2,y2)' to the middle of the
  624. edge along with its index, so that the one closest can be chosen.
  625. """
  626. (x1, y1) = point1
  627. (x2, y2) = point2
  628. for i in range(4):
  629. x3, y3 = points[i]
  630. x4, y4 = points[(i + 1) % 4]
  631. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  632. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  633. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  634. if denom == 0:
  635. # This covers two cases:
  636. # nua == nub == 0: Coincident
  637. # otherwise: Parallel
  638. continue
  639. ua, ub = nua / denom, nub / denom
  640. if 0 <= ua <= 1 and 0 <= ub <= 1:
  641. x = x1 + ua * (x2 - x1)
  642. y = y1 + ua * (y2 - y1)
  643. m = QtCore.QPoint((x3 + x4) / 2, (y3 + y4) / 2)
  644. d = labelme.utils.distance(m - QtCore.QPoint(x2, y2))
  645. yield d, i, (x, y)
  646. # These two, along with a call to adjustSize are required for the
  647. # scroll area.
  648. def sizeHint(self):
  649. return self.minimumSizeHint()
  650. def minimumSizeHint(self):
  651. if self.pixmap:
  652. return self.scale * self.pixmap.size()
  653. return super(Canvas, self).minimumSizeHint()
  654. def wheelEvent(self, ev):
  655. if QT5:
  656. mods = ev.modifiers()
  657. delta = ev.angleDelta()
  658. if QtCore.Qt.ControlModifier == int(mods):
  659. # with Ctrl/Command key
  660. # zoom
  661. self.zoomRequest.emit(delta.y(), ev.pos())
  662. else:
  663. # scroll
  664. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  665. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  666. else:
  667. if ev.orientation() == QtCore.Qt.Vertical:
  668. mods = ev.modifiers()
  669. if QtCore.Qt.ControlModifier == int(mods):
  670. # with Ctrl/Command key
  671. self.zoomRequest.emit(ev.delta(), ev.pos())
  672. else:
  673. self.scrollRequest.emit(
  674. ev.delta(),
  675. QtCore.Qt.Horizontal
  676. if (QtCore.Qt.ShiftModifier == int(mods))
  677. else QtCore.Qt.Vertical,
  678. )
  679. else:
  680. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  681. ev.accept()
  682. def keyPressEvent(self, ev):
  683. modifiers = ev.modifiers()
  684. key = ev.key()
  685. if key == QtCore.Qt.Key_Escape and self.current:
  686. self.current = None
  687. self.drawingPolygon.emit(False)
  688. self.update()
  689. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  690. self.finalise()
  691. elif modifiers == QtCore.Qt.AltModifier:
  692. self.snapping = False
  693. def keyReleaseEvent(self, ev):
  694. modifiers = ev.modifiers()
  695. if int(modifiers) == 0:
  696. self.snapping = True
  697. def setLastLabel(self, text, flags):
  698. assert text
  699. self.shapes[-1].label = text
  700. self.shapes[-1].flags = flags
  701. self.shapesBackups.pop()
  702. self.storeShapes()
  703. return self.shapes[-1]
  704. def undoLastLine(self):
  705. assert self.shapes
  706. self.current = self.shapes.pop()
  707. self.current.setOpen()
  708. if self.createMode in ["polygon", "linestrip"]:
  709. self.line.points = [self.current[-1], self.current[0]]
  710. elif self.createMode in ["rectangle", "line", "circle"]:
  711. self.current.points = self.current.points[0:1]
  712. elif self.createMode == "point":
  713. self.current = None
  714. self.drawingPolygon.emit(True)
  715. def undoLastPoint(self):
  716. if not self.current or self.current.isClosed():
  717. return
  718. self.current.popPoint()
  719. if len(self.current) > 0:
  720. self.line[0] = self.current[-1]
  721. else:
  722. self.current = None
  723. self.drawingPolygon.emit(False)
  724. self.update()
  725. def loadPixmap(self, pixmap, clear_shapes=True):
  726. self.pixmap = pixmap
  727. if clear_shapes:
  728. self.shapes = []
  729. self.update()
  730. def loadShapes(self, shapes, replace=True):
  731. if replace:
  732. self.shapes = list(shapes)
  733. else:
  734. self.shapes.extend(shapes)
  735. self.storeShapes()
  736. self.current = None
  737. self.hShape = None
  738. self.hVertex = None
  739. self.hEdge = None
  740. self.update()
  741. def setShapeVisible(self, shape, value):
  742. self.visible[shape] = value
  743. self.update()
  744. def overrideCursor(self, cursor):
  745. self.restoreCursor()
  746. self._cursor = cursor
  747. QtWidgets.QApplication.setOverrideCursor(cursor)
  748. def restoreCursor(self):
  749. QtWidgets.QApplication.restoreOverrideCursor()
  750. def resetState(self):
  751. self.restoreCursor()
  752. self.pixmap = None
  753. self.shapesBackups = []
  754. self.update()