canvas.py 27 KB

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