canvas.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. currentShapeIndex = self.shapes.index(self.hShape)
  324. if not self.shapesBackups[-1][currentShapeIndex].points == self.shapes[currentShapeIndex].points:
  325. self.storeShapes()
  326. self.shapeMoved.emit()
  327. def endMove(self, copy):
  328. assert self.selectedShapes and self.selectedShapesCopy
  329. assert len(self.selectedShapesCopy) == len(self.selectedShapes)
  330. # del shape.fill_color
  331. # del shape.line_color
  332. if copy:
  333. for i, shape in enumerate(self.selectedShapesCopy):
  334. self.shapes.append(shape)
  335. self.selectedShapes[i].selected = False
  336. self.selectedShapes[i] = shape
  337. else:
  338. for i, shape in enumerate(self.selectedShapesCopy):
  339. self.selectedShapes[i].points = shape.points
  340. self.selectedShapesCopy = []
  341. self.repaint()
  342. self.storeShapes()
  343. return True
  344. def hideBackroundShapes(self, value):
  345. self.hideBackround = value
  346. if self.selectedShapes:
  347. # Only hide other shapes if there is a current selection.
  348. # Otherwise the user will not be able to select a shape.
  349. self.setHiding(True)
  350. self.repaint()
  351. def setHiding(self, enable=True):
  352. self._hideBackround = self.hideBackround if enable else False
  353. def canCloseShape(self):
  354. return self.drawing() and self.current and len(self.current) > 2
  355. def mouseDoubleClickEvent(self, ev):
  356. # We need at least 4 points here, since the mousePress handler
  357. # adds an extra one before this handler is called.
  358. if self.canCloseShape() and len(self.current) > 3:
  359. self.current.popPoint()
  360. self.finalise()
  361. def selectShapes(self, shapes):
  362. self.setHiding()
  363. self.selectionChanged.emit(shapes)
  364. self.update()
  365. def selectShapePoint(self, point, multiple_selection_mode):
  366. """Select the first shape created which contains this point."""
  367. if self.selectedVertex(): # A vertex is marked for selection.
  368. index, shape = self.hVertex, self.hShape
  369. shape.highlightVertex(index, shape.MOVE_VERTEX)
  370. else:
  371. for shape in reversed(self.shapes):
  372. if self.isVisible(shape) and shape.containsPoint(point):
  373. self.calculateOffsets(shape, point)
  374. self.setHiding()
  375. if multiple_selection_mode:
  376. if shape not in self.selectedShapes:
  377. self.selectionChanged.emit(
  378. self.selectedShapes + [shape])
  379. else:
  380. self.selectionChanged.emit([shape])
  381. return
  382. self.deSelectShape()
  383. def calculateOffsets(self, shape, point):
  384. rect = shape.boundingRect()
  385. x1 = rect.x() - point.x()
  386. y1 = rect.y() - point.y()
  387. x2 = (rect.x() + rect.width() - 1) - point.x()
  388. y2 = (rect.y() + rect.height() - 1) - point.y()
  389. self.offsets = QtCore.QPoint(x1, y1), QtCore.QPoint(x2, y2)
  390. def boundedMoveVertex(self, pos):
  391. index, shape = self.hVertex, self.hShape
  392. point = shape[index]
  393. if self.outOfPixmap(pos):
  394. pos = self.intersectionPoint(point, pos)
  395. shape.moveVertexBy(index, pos - point)
  396. def boundedMoveShapes(self, shapes, pos):
  397. if self.outOfPixmap(pos):
  398. return False # No need to move
  399. o1 = pos + self.offsets[0]
  400. if self.outOfPixmap(o1):
  401. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  402. o2 = pos + self.offsets[1]
  403. if self.outOfPixmap(o2):
  404. pos += QtCore.QPoint(min(0, self.pixmap.width() - o2.x()),
  405. min(0, self.pixmap.height() - o2.y()))
  406. # XXX: The next line tracks the new position of the cursor
  407. # relative to the shape, but also results in making it
  408. # a bit "shaky" when nearing the border and allows it to
  409. # go outside of the shape's area for some reason.
  410. # self.calculateOffsets(self.selectedShapes, pos)
  411. dp = pos - self.prevPoint
  412. if dp:
  413. for shape in shapes:
  414. shape.moveBy(dp)
  415. self.prevPoint = pos
  416. return True
  417. return False
  418. def deSelectShape(self):
  419. if self.selectedShapes:
  420. self.setHiding(False)
  421. self.selectionChanged.emit([])
  422. self.update()
  423. def deleteSelected(self):
  424. deleted_shapes = []
  425. if self.selectedShapes:
  426. for shape in self.selectedShapes:
  427. self.shapes.remove(shape)
  428. deleted_shapes.append(shape)
  429. self.storeShapes()
  430. self.selectedShapes = []
  431. self.update()
  432. return deleted_shapes
  433. def copySelectedShapes(self):
  434. if self.selectedShapes:
  435. self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
  436. self.boundedShiftShapes(self.selectedShapesCopy)
  437. self.endMove(copy=True)
  438. return self.selectedShapes
  439. def boundedShiftShapes(self, shapes):
  440. # Try to move in one direction, and if it fails in another.
  441. # Give up if both fail.
  442. point = shapes[0][0]
  443. offset = QtCore.QPoint(2.0, 2.0)
  444. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  445. self.prevPoint = point
  446. if not self.boundedMoveShapes(shapes, point - offset):
  447. self.boundedMoveShapes(shapes, point + offset)
  448. def paintEvent(self, event):
  449. if not self.pixmap:
  450. return super(Canvas, self).paintEvent(event)
  451. p = self._painter
  452. p.begin(self)
  453. p.setRenderHint(QtGui.QPainter.Antialiasing)
  454. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  455. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  456. p.scale(self.scale, self.scale)
  457. p.translate(self.offsetToCenter())
  458. p.drawPixmap(0, 0, self.pixmap)
  459. Shape.scale = self.scale
  460. for shape in self.shapes:
  461. if (shape.selected or not self._hideBackround) and \
  462. self.isVisible(shape):
  463. shape.fill = shape.selected or shape == self.hShape
  464. shape.paint(p)
  465. if self.current:
  466. self.current.paint(p)
  467. self.line.paint(p)
  468. if self.selectedShapesCopy:
  469. for s in self.selectedShapesCopy:
  470. s.paint(p)
  471. if (self.fillDrawing() and self.createMode == 'polygon' and
  472. self.current is not None and len(self.current.points) >= 2):
  473. drawing_shape = self.current.copy()
  474. drawing_shape.addPoint(self.line[1])
  475. drawing_shape.fill = True
  476. drawing_shape.fill_color.setAlpha(64)
  477. drawing_shape.paint(p)
  478. p.end()
  479. def transformPos(self, point):
  480. """Convert from widget-logical coordinates to painter-logical ones."""
  481. return point / self.scale - self.offsetToCenter()
  482. def offsetToCenter(self):
  483. s = self.scale
  484. area = super(Canvas, self).size()
  485. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  486. aw, ah = area.width(), area.height()
  487. x = (aw - w) / (2 * s) if aw > w else 0
  488. y = (ah - h) / (2 * s) if ah > h else 0
  489. return QtCore.QPoint(x, y)
  490. def outOfPixmap(self, p):
  491. w, h = self.pixmap.width(), self.pixmap.height()
  492. return not (0 <= p.x() <= w - 1 and 0 <= p.y() <= h - 1)
  493. def finalise(self):
  494. assert self.current
  495. self.current.close()
  496. self.shapes.append(self.current)
  497. self.storeShapes()
  498. self.current = None
  499. self.setHiding(False)
  500. self.newShape.emit()
  501. self.update()
  502. def closeEnough(self, p1, p2):
  503. # d = distance(p1 - p2)
  504. # m = (p1-p2).manhattanLength()
  505. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  506. # divide by scale to allow more precision when zoomed in
  507. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  508. def intersectionPoint(self, p1, p2):
  509. # Cycle through each image edge in clockwise fashion,
  510. # and find the one intersecting the current line segment.
  511. # http://paulbourke.net/geometry/lineline2d/
  512. size = self.pixmap.size()
  513. points = [(0, 0),
  514. (size.width() - 1, 0),
  515. (size.width() - 1, size.height() - 1),
  516. (0, size.height() - 1)]
  517. # x1, y1 should be in the pixmap, x2, y2 should be out of the pixmap
  518. x1 = min(max(p1.x(), 0), size.width() - 1)
  519. y1 = min(max(p1.y(), 0), size.height() - 1)
  520. x2, y2 = p2.x(), p2.y()
  521. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  522. x3, y3 = points[i]
  523. x4, y4 = points[(i + 1) % 4]
  524. if (x, y) == (x1, y1):
  525. # Handle cases where previous point is on one of the edges.
  526. if x3 == x4:
  527. return QtCore.QPoint(x3, min(max(0, y2), max(y3, y4)))
  528. else: # y3 == y4
  529. return QtCore.QPoint(min(max(0, x2), max(x3, x4)), y3)
  530. return QtCore.QPoint(x, y)
  531. def intersectingEdges(self, point1, point2, points):
  532. """Find intersecting edges.
  533. For each edge formed by `points', yield the intersection
  534. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  535. Also return the distance of `(x2,y2)' to the middle of the
  536. edge along with its index, so that the one closest can be chosen.
  537. """
  538. (x1, y1) = point1
  539. (x2, y2) = point2
  540. for i in range(4):
  541. x3, y3 = points[i]
  542. x4, y4 = points[(i + 1) % 4]
  543. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  544. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  545. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  546. if denom == 0:
  547. # This covers two cases:
  548. # nua == nub == 0: Coincident
  549. # otherwise: Parallel
  550. continue
  551. ua, ub = nua / denom, nub / denom
  552. if 0 <= ua <= 1 and 0 <= ub <= 1:
  553. x = x1 + ua * (x2 - x1)
  554. y = y1 + ua * (y2 - y1)
  555. m = QtCore.QPoint((x3 + x4) / 2, (y3 + y4) / 2)
  556. d = labelme.utils.distance(m - QtCore.QPoint(x2, y2))
  557. yield d, i, (x, y)
  558. # These two, along with a call to adjustSize are required for the
  559. # scroll area.
  560. def sizeHint(self):
  561. return self.minimumSizeHint()
  562. def minimumSizeHint(self):
  563. if self.pixmap:
  564. return self.scale * self.pixmap.size()
  565. return super(Canvas, self).minimumSizeHint()
  566. def wheelEvent(self, ev):
  567. if QT5:
  568. mods = ev.modifiers()
  569. delta = ev.angleDelta()
  570. if QtCore.Qt.ControlModifier == int(mods):
  571. # with Ctrl/Command key
  572. # zoom
  573. self.zoomRequest.emit(delta.y(), ev.pos())
  574. else:
  575. # scroll
  576. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  577. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  578. else:
  579. if ev.orientation() == QtCore.Qt.Vertical:
  580. mods = ev.modifiers()
  581. if QtCore.Qt.ControlModifier == int(mods):
  582. # with Ctrl/Command key
  583. self.zoomRequest.emit(ev.delta(), ev.pos())
  584. else:
  585. self.scrollRequest.emit(
  586. ev.delta(),
  587. QtCore.Qt.Horizontal
  588. if (QtCore.Qt.ShiftModifier == int(mods))
  589. else QtCore.Qt.Vertical)
  590. else:
  591. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  592. ev.accept()
  593. def keyPressEvent(self, ev):
  594. key = ev.key()
  595. if key == QtCore.Qt.Key_Escape and self.current:
  596. self.current = None
  597. self.drawingPolygon.emit(False)
  598. self.update()
  599. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  600. self.finalise()
  601. def setLastLabel(self, text, flags):
  602. assert text
  603. self.shapes[-1].label = text
  604. self.shapes[-1].flags = flags
  605. self.shapesBackups.pop()
  606. self.storeShapes()
  607. return self.shapes[-1]
  608. def undoLastLine(self):
  609. assert self.shapes
  610. self.current = self.shapes.pop()
  611. self.current.setOpen()
  612. if self.createMode in ['polygon', 'linestrip']:
  613. self.line.points = [self.current[-1], self.current[0]]
  614. elif self.createMode in ['rectangle', 'line', 'circle']:
  615. self.current.points = self.current.points[0:1]
  616. elif self.createMode == 'point':
  617. self.current = None
  618. self.drawingPolygon.emit(True)
  619. def undoLastPoint(self):
  620. if not self.current or self.current.isClosed():
  621. return
  622. self.current.popPoint()
  623. if len(self.current) > 0:
  624. self.line[0] = self.current[-1]
  625. else:
  626. self.current = None
  627. self.drawingPolygon.emit(False)
  628. self.repaint()
  629. def loadPixmap(self, pixmap):
  630. self.pixmap = pixmap
  631. self.shapes = []
  632. self.repaint()
  633. def loadShapes(self, shapes, replace=True):
  634. if replace:
  635. self.shapes = list(shapes)
  636. else:
  637. self.shapes.extend(shapes)
  638. self.storeShapes()
  639. self.current = None
  640. self.repaint()
  641. def setShapeVisible(self, shape, value):
  642. self.visible[shape] = value
  643. self.repaint()
  644. def overrideCursor(self, cursor):
  645. self.restoreCursor()
  646. self._cursor = cursor
  647. QtWidgets.QApplication.setOverrideCursor(cursor)
  648. def restoreCursor(self):
  649. QtWidgets.QApplication.restoreOverrideCursor()
  650. def resetState(self):
  651. self.restoreCursor()
  652. self.pixmap = None
  653. self.shapesBackups = []
  654. self.update()