canvas.py 21 KB

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