canvas.py 28 KB

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