canvas.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. from qtpy import QtCore
  2. from qtpy import QtGui
  3. from qtpy import QtWidgets
  4. from labelme import QT5
  5. from labelme.shape import Shape
  6. import labelme.utils
  7. # TODO(unknown):
  8. # - [maybe] Find optimal epsilon value.
  9. CURSOR_DEFAULT = QtCore.Qt.ArrowCursor
  10. CURSOR_POINT = QtCore.Qt.PointingHandCursor
  11. CURSOR_DRAW = QtCore.Qt.CrossCursor
  12. CURSOR_MOVE = QtCore.Qt.ClosedHandCursor
  13. CURSOR_GRAB = QtCore.Qt.OpenHandCursor
  14. class Canvas(QtWidgets.QWidget):
  15. zoomRequest = QtCore.Signal(int, QtCore.QPoint)
  16. scrollRequest = QtCore.Signal(int, int)
  17. newShape = QtCore.Signal()
  18. selectionChanged = QtCore.Signal(list)
  19. shapeMoved = QtCore.Signal()
  20. drawingPolygon = QtCore.Signal(bool)
  21. edgeSelected = QtCore.Signal(bool, object)
  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._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 mouseMoveEvent(self, ev):
  155. """Update line with last point and current coordinates."""
  156. try:
  157. if QT5:
  158. pos = self.transformPos(ev.localPos())
  159. else:
  160. pos = self.transformPos(ev.posF())
  161. except AttributeError:
  162. return
  163. self.prevMovePoint = pos
  164. self.restoreCursor()
  165. # Polygon drawing.
  166. if self.drawing():
  167. self.line.shape_type = self.createMode
  168. self.overrideCursor(CURSOR_DRAW)
  169. if not self.current:
  170. return
  171. if self.outOfPixmap(pos):
  172. # Don't allow the user to draw outside the pixmap.
  173. # Project the point to the pixmap's edges.
  174. pos = self.intersectionPoint(self.current[-1], pos)
  175. elif (
  176. self.snapping
  177. and len(self.current) > 1
  178. and self.createMode == "polygon"
  179. and self.closeEnough(pos, self.current[0])
  180. ):
  181. # Attract line to starting point and
  182. # colorise to alert the user.
  183. pos = self.current[0]
  184. self.overrideCursor(CURSOR_POINT)
  185. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  186. if self.createMode in ["polygon", "linestrip"]:
  187. self.line[0] = self.current[-1]
  188. self.line[1] = pos
  189. elif self.createMode == "rectangle":
  190. self.line.points = [self.current[0], pos]
  191. self.line.close()
  192. elif self.createMode == "circle":
  193. self.line.points = [self.current[0], pos]
  194. self.line.shape_type = "circle"
  195. elif self.createMode == "line":
  196. self.line.points = [self.current[0], pos]
  197. self.line.close()
  198. elif self.createMode == "point":
  199. self.line.points = [self.current[0]]
  200. self.line.close()
  201. self.repaint()
  202. self.current.highlightClear()
  203. return
  204. # Polygon copy moving.
  205. if QtCore.Qt.RightButton & ev.buttons():
  206. if self.selectedShapesCopy and self.prevPoint:
  207. self.overrideCursor(CURSOR_MOVE)
  208. self.boundedMoveShapes(self.selectedShapesCopy, pos)
  209. self.repaint()
  210. elif self.selectedShapes:
  211. self.selectedShapesCopy = [
  212. s.copy() for s in self.selectedShapes
  213. ]
  214. self.repaint()
  215. return
  216. # Polygon/Vertex moving.
  217. if QtCore.Qt.LeftButton & ev.buttons():
  218. if self.selectedVertex():
  219. self.boundedMoveVertex(pos)
  220. self.repaint()
  221. self.movingShape = True
  222. elif self.selectedShapes and self.prevPoint:
  223. self.overrideCursor(CURSOR_MOVE)
  224. self.boundedMoveShapes(self.selectedShapes, pos)
  225. self.repaint()
  226. self.movingShape = True
  227. return
  228. # Just hovering over the canvas, 2 possibilities:
  229. # - Highlight shapes
  230. # - Highlight vertex
  231. # Update shape/vertex fill and tooltip value accordingly.
  232. self.setToolTip(self.tr("Image"))
  233. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  234. # Look for a nearby vertex to highlight. If that fails,
  235. # check if we happen to be inside a shape.
  236. index = shape.nearestVertex(pos, self.epsilon / self.scale)
  237. index_edge = shape.nearestEdge(pos, self.epsilon / self.scale)
  238. if index is not None:
  239. if self.selectedVertex():
  240. self.hShape.highlightClear()
  241. self.prevhVertex = self.hVertex = index
  242. self.prevhShape = self.hShape = shape
  243. self.prevhEdge = self.hEdge = index_edge
  244. shape.highlightVertex(index, shape.MOVE_VERTEX)
  245. self.overrideCursor(CURSOR_POINT)
  246. self.setToolTip(self.tr("Click & drag to move point"))
  247. self.setStatusTip(self.toolTip())
  248. self.update()
  249. break
  250. elif shape.containsPoint(pos):
  251. if self.selectedVertex():
  252. self.hShape.highlightClear()
  253. self.prevhVertex = self.hVertex
  254. self.hVertex = None
  255. self.prevhShape = self.hShape = shape
  256. self.prevhEdge = self.hEdge = index_edge
  257. self.setToolTip(
  258. self.tr("Click & drag to move shape '%s'") % shape.label
  259. )
  260. self.setStatusTip(self.toolTip())
  261. self.overrideCursor(CURSOR_GRAB)
  262. self.update()
  263. break
  264. else: # Nothing found, clear highlights, reset state.
  265. self.unHighlight()
  266. self.edgeSelected.emit(self.hEdge is not None, self.hShape)
  267. self.vertexSelected.emit(self.hVertex is not None)
  268. def addPointToEdge(self):
  269. shape = self.prevhShape
  270. index = self.prevhEdge
  271. point = self.prevMovePoint
  272. if shape is None or index is None or point is None:
  273. return
  274. shape.insertPoint(index, point)
  275. shape.highlightVertex(index, shape.MOVE_VERTEX)
  276. self.hShape = shape
  277. self.hVertex = index
  278. self.hEdge = None
  279. self.movingShape = True
  280. def removeSelectedPoint(self):
  281. shape = self.prevhShape
  282. point = self.prevMovePoint
  283. if shape is None or point is None:
  284. return
  285. index = shape.nearestVertex(point, self.epsilon)
  286. shape.removePoint(index)
  287. # shape.highlightVertex(index, shape.MOVE_VERTEX)
  288. self.hShape = shape
  289. self.hVertex = None
  290. self.hEdge = None
  291. self.movingShape = True # Save changes
  292. def mousePressEvent(self, ev):
  293. if QT5:
  294. pos = self.transformPos(ev.localPos())
  295. else:
  296. pos = self.transformPos(ev.posF())
  297. if ev.button() == QtCore.Qt.LeftButton:
  298. if self.drawing():
  299. if self.current:
  300. # Add point to existing shape.
  301. if self.createMode == "polygon":
  302. self.current.addPoint(self.line[1])
  303. self.line[0] = self.current[-1]
  304. if self.current.isClosed():
  305. self.finalise()
  306. elif self.createMode in ["rectangle", "circle", "line"]:
  307. assert len(self.current.points) == 1
  308. self.current.points = self.line.points
  309. self.finalise()
  310. elif self.createMode == "linestrip":
  311. self.current.addPoint(self.line[1])
  312. self.line[0] = self.current[-1]
  313. if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
  314. self.finalise()
  315. elif not self.outOfPixmap(pos):
  316. # Create new shape.
  317. self.current = Shape(shape_type=self.createMode)
  318. self.current.addPoint(pos)
  319. if self.createMode == "point":
  320. self.finalise()
  321. else:
  322. if self.createMode == "circle":
  323. self.current.shape_type = "circle"
  324. self.line.points = [pos, pos]
  325. self.setHiding()
  326. self.drawingPolygon.emit(True)
  327. self.update()
  328. else:
  329. group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
  330. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  331. self.prevPoint = pos
  332. self.repaint()
  333. elif ev.button() == QtCore.Qt.RightButton and self.editing():
  334. group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
  335. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  336. self.prevPoint = pos
  337. self.repaint()
  338. def mouseReleaseEvent(self, ev):
  339. if ev.button() == QtCore.Qt.RightButton:
  340. menu = self.menus[len(self.selectedShapesCopy) > 0]
  341. self.restoreCursor()
  342. if (
  343. not menu.exec_(self.mapToGlobal(ev.pos()))
  344. and self.selectedShapesCopy
  345. ):
  346. # Cancel the move by deleting the shadow copy.
  347. self.selectedShapesCopy = []
  348. self.repaint()
  349. elif ev.button() == QtCore.Qt.LeftButton and self.selectedShapes:
  350. self.overrideCursor(CURSOR_GRAB)
  351. if (
  352. self.editing()
  353. and int(ev.modifiers()) == QtCore.Qt.ShiftModifier
  354. ):
  355. # Add point to line if: left-click + SHIFT on a line segment
  356. self.addPointToEdge()
  357. elif ev.button() == QtCore.Qt.LeftButton and self.selectedVertex():
  358. if (
  359. self.editing()
  360. and int(ev.modifiers()) == QtCore.Qt.ShiftModifier
  361. ):
  362. # Delete point if: left-click + SHIFT on a point
  363. self.removeSelectedPoint()
  364. if self.movingShape and self.hShape:
  365. index = self.shapes.index(self.hShape)
  366. if (
  367. self.shapesBackups[-1][index].points
  368. != self.shapes[index].points
  369. ):
  370. self.storeShapes()
  371. self.shapeMoved.emit()
  372. self.movingShape = False
  373. def endMove(self, copy):
  374. assert self.selectedShapes and self.selectedShapesCopy
  375. assert len(self.selectedShapesCopy) == len(self.selectedShapes)
  376. if copy:
  377. for i, shape in enumerate(self.selectedShapesCopy):
  378. self.shapes.append(shape)
  379. self.selectedShapes[i].selected = False
  380. self.selectedShapes[i] = shape
  381. else:
  382. for i, shape in enumerate(self.selectedShapesCopy):
  383. self.selectedShapes[i].points = shape.points
  384. self.selectedShapesCopy = []
  385. self.repaint()
  386. self.storeShapes()
  387. return True
  388. def hideBackroundShapes(self, value):
  389. self.hideBackround = value
  390. if self.selectedShapes:
  391. # Only hide other shapes if there is a current selection.
  392. # Otherwise the user will not be able to select a shape.
  393. self.setHiding(True)
  394. self.update()
  395. def setHiding(self, enable=True):
  396. self._hideBackround = self.hideBackround if enable else False
  397. def canCloseShape(self):
  398. return self.drawing() and self.current and len(self.current) > 2
  399. def mouseDoubleClickEvent(self, ev):
  400. # We need at least 4 points here, since the mousePress handler
  401. # adds an extra one before this handler is called.
  402. if (
  403. self.double_click == "close"
  404. and self.canCloseShape()
  405. and len(self.current) > 3
  406. ):
  407. self.current.popPoint()
  408. self.finalise()
  409. def selectShapes(self, shapes):
  410. self.setHiding()
  411. self.selectionChanged.emit(shapes)
  412. self.update()
  413. def selectShapePoint(self, point, multiple_selection_mode):
  414. """Select the first shape created which contains this point."""
  415. if self.selectedVertex(): # A vertex is marked for selection.
  416. index, shape = self.hVertex, self.hShape
  417. shape.highlightVertex(index, shape.MOVE_VERTEX)
  418. else:
  419. for shape in reversed(self.shapes):
  420. if self.isVisible(shape) and shape.containsPoint(point):
  421. self.calculateOffsets(shape, point)
  422. self.setHiding()
  423. if multiple_selection_mode:
  424. if shape not in self.selectedShapes:
  425. self.selectionChanged.emit(
  426. self.selectedShapes + [shape]
  427. )
  428. else:
  429. self.selectionChanged.emit([shape])
  430. return
  431. self.deSelectShape()
  432. def calculateOffsets(self, shape, point):
  433. rect = shape.boundingRect()
  434. x1 = rect.x() - point.x()
  435. y1 = rect.y() - point.y()
  436. x2 = (rect.x() + rect.width() - 1) - point.x()
  437. y2 = (rect.y() + rect.height() - 1) - point.y()
  438. self.offsets = QtCore.QPoint(x1, y1), QtCore.QPoint(x2, y2)
  439. def boundedMoveVertex(self, pos):
  440. index, shape = self.hVertex, self.hShape
  441. point = shape[index]
  442. if self.outOfPixmap(pos):
  443. pos = self.intersectionPoint(point, pos)
  444. shape.moveVertexBy(index, pos - point)
  445. def boundedMoveShapes(self, shapes, pos):
  446. if self.outOfPixmap(pos):
  447. return False # No need to move
  448. o1 = pos + self.offsets[0]
  449. if self.outOfPixmap(o1):
  450. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  451. o2 = pos + self.offsets[1]
  452. if self.outOfPixmap(o2):
  453. pos += QtCore.QPoint(
  454. min(0, self.pixmap.width() - o2.x()),
  455. min(0, self.pixmap.height() - o2.y()),
  456. )
  457. # XXX: The next line tracks the new position of the cursor
  458. # relative to the shape, but also results in making it
  459. # a bit "shaky" when nearing the border and allows it to
  460. # go outside of the shape's area for some reason.
  461. # self.calculateOffsets(self.selectedShapes, pos)
  462. dp = pos - self.prevPoint
  463. if dp:
  464. for shape in shapes:
  465. shape.moveBy(dp)
  466. self.prevPoint = pos
  467. return True
  468. return False
  469. def deSelectShape(self):
  470. if self.selectedShapes:
  471. self.setHiding(False)
  472. self.selectionChanged.emit([])
  473. self.update()
  474. def deleteSelected(self):
  475. deleted_shapes = []
  476. if self.selectedShapes:
  477. for shape in self.selectedShapes:
  478. self.shapes.remove(shape)
  479. deleted_shapes.append(shape)
  480. self.storeShapes()
  481. self.selectedShapes = []
  482. self.update()
  483. return deleted_shapes
  484. def deleteShape(self, shape):
  485. if shape in self.selectedShapes:
  486. self.selectedShapes.remove(shape)
  487. if shape in self.shapes:
  488. self.shapes.remove(shape)
  489. self.storeShapes()
  490. self.update()
  491. def copySelectedShapes(self):
  492. if self.selectedShapes:
  493. self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
  494. self.boundedShiftShapes(self.selectedShapesCopy)
  495. self.endMove(copy=True)
  496. return self.selectedShapes
  497. def boundedShiftShapes(self, shapes):
  498. # Try to move in one direction, and if it fails in another.
  499. # Give up if both fail.
  500. point = shapes[0][0]
  501. offset = QtCore.QPoint(2.0, 2.0)
  502. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  503. self.prevPoint = point
  504. if not self.boundedMoveShapes(shapes, point - offset):
  505. self.boundedMoveShapes(shapes, point + offset)
  506. def paintEvent(self, event):
  507. if not self.pixmap:
  508. return super(Canvas, self).paintEvent(event)
  509. p = self._painter
  510. p.begin(self)
  511. p.setRenderHint(QtGui.QPainter.Antialiasing)
  512. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  513. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  514. p.scale(self.scale, self.scale)
  515. p.translate(self.offsetToCenter())
  516. p.drawPixmap(0, 0, self.pixmap)
  517. Shape.scale = self.scale
  518. for shape in self.shapes:
  519. if (shape.selected or not self._hideBackround) and self.isVisible(
  520. shape
  521. ):
  522. shape.fill = shape.selected or shape == self.hShape
  523. shape.paint(p)
  524. if self.current:
  525. self.current.paint(p)
  526. self.line.paint(p)
  527. if self.selectedShapesCopy:
  528. for s in self.selectedShapesCopy:
  529. s.paint(p)
  530. if (
  531. self.fillDrawing()
  532. and self.createMode == "polygon"
  533. and self.current is not None
  534. and len(self.current.points) >= 2
  535. ):
  536. drawing_shape = self.current.copy()
  537. drawing_shape.addPoint(self.line[1])
  538. drawing_shape.fill = True
  539. drawing_shape.paint(p)
  540. p.end()
  541. def transformPos(self, point):
  542. """Convert from widget-logical coordinates to painter-logical ones."""
  543. return point / self.scale - self.offsetToCenter()
  544. def offsetToCenter(self):
  545. s = self.scale
  546. area = super(Canvas, self).size()
  547. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  548. aw, ah = area.width(), area.height()
  549. x = (aw - w) / (2 * s) if aw > w else 0
  550. y = (ah - h) / (2 * s) if ah > h else 0
  551. return QtCore.QPoint(x, y)
  552. def outOfPixmap(self, p):
  553. w, h = self.pixmap.width(), self.pixmap.height()
  554. return not (0 <= p.x() <= w - 1 and 0 <= p.y() <= h - 1)
  555. def finalise(self):
  556. assert self.current
  557. self.current.close()
  558. self.shapes.append(self.current)
  559. self.storeShapes()
  560. self.current = None
  561. self.setHiding(False)
  562. self.newShape.emit()
  563. self.update()
  564. def closeEnough(self, p1, p2):
  565. # d = distance(p1 - p2)
  566. # m = (p1-p2).manhattanLength()
  567. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  568. # divide by scale to allow more precision when zoomed in
  569. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  570. def intersectionPoint(self, p1, p2):
  571. # Cycle through each image edge in clockwise fashion,
  572. # and find the one intersecting the current line segment.
  573. # http://paulbourke.net/geometry/lineline2d/
  574. size = self.pixmap.size()
  575. points = [
  576. (0, 0),
  577. (size.width() - 1, 0),
  578. (size.width() - 1, size.height() - 1),
  579. (0, size.height() - 1),
  580. ]
  581. # x1, y1 should be in the pixmap, x2, y2 should be out of the pixmap
  582. x1 = min(max(p1.x(), 0), size.width() - 1)
  583. y1 = min(max(p1.y(), 0), size.height() - 1)
  584. x2, y2 = p2.x(), p2.y()
  585. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  586. x3, y3 = points[i]
  587. x4, y4 = points[(i + 1) % 4]
  588. if (x, y) == (x1, y1):
  589. # Handle cases where previous point is on one of the edges.
  590. if x3 == x4:
  591. return QtCore.QPoint(x3, min(max(0, y2), max(y3, y4)))
  592. else: # y3 == y4
  593. return QtCore.QPoint(min(max(0, x2), max(x3, x4)), y3)
  594. return QtCore.QPoint(x, y)
  595. def intersectingEdges(self, point1, point2, points):
  596. """Find intersecting edges.
  597. For each edge formed by `points', yield the intersection
  598. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  599. Also return the distance of `(x2,y2)' to the middle of the
  600. edge along with its index, so that the one closest can be chosen.
  601. """
  602. (x1, y1) = point1
  603. (x2, y2) = point2
  604. for i in range(4):
  605. x3, y3 = points[i]
  606. x4, y4 = points[(i + 1) % 4]
  607. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  608. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  609. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  610. if denom == 0:
  611. # This covers two cases:
  612. # nua == nub == 0: Coincident
  613. # otherwise: Parallel
  614. continue
  615. ua, ub = nua / denom, nub / denom
  616. if 0 <= ua <= 1 and 0 <= ub <= 1:
  617. x = x1 + ua * (x2 - x1)
  618. y = y1 + ua * (y2 - y1)
  619. m = QtCore.QPoint((x3 + x4) / 2, (y3 + y4) / 2)
  620. d = labelme.utils.distance(m - QtCore.QPoint(x2, y2))
  621. yield d, i, (x, y)
  622. # These two, along with a call to adjustSize are required for the
  623. # scroll area.
  624. def sizeHint(self):
  625. return self.minimumSizeHint()
  626. def minimumSizeHint(self):
  627. if self.pixmap:
  628. return self.scale * self.pixmap.size()
  629. return super(Canvas, self).minimumSizeHint()
  630. def wheelEvent(self, ev):
  631. if QT5:
  632. mods = ev.modifiers()
  633. delta = ev.angleDelta()
  634. if QtCore.Qt.ControlModifier == int(mods):
  635. # with Ctrl/Command key
  636. # zoom
  637. self.zoomRequest.emit(delta.y(), ev.pos())
  638. else:
  639. # scroll
  640. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  641. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  642. else:
  643. if ev.orientation() == QtCore.Qt.Vertical:
  644. mods = ev.modifiers()
  645. if QtCore.Qt.ControlModifier == int(mods):
  646. # with Ctrl/Command key
  647. self.zoomRequest.emit(ev.delta(), ev.pos())
  648. else:
  649. self.scrollRequest.emit(
  650. ev.delta(),
  651. QtCore.Qt.Horizontal
  652. if (QtCore.Qt.ShiftModifier == int(mods))
  653. else QtCore.Qt.Vertical,
  654. )
  655. else:
  656. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  657. ev.accept()
  658. def keyPressEvent(self, ev):
  659. modifiers = ev.modifiers()
  660. key = ev.key()
  661. if key == QtCore.Qt.Key_Escape and self.current:
  662. self.current = None
  663. self.drawingPolygon.emit(False)
  664. self.update()
  665. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  666. self.finalise()
  667. elif modifiers == QtCore.Qt.AltModifier:
  668. self.snapping = False
  669. def keyReleaseEvent(self, ev):
  670. modifiers = ev.modifiers()
  671. if int(modifiers) == 0:
  672. self.snapping = True
  673. def setLastLabel(self, text, flags):
  674. assert text
  675. self.shapes[-1].label = text
  676. self.shapes[-1].flags = flags
  677. self.shapesBackups.pop()
  678. self.storeShapes()
  679. return self.shapes[-1]
  680. def undoLastLine(self):
  681. assert self.shapes
  682. self.current = self.shapes.pop()
  683. self.current.setOpen()
  684. if self.createMode in ["polygon", "linestrip"]:
  685. self.line.points = [self.current[-1], self.current[0]]
  686. elif self.createMode in ["rectangle", "line", "circle"]:
  687. self.current.points = self.current.points[0:1]
  688. elif self.createMode == "point":
  689. self.current = None
  690. self.drawingPolygon.emit(True)
  691. def undoLastPoint(self):
  692. if not self.current or self.current.isClosed():
  693. return
  694. self.current.popPoint()
  695. if len(self.current) > 0:
  696. self.line[0] = self.current[-1]
  697. else:
  698. self.current = None
  699. self.drawingPolygon.emit(False)
  700. self.update()
  701. def loadPixmap(self, pixmap, clear_shapes=True):
  702. self.pixmap = pixmap
  703. if clear_shapes:
  704. self.shapes = []
  705. self.update()
  706. def loadShapes(self, shapes, replace=True):
  707. if replace:
  708. self.shapes = list(shapes)
  709. else:
  710. self.shapes.extend(shapes)
  711. self.storeShapes()
  712. self.current = None
  713. self.hShape = None
  714. self.hVertex = None
  715. self.hEdge = None
  716. self.update()
  717. def setShapeVisible(self, shape, value):
  718. self.visible[shape] = value
  719. self.update()
  720. def overrideCursor(self, cursor):
  721. self.restoreCursor()
  722. self._cursor = cursor
  723. QtWidgets.QApplication.setOverrideCursor(cursor)
  724. def restoreCursor(self):
  725. QtWidgets.QApplication.restoreOverrideCursor()
  726. def resetState(self):
  727. self.restoreCursor()
  728. self.pixmap = None
  729. self.shapesBackups = []
  730. self.update()