canvas.py 28 KB

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