canvas.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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. elif (
  344. self.selectedVertex()
  345. and int(ev.modifiers()) == QtCore.Qt.ShiftModifier
  346. ):
  347. # Delete point if: left-click + SHIFT on a point
  348. self.removeSelectedPoint()
  349. group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
  350. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  351. self.prevPoint = pos
  352. self.repaint()
  353. elif ev.button() == QtCore.Qt.RightButton and self.editing():
  354. group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
  355. if not self.selectedShapes or (
  356. self.hShape is not None
  357. and self.hShape not in self.selectedShapes
  358. ):
  359. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  360. self.repaint()
  361. self.prevPoint = pos
  362. def mouseReleaseEvent(self, ev):
  363. if ev.button() == QtCore.Qt.RightButton:
  364. menu = self.menus[len(self.selectedShapesCopy) > 0]
  365. self.restoreCursor()
  366. if (
  367. not menu.exec_(self.mapToGlobal(ev.pos()))
  368. and self.selectedShapesCopy
  369. ):
  370. # Cancel the move by deleting the shadow copy.
  371. self.selectedShapesCopy = []
  372. self.repaint()
  373. if self.movingShape and self.hShape:
  374. index = self.shapes.index(self.hShape)
  375. if (
  376. self.shapesBackups[-1][index].points
  377. != self.shapes[index].points
  378. ):
  379. self.storeShapes()
  380. self.shapeMoved.emit()
  381. self.movingShape = False
  382. def endMove(self, copy):
  383. assert self.selectedShapes and self.selectedShapesCopy
  384. assert len(self.selectedShapesCopy) == len(self.selectedShapes)
  385. if copy:
  386. for i, shape in enumerate(self.selectedShapesCopy):
  387. self.shapes.append(shape)
  388. self.selectedShapes[i].selected = False
  389. self.selectedShapes[i] = shape
  390. else:
  391. for i, shape in enumerate(self.selectedShapesCopy):
  392. self.selectedShapes[i].points = shape.points
  393. self.selectedShapesCopy = []
  394. self.repaint()
  395. self.storeShapes()
  396. return True
  397. def hideBackroundShapes(self, value):
  398. self.hideBackround = value
  399. if self.selectedShapes:
  400. # Only hide other shapes if there is a current selection.
  401. # Otherwise the user will not be able to select a shape.
  402. self.setHiding(True)
  403. self.update()
  404. def setHiding(self, enable=True):
  405. self._hideBackround = self.hideBackround if enable else False
  406. def canCloseShape(self):
  407. return self.drawing() and self.current and len(self.current) > 2
  408. def mouseDoubleClickEvent(self, ev):
  409. # We need at least 4 points here, since the mousePress handler
  410. # adds an extra one before this handler is called.
  411. if (
  412. self.double_click == "close"
  413. and self.canCloseShape()
  414. and len(self.current) > 3
  415. ):
  416. self.current.popPoint()
  417. self.finalise()
  418. def selectShapes(self, shapes):
  419. self.setHiding()
  420. self.selectionChanged.emit(shapes)
  421. self.update()
  422. def selectShapePoint(self, point, multiple_selection_mode):
  423. """Select the first shape created which contains this point."""
  424. if self.selectedVertex(): # A vertex is marked for selection.
  425. index, shape = self.hVertex, self.hShape
  426. shape.highlightVertex(index, shape.MOVE_VERTEX)
  427. else:
  428. for shape in reversed(self.shapes):
  429. if self.isVisible(shape) and shape.containsPoint(point):
  430. self.calculateOffsets(shape, point)
  431. self.setHiding()
  432. if shape not in self.selectedShapes:
  433. if multiple_selection_mode:
  434. self.selectionChanged.emit(
  435. self.selectedShapes + [shape]
  436. )
  437. else:
  438. self.selectionChanged.emit([shape])
  439. else:
  440. self.selectionChanged.emit(
  441. [
  442. x
  443. for x in self.selectedShapes
  444. if x != self.hShape
  445. ]
  446. )
  447. return
  448. self.deSelectShape()
  449. def calculateOffsets(self, shape, point):
  450. rect = shape.boundingRect()
  451. x1 = rect.x() - point.x()
  452. y1 = rect.y() - point.y()
  453. x2 = (rect.x() + rect.width() - 1) - point.x()
  454. y2 = (rect.y() + rect.height() - 1) - point.y()
  455. self.offsets = QtCore.QPoint(x1, y1), QtCore.QPoint(x2, y2)
  456. def boundedMoveVertex(self, pos):
  457. index, shape = self.hVertex, self.hShape
  458. point = shape[index]
  459. if self.outOfPixmap(pos):
  460. pos = self.intersectionPoint(point, pos)
  461. shape.moveVertexBy(index, pos - point)
  462. def boundedMoveShapes(self, shapes, pos):
  463. if self.outOfPixmap(pos):
  464. return False # No need to move
  465. o1 = pos + self.offsets[0]
  466. if self.outOfPixmap(o1):
  467. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  468. o2 = pos + self.offsets[1]
  469. if self.outOfPixmap(o2):
  470. pos += QtCore.QPoint(
  471. min(0, self.pixmap.width() - o2.x()),
  472. min(0, self.pixmap.height() - o2.y()),
  473. )
  474. # XXX: The next line tracks the new position of the cursor
  475. # relative to the shape, but also results in making it
  476. # a bit "shaky" when nearing the border and allows it to
  477. # go outside of the shape's area for some reason.
  478. # self.calculateOffsets(self.selectedShapes, pos)
  479. dp = pos - self.prevPoint
  480. if dp:
  481. for shape in shapes:
  482. shape.moveBy(dp)
  483. self.prevPoint = pos
  484. return True
  485. return False
  486. def deSelectShape(self):
  487. if self.selectedShapes:
  488. self.setHiding(False)
  489. self.selectionChanged.emit([])
  490. self.update()
  491. def deleteSelected(self):
  492. deleted_shapes = []
  493. if self.selectedShapes:
  494. for shape in self.selectedShapes:
  495. self.shapes.remove(shape)
  496. deleted_shapes.append(shape)
  497. self.storeShapes()
  498. self.selectedShapes = []
  499. self.update()
  500. return deleted_shapes
  501. def deleteShape(self, shape):
  502. if shape in self.selectedShapes:
  503. self.selectedShapes.remove(shape)
  504. if shape in self.shapes:
  505. self.shapes.remove(shape)
  506. self.storeShapes()
  507. self.update()
  508. def duplicateSelectedShapes(self):
  509. if self.selectedShapes:
  510. self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
  511. self.boundedShiftShapes(self.selectedShapesCopy)
  512. self.endMove(copy=True)
  513. return self.selectedShapes
  514. def boundedShiftShapes(self, shapes):
  515. # Try to move in one direction, and if it fails in another.
  516. # Give up if both fail.
  517. point = shapes[0][0]
  518. offset = QtCore.QPoint(2.0, 2.0)
  519. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  520. self.prevPoint = point
  521. if not self.boundedMoveShapes(shapes, point - offset):
  522. self.boundedMoveShapes(shapes, point + offset)
  523. def paintEvent(self, event):
  524. if not self.pixmap:
  525. return super(Canvas, self).paintEvent(event)
  526. p = self._painter
  527. p.begin(self)
  528. p.setRenderHint(QtGui.QPainter.Antialiasing)
  529. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  530. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  531. p.scale(self.scale, self.scale)
  532. p.translate(self.offsetToCenter())
  533. p.drawPixmap(0, 0, self.pixmap)
  534. Shape.scale = self.scale
  535. for shape in self.shapes:
  536. if (shape.selected or not self._hideBackround) and self.isVisible(
  537. shape
  538. ):
  539. shape.fill = shape.selected or shape == self.hShape
  540. shape.paint(p)
  541. if self.current:
  542. self.current.paint(p)
  543. self.line.paint(p)
  544. if self.selectedShapesCopy:
  545. for s in self.selectedShapesCopy:
  546. s.paint(p)
  547. if (
  548. self.fillDrawing()
  549. and self.createMode == "polygon"
  550. and self.current is not None
  551. and len(self.current.points) >= 2
  552. ):
  553. drawing_shape = self.current.copy()
  554. drawing_shape.addPoint(self.line[1])
  555. drawing_shape.fill = True
  556. drawing_shape.paint(p)
  557. p.end()
  558. def transformPos(self, point):
  559. """Convert from widget-logical coordinates to painter-logical ones."""
  560. return point / self.scale - self.offsetToCenter()
  561. def offsetToCenter(self):
  562. s = self.scale
  563. area = super(Canvas, self).size()
  564. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  565. aw, ah = area.width(), area.height()
  566. x = (aw - w) / (2 * s) if aw > w else 0
  567. y = (ah - h) / (2 * s) if ah > h else 0
  568. return QtCore.QPoint(x, y)
  569. def outOfPixmap(self, p):
  570. w, h = self.pixmap.width(), self.pixmap.height()
  571. return not (0 <= p.x() <= w - 1 and 0 <= p.y() <= h - 1)
  572. def finalise(self):
  573. assert self.current
  574. self.current.close()
  575. self.shapes.append(self.current)
  576. self.storeShapes()
  577. self.current = None
  578. self.setHiding(False)
  579. self.newShape.emit()
  580. self.update()
  581. def closeEnough(self, p1, p2):
  582. # d = distance(p1 - p2)
  583. # m = (p1-p2).manhattanLength()
  584. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  585. # divide by scale to allow more precision when zoomed in
  586. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  587. def intersectionPoint(self, p1, p2):
  588. # Cycle through each image edge in clockwise fashion,
  589. # and find the one intersecting the current line segment.
  590. # http://paulbourke.net/geometry/lineline2d/
  591. size = self.pixmap.size()
  592. points = [
  593. (0, 0),
  594. (size.width() - 1, 0),
  595. (size.width() - 1, size.height() - 1),
  596. (0, size.height() - 1),
  597. ]
  598. # x1, y1 should be in the pixmap, x2, y2 should be out of the pixmap
  599. x1 = min(max(p1.x(), 0), size.width() - 1)
  600. y1 = min(max(p1.y(), 0), size.height() - 1)
  601. x2, y2 = p2.x(), p2.y()
  602. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  603. x3, y3 = points[i]
  604. x4, y4 = points[(i + 1) % 4]
  605. if (x, y) == (x1, y1):
  606. # Handle cases where previous point is on one of the edges.
  607. if x3 == x4:
  608. return QtCore.QPoint(x3, min(max(0, y2), max(y3, y4)))
  609. else: # y3 == y4
  610. return QtCore.QPoint(min(max(0, x2), max(x3, x4)), y3)
  611. return QtCore.QPoint(x, y)
  612. def intersectingEdges(self, point1, point2, points):
  613. """Find intersecting edges.
  614. For each edge formed by `points', yield the intersection
  615. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  616. Also return the distance of `(x2,y2)' to the middle of the
  617. edge along with its index, so that the one closest can be chosen.
  618. """
  619. (x1, y1) = point1
  620. (x2, y2) = point2
  621. for i in range(4):
  622. x3, y3 = points[i]
  623. x4, y4 = points[(i + 1) % 4]
  624. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  625. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  626. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  627. if denom == 0:
  628. # This covers two cases:
  629. # nua == nub == 0: Coincident
  630. # otherwise: Parallel
  631. continue
  632. ua, ub = nua / denom, nub / denom
  633. if 0 <= ua <= 1 and 0 <= ub <= 1:
  634. x = x1 + ua * (x2 - x1)
  635. y = y1 + ua * (y2 - y1)
  636. m = QtCore.QPoint((x3 + x4) / 2, (y3 + y4) / 2)
  637. d = labelme.utils.distance(m - QtCore.QPoint(x2, y2))
  638. yield d, i, (x, y)
  639. # These two, along with a call to adjustSize are required for the
  640. # scroll area.
  641. def sizeHint(self):
  642. return self.minimumSizeHint()
  643. def minimumSizeHint(self):
  644. if self.pixmap:
  645. return self.scale * self.pixmap.size()
  646. return super(Canvas, self).minimumSizeHint()
  647. def wheelEvent(self, ev):
  648. if QT5:
  649. mods = ev.modifiers()
  650. delta = ev.angleDelta()
  651. if QtCore.Qt.ControlModifier == int(mods):
  652. # with Ctrl/Command key
  653. # zoom
  654. self.zoomRequest.emit(delta.y(), ev.pos())
  655. else:
  656. # scroll
  657. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  658. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  659. else:
  660. if ev.orientation() == QtCore.Qt.Vertical:
  661. mods = ev.modifiers()
  662. if QtCore.Qt.ControlModifier == int(mods):
  663. # with Ctrl/Command key
  664. self.zoomRequest.emit(ev.delta(), ev.pos())
  665. else:
  666. self.scrollRequest.emit(
  667. ev.delta(),
  668. QtCore.Qt.Horizontal
  669. if (QtCore.Qt.ShiftModifier == int(mods))
  670. else QtCore.Qt.Vertical,
  671. )
  672. else:
  673. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  674. ev.accept()
  675. def keyPressEvent(self, ev):
  676. modifiers = ev.modifiers()
  677. key = ev.key()
  678. if key == QtCore.Qt.Key_Escape and self.current:
  679. self.current = None
  680. self.drawingPolygon.emit(False)
  681. self.update()
  682. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  683. self.finalise()
  684. elif modifiers == QtCore.Qt.AltModifier:
  685. self.snapping = False
  686. def keyReleaseEvent(self, ev):
  687. modifiers = ev.modifiers()
  688. if int(modifiers) == 0:
  689. self.snapping = True
  690. def setLastLabel(self, text, flags):
  691. assert text
  692. self.shapes[-1].label = text
  693. self.shapes[-1].flags = flags
  694. self.shapesBackups.pop()
  695. self.storeShapes()
  696. return self.shapes[-1]
  697. def undoLastLine(self):
  698. assert self.shapes
  699. self.current = self.shapes.pop()
  700. self.current.setOpen()
  701. if self.createMode in ["polygon", "linestrip"]:
  702. self.line.points = [self.current[-1], self.current[0]]
  703. elif self.createMode in ["rectangle", "line", "circle"]:
  704. self.current.points = self.current.points[0:1]
  705. elif self.createMode == "point":
  706. self.current = None
  707. self.drawingPolygon.emit(True)
  708. def undoLastPoint(self):
  709. if not self.current or self.current.isClosed():
  710. return
  711. self.current.popPoint()
  712. if len(self.current) > 0:
  713. self.line[0] = self.current[-1]
  714. else:
  715. self.current = None
  716. self.drawingPolygon.emit(False)
  717. self.update()
  718. def loadPixmap(self, pixmap, clear_shapes=True):
  719. self.pixmap = pixmap
  720. if clear_shapes:
  721. self.shapes = []
  722. self.update()
  723. def loadShapes(self, shapes, replace=True):
  724. if replace:
  725. self.shapes = list(shapes)
  726. else:
  727. self.shapes.extend(shapes)
  728. self.storeShapes()
  729. self.current = None
  730. self.hShape = None
  731. self.hVertex = None
  732. self.hEdge = None
  733. self.update()
  734. def setShapeVisible(self, shape, value):
  735. self.visible[shape] = value
  736. self.update()
  737. def overrideCursor(self, cursor):
  738. self.restoreCursor()
  739. self._cursor = cursor
  740. QtWidgets.QApplication.setOverrideCursor(cursor)
  741. def restoreCursor(self):
  742. QtWidgets.QApplication.restoreOverrideCursor()
  743. def resetState(self):
  744. self.restoreCursor()
  745. self.pixmap = None
  746. self.shapesBackups = []
  747. self.update()