canvas.py 27 KB

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