canvas.py 33 KB

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