canvas.py 29 KB

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