canvas.py 22 KB

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