canvas.py 21 KB

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