canvas.py 26 KB

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