canvas.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  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. 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.setHiding()
  442. if shape not in self.selectedShapes:
  443. if multiple_selection_mode:
  444. self.selectionChanged.emit(
  445. self.selectedShapes + [shape]
  446. )
  447. else:
  448. self.selectionChanged.emit([shape])
  449. self.hShapeIsSelected = False
  450. else:
  451. self.hShapeIsSelected = True
  452. self.calculateOffsets(point)
  453. return
  454. self.deSelectShape()
  455. def calculateOffsets(self, point):
  456. left = self.pixmap.width() - 1
  457. right = 0
  458. top = self.pixmap.height() - 1
  459. bottom = 0
  460. for s in self.selectedShapes:
  461. rect = s.boundingRect()
  462. if rect.left() < left:
  463. left = rect.left()
  464. if rect.right() > right:
  465. right = rect.right()
  466. if rect.top() < top:
  467. top = rect.top()
  468. if rect.bottom() > bottom:
  469. bottom = rect.bottom()
  470. x1 = left - point.x()
  471. y1 = top - point.y()
  472. x2 = right - point.x()
  473. y2 = bottom - point.y()
  474. self.offsets = QtCore.QPointF(x1, y1), QtCore.QPointF(x2, y2)
  475. def boundedMoveVertex(self, pos):
  476. index, shape = self.hVertex, self.hShape
  477. point = shape[index]
  478. if self.outOfPixmap(pos):
  479. pos = self.intersectionPoint(point, pos)
  480. shape.moveVertexBy(index, pos - point)
  481. def boundedMoveShapes(self, shapes, pos):
  482. if self.outOfPixmap(pos):
  483. return False # No need to move
  484. o1 = pos + self.offsets[0]
  485. if self.outOfPixmap(o1):
  486. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  487. o2 = pos + self.offsets[1]
  488. if self.outOfPixmap(o2):
  489. pos += QtCore.QPoint(
  490. min(0, self.pixmap.width() - o2.x()),
  491. min(0, self.pixmap.height() - o2.y()),
  492. )
  493. # XXX: The next line tracks the new position of the cursor
  494. # relative to the shape, but also results in making it
  495. # a bit "shaky" when nearing the border and allows it to
  496. # go outside of the shape's area for some reason.
  497. # self.calculateOffsets(self.selectedShapes, pos)
  498. dp = pos - self.prevPoint
  499. if dp:
  500. for shape in shapes:
  501. shape.moveBy(dp)
  502. self.prevPoint = pos
  503. return True
  504. return False
  505. def deSelectShape(self):
  506. if self.selectedShapes:
  507. self.setHiding(False)
  508. self.selectionChanged.emit([])
  509. self.hShapeIsSelected = False
  510. self.update()
  511. def deleteSelected(self):
  512. deleted_shapes = []
  513. if self.selectedShapes:
  514. for shape in self.selectedShapes:
  515. self.shapes.remove(shape)
  516. deleted_shapes.append(shape)
  517. self.storeShapes()
  518. self.selectedShapes = []
  519. self.update()
  520. return deleted_shapes
  521. def deleteShape(self, shape):
  522. if shape in self.selectedShapes:
  523. self.selectedShapes.remove(shape)
  524. if shape in self.shapes:
  525. self.shapes.remove(shape)
  526. self.storeShapes()
  527. self.update()
  528. def duplicateSelectedShapes(self):
  529. if self.selectedShapes:
  530. self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
  531. self.boundedShiftShapes(self.selectedShapesCopy)
  532. self.endMove(copy=True)
  533. return self.selectedShapes
  534. def boundedShiftShapes(self, shapes):
  535. # Try to move in one direction, and if it fails in another.
  536. # Give up if both fail.
  537. point = shapes[0][0]
  538. offset = QtCore.QPointF(2.0, 2.0)
  539. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  540. self.prevPoint = point
  541. if not self.boundedMoveShapes(shapes, point - offset):
  542. self.boundedMoveShapes(shapes, point + offset)
  543. def paintEvent(self, event):
  544. if not self.pixmap:
  545. return super(Canvas, self).paintEvent(event)
  546. p = self._painter
  547. p.begin(self)
  548. p.setRenderHint(QtGui.QPainter.Antialiasing)
  549. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  550. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  551. p.scale(self.scale, self.scale)
  552. p.translate(self.offsetToCenter())
  553. p.drawPixmap(0, 0, self.pixmap)
  554. Shape.scale = self.scale
  555. for shape in self.shapes:
  556. if (shape.selected or not self._hideBackround) and self.isVisible(
  557. shape
  558. ):
  559. shape.fill = shape.selected or shape == self.hShape
  560. shape.paint(p)
  561. if self.current:
  562. self.current.paint(p)
  563. self.line.paint(p)
  564. if self.selectedShapesCopy:
  565. for s in self.selectedShapesCopy:
  566. s.paint(p)
  567. if (
  568. self.fillDrawing()
  569. and self.createMode == "polygon"
  570. and self.current is not None
  571. and len(self.current.points) >= 2
  572. ):
  573. drawing_shape = self.current.copy()
  574. drawing_shape.addPoint(self.line[1])
  575. drawing_shape.fill = True
  576. drawing_shape.paint(p)
  577. p.end()
  578. def transformPos(self, point):
  579. """Convert from widget-logical coordinates to painter-logical ones."""
  580. return point / self.scale - self.offsetToCenter()
  581. def offsetToCenter(self):
  582. s = self.scale
  583. area = super(Canvas, self).size()
  584. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  585. aw, ah = area.width(), area.height()
  586. x = (aw - w) / (2 * s) if aw > w else 0
  587. y = (ah - h) / (2 * s) if ah > h else 0
  588. return QtCore.QPointF(x, y)
  589. def outOfPixmap(self, p):
  590. w, h = self.pixmap.width(), self.pixmap.height()
  591. return not (0 <= p.x() <= w - 1 and 0 <= p.y() <= h - 1)
  592. def finalise(self):
  593. assert self.current
  594. self.current.close()
  595. self.shapes.append(self.current)
  596. self.storeShapes()
  597. self.current = None
  598. self.setHiding(False)
  599. self.newShape.emit()
  600. self.update()
  601. def closeEnough(self, p1, p2):
  602. # d = distance(p1 - p2)
  603. # m = (p1-p2).manhattanLength()
  604. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  605. # divide by scale to allow more precision when zoomed in
  606. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  607. def intersectionPoint(self, p1, p2):
  608. # Cycle through each image edge in clockwise fashion,
  609. # and find the one intersecting the current line segment.
  610. # http://paulbourke.net/geometry/lineline2d/
  611. size = self.pixmap.size()
  612. points = [
  613. (0, 0),
  614. (size.width() - 1, 0),
  615. (size.width() - 1, size.height() - 1),
  616. (0, size.height() - 1),
  617. ]
  618. # x1, y1 should be in the pixmap, x2, y2 should be out of the pixmap
  619. x1 = min(max(p1.x(), 0), size.width() - 1)
  620. y1 = min(max(p1.y(), 0), size.height() - 1)
  621. x2, y2 = p2.x(), p2.y()
  622. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  623. x3, y3 = points[i]
  624. x4, y4 = points[(i + 1) % 4]
  625. if (x, y) == (x1, y1):
  626. # Handle cases where previous point is on one of the edges.
  627. if x3 == x4:
  628. return QtCore.QPointF(x3, min(max(0, y2), max(y3, y4)))
  629. else: # y3 == y4
  630. return QtCore.QPointF(min(max(0, x2), max(x3, x4)), y3)
  631. return QtCore.QPointF(x, y)
  632. def intersectingEdges(self, point1, point2, points):
  633. """Find intersecting edges.
  634. For each edge formed by `points', yield the intersection
  635. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  636. Also return the distance of `(x2,y2)' to the middle of the
  637. edge along with its index, so that the one closest can be chosen.
  638. """
  639. (x1, y1) = point1
  640. (x2, y2) = point2
  641. for i in range(4):
  642. x3, y3 = points[i]
  643. x4, y4 = points[(i + 1) % 4]
  644. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  645. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  646. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  647. if denom == 0:
  648. # This covers two cases:
  649. # nua == nub == 0: Coincident
  650. # otherwise: Parallel
  651. continue
  652. ua, ub = nua / denom, nub / denom
  653. if 0 <= ua <= 1 and 0 <= ub <= 1:
  654. x = x1 + ua * (x2 - x1)
  655. y = y1 + ua * (y2 - y1)
  656. m = QtCore.QPointF((x3 + x4) / 2, (y3 + y4) / 2)
  657. d = labelme.utils.distance(m - QtCore.QPointF(x2, y2))
  658. yield d, i, (x, y)
  659. # These two, along with a call to adjustSize are required for the
  660. # scroll area.
  661. def sizeHint(self):
  662. return self.minimumSizeHint()
  663. def minimumSizeHint(self):
  664. if self.pixmap:
  665. return self.scale * self.pixmap.size()
  666. return super(Canvas, self).minimumSizeHint()
  667. def wheelEvent(self, ev):
  668. if QT5:
  669. mods = ev.modifiers()
  670. delta = ev.angleDelta()
  671. if QtCore.Qt.ControlModifier == int(mods):
  672. # with Ctrl/Command key
  673. # zoom
  674. self.zoomRequest.emit(delta.y(), ev.pos())
  675. else:
  676. # scroll
  677. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  678. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  679. else:
  680. if ev.orientation() == QtCore.Qt.Vertical:
  681. mods = ev.modifiers()
  682. if QtCore.Qt.ControlModifier == int(mods):
  683. # with Ctrl/Command key
  684. self.zoomRequest.emit(ev.delta(), ev.pos())
  685. else:
  686. self.scrollRequest.emit(
  687. ev.delta(),
  688. QtCore.Qt.Horizontal
  689. if (QtCore.Qt.ShiftModifier == int(mods))
  690. else QtCore.Qt.Vertical,
  691. )
  692. else:
  693. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  694. ev.accept()
  695. def moveByKeyboard(self, offset):
  696. if self.selectedShapes:
  697. self.boundedMoveShapes(
  698. self.selectedShapes, self.prevPoint + offset
  699. )
  700. self.repaint()
  701. self.movingShape = True
  702. def keyPressEvent(self, ev):
  703. modifiers = ev.modifiers()
  704. key = ev.key()
  705. if self.drawing():
  706. if key == QtCore.Qt.Key_Escape and self.current:
  707. self.current = None
  708. self.drawingPolygon.emit(False)
  709. self.update()
  710. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  711. self.finalise()
  712. elif modifiers == QtCore.Qt.AltModifier:
  713. self.snapping = False
  714. elif self.editing():
  715. if key == QtCore.Qt.Key_Up:
  716. self.moveByKeyboard(QtCore.QPointF(0.0, -MOVE_SPEED))
  717. elif key == QtCore.Qt.Key_Down:
  718. self.moveByKeyboard(QtCore.QPointF(0.0, MOVE_SPEED))
  719. elif key == QtCore.Qt.Key_Left:
  720. self.moveByKeyboard(QtCore.QPointF(-MOVE_SPEED, 0.0))
  721. elif key == QtCore.Qt.Key_Right:
  722. self.moveByKeyboard(QtCore.QPointF(MOVE_SPEED, 0.0))
  723. def keyReleaseEvent(self, ev):
  724. modifiers = ev.modifiers()
  725. if self.drawing():
  726. if int(modifiers) == 0:
  727. self.snapping = True
  728. elif self.editing():
  729. if self.movingShape and self.selectedShapes:
  730. index = self.shapes.index(self.selectedShapes[0])
  731. if (
  732. self.shapesBackups[-1][index].points
  733. != self.shapes[index].points
  734. ):
  735. self.storeShapes()
  736. self.shapeMoved.emit()
  737. self.movingShape = False
  738. def setLastLabel(self, text, flags):
  739. assert text
  740. self.shapes[-1].label = text
  741. self.shapes[-1].flags = flags
  742. self.shapesBackups.pop()
  743. self.storeShapes()
  744. return self.shapes[-1]
  745. def undoLastLine(self):
  746. assert self.shapes
  747. self.current = self.shapes.pop()
  748. self.current.setOpen()
  749. if self.createMode in ["polygon", "linestrip"]:
  750. self.line.points = [self.current[-1], self.current[0]]
  751. elif self.createMode in ["rectangle", "line", "circle"]:
  752. self.current.points = self.current.points[0:1]
  753. elif self.createMode == "point":
  754. self.current = None
  755. self.drawingPolygon.emit(True)
  756. def undoLastPoint(self):
  757. if not self.current or self.current.isClosed():
  758. return
  759. self.current.popPoint()
  760. if len(self.current) > 0:
  761. self.line[0] = self.current[-1]
  762. else:
  763. self.current = None
  764. self.drawingPolygon.emit(False)
  765. self.update()
  766. def loadPixmap(self, pixmap, clear_shapes=True):
  767. self.pixmap = pixmap
  768. if clear_shapes:
  769. self.shapes = []
  770. self.update()
  771. def loadShapes(self, shapes, replace=True):
  772. if replace:
  773. self.shapes = list(shapes)
  774. else:
  775. self.shapes.extend(shapes)
  776. self.storeShapes()
  777. self.current = None
  778. self.hShape = None
  779. self.hVertex = None
  780. self.hEdge = None
  781. self.update()
  782. def setShapeVisible(self, shape, value):
  783. self.visible[shape] = value
  784. self.update()
  785. def overrideCursor(self, cursor):
  786. self.restoreCursor()
  787. self._cursor = cursor
  788. QtWidgets.QApplication.setOverrideCursor(cursor)
  789. def restoreCursor(self):
  790. QtWidgets.QApplication.restoreOverrideCursor()
  791. def resetState(self):
  792. self.restoreCursor()
  793. self.pixmap = None
  794. self.shapesBackups = []
  795. self.update()