canvas.py 27 KB

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