canvas.py 20 KB

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