canvas.py 27 KB

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