canvas.py 21 KB

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