canvas.py 20 KB

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