canvas.py 27 KB

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