canvas.py 32 KB

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