canvas.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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.hVertex = None
  59. self.hEdge = None
  60. self.movingShape = False
  61. self._painter = QtGui.QPainter()
  62. self._cursor = CURSOR_DEFAULT
  63. # Menus:
  64. # 0: right-click without selection and dragging of shapes
  65. # 1: right-click with selection and dragging of shapes
  66. self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
  67. # Set widget options.
  68. self.setMouseTracking(True)
  69. self.setFocusPolicy(QtCore.Qt.WheelFocus)
  70. def fillDrawing(self):
  71. return self._fill_drawing
  72. def setFillDrawing(self, value):
  73. self._fill_drawing = value
  74. @property
  75. def createMode(self):
  76. return self._createMode
  77. @createMode.setter
  78. def createMode(self, value):
  79. if value not in ['polygon', 'rectangle', 'circle',
  80. 'line', 'point', 'linestrip']:
  81. raise ValueError('Unsupported createMode: %s' % value)
  82. self._createMode = value
  83. def storeShapes(self):
  84. shapesBackup = []
  85. for shape in self.shapes:
  86. shapesBackup.append(shape.copy())
  87. if len(self.shapesBackups) >= 10:
  88. self.shapesBackups = self.shapesBackups[-9:]
  89. self.shapesBackups.append(shapesBackup)
  90. @property
  91. def isShapeRestorable(self):
  92. if len(self.shapesBackups) < 2:
  93. return False
  94. return True
  95. def restoreShape(self):
  96. if not self.isShapeRestorable:
  97. return
  98. self.shapesBackups.pop() # latest
  99. shapesBackup = self.shapesBackups.pop()
  100. self.shapes = shapesBackup
  101. self.selectedShapes = []
  102. for shape in self.shapes:
  103. shape.selected = False
  104. self.repaint()
  105. def enterEvent(self, ev):
  106. self.overrideCursor(self._cursor)
  107. def leaveEvent(self, ev):
  108. self.unHighlight()
  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.update()
  127. self.hVertex, self.hShape, self.hEdge = None, None, None
  128. def selectedVertex(self):
  129. return self.hVertex is not None
  130. def mouseMoveEvent(self, ev):
  131. """Update line with last point and current coordinates."""
  132. try:
  133. if QT5:
  134. pos = self.transformPos(ev.localPos())
  135. else:
  136. pos = self.transformPos(ev.posF())
  137. except AttributeError:
  138. return
  139. self.prevMovePoint = pos
  140. self.restoreCursor()
  141. # Polygon drawing.
  142. if self.drawing():
  143. self.line.shape_type = self.createMode
  144. self.overrideCursor(CURSOR_DRAW)
  145. if not self.current:
  146. return
  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. self.overrideCursor(CURSOR_POINT)
  157. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  158. if self.createMode in ['polygon', 'linestrip']:
  159. self.line[0] = self.current[-1]
  160. self.line[1] = pos
  161. elif self.createMode == 'rectangle':
  162. self.line.points = [self.current[0], pos]
  163. self.line.close()
  164. elif self.createMode == 'circle':
  165. self.line.points = [self.current[0], pos]
  166. self.line.shape_type = "circle"
  167. elif self.createMode == 'line':
  168. self.line.points = [self.current[0], pos]
  169. self.line.close()
  170. elif self.createMode == 'point':
  171. self.line.points = [self.current[0]]
  172. self.line.close()
  173. self.repaint()
  174. self.current.highlightClear()
  175. return
  176. # Polygon copy moving.
  177. if QtCore.Qt.RightButton & ev.buttons():
  178. if self.selectedShapesCopy and self.prevPoint:
  179. self.overrideCursor(CURSOR_MOVE)
  180. self.boundedMoveShapes(self.selectedShapesCopy, pos)
  181. self.repaint()
  182. elif self.selectedShapes:
  183. self.selectedShapesCopy = \
  184. [s.copy() for s in self.selectedShapes]
  185. self.repaint()
  186. return
  187. # Polygon/Vertex moving.
  188. if QtCore.Qt.LeftButton & ev.buttons():
  189. if self.selectedVertex():
  190. self.boundedMoveVertex(pos)
  191. self.repaint()
  192. self.movingShape = True
  193. elif self.selectedShapes and self.prevPoint:
  194. self.overrideCursor(CURSOR_MOVE)
  195. self.boundedMoveShapes(self.selectedShapes, pos)
  196. self.repaint()
  197. self.movingShape = True
  198. return
  199. # Just hovering over the canvas, 2 possibilities:
  200. # - Highlight shapes
  201. # - Highlight vertex
  202. # Update shape/vertex fill and tooltip value accordingly.
  203. self.setToolTip(self.tr("Image"))
  204. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  205. # Look for a nearby vertex to highlight. If that fails,
  206. # check if we happen to be inside a shape.
  207. index = shape.nearestVertex(pos, self.epsilon / self.scale)
  208. index_edge = shape.nearestEdge(pos, self.epsilon / self.scale)
  209. if index is not None:
  210. if self.selectedVertex():
  211. self.hShape.highlightClear()
  212. self.hVertex = index
  213. self.hShape = shape
  214. self.hEdge = index_edge
  215. shape.highlightVertex(index, shape.MOVE_VERTEX)
  216. self.overrideCursor(CURSOR_POINT)
  217. self.setToolTip(self.tr("Click & drag to move point"))
  218. self.setStatusTip(self.toolTip())
  219. self.update()
  220. break
  221. elif shape.containsPoint(pos):
  222. if self.selectedVertex():
  223. self.hShape.highlightClear()
  224. self.hVertex = None
  225. self.hShape = shape
  226. self.hEdge = index_edge
  227. self.setToolTip(
  228. self.tr("Click & drag to move shape '%s'") % shape.label)
  229. self.setStatusTip(self.toolTip())
  230. self.overrideCursor(CURSOR_GRAB)
  231. self.update()
  232. break
  233. else: # Nothing found, clear highlights, reset state.
  234. self.unHighlight()
  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 and self.hShape:
  322. index = self.shapes.index(self.hShape)
  323. if (self.shapesBackups[-1][index].points !=
  324. self.shapes[index].points):
  325. self.storeShapes()
  326. self.shapeMoved.emit()
  327. self.movingShape = False
  328. def endMove(self, copy):
  329. assert self.selectedShapes and self.selectedShapesCopy
  330. assert len(self.selectedShapesCopy) == len(self.selectedShapes)
  331. if copy:
  332. for i, shape in enumerate(self.selectedShapesCopy):
  333. self.shapes.append(shape)
  334. self.selectedShapes[i].selected = False
  335. self.selectedShapes[i] = shape
  336. else:
  337. for i, shape in enumerate(self.selectedShapesCopy):
  338. self.selectedShapes[i].points = shape.points
  339. self.selectedShapesCopy = []
  340. self.repaint()
  341. self.storeShapes()
  342. return True
  343. def hideBackroundShapes(self, value):
  344. self.hideBackround = value
  345. if self.selectedShapes:
  346. # Only hide other shapes if there is a current selection.
  347. # Otherwise the user will not be able to select a shape.
  348. self.setHiding(True)
  349. self.repaint()
  350. def setHiding(self, enable=True):
  351. self._hideBackround = self.hideBackround if enable else False
  352. def canCloseShape(self):
  353. return self.drawing() and self.current and len(self.current) > 2
  354. def mouseDoubleClickEvent(self, ev):
  355. # We need at least 4 points here, since the mousePress handler
  356. # adds an extra one before this handler is called.
  357. if (self.double_click == 'close' and self.canCloseShape() and
  358. 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.hShape = None
  641. self.hVertex = None
  642. self.hEdge = None
  643. self.repaint()
  644. def setShapeVisible(self, shape, value):
  645. self.visible[shape] = value
  646. self.repaint()
  647. def overrideCursor(self, cursor):
  648. self.restoreCursor()
  649. self._cursor = cursor
  650. QtWidgets.QApplication.setOverrideCursor(cursor)
  651. def restoreCursor(self):
  652. QtWidgets.QApplication.restoreOverrideCursor()
  653. def resetState(self):
  654. self.restoreCursor()
  655. self.pixmap = None
  656. self.shapesBackups = []
  657. self.update()