canvas.py 29 KB

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