canvas.py 27 KB

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