canvas.py 27 KB

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