canvas.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. # flake8: noqa
  2. #
  3. # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
  4. #
  5. # This file is part of Labelme.
  6. #
  7. # Labelme is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Labelme is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Labelme. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. from __future__ import print_function
  21. import sys
  22. try:
  23. from PyQt5.QtGui import *
  24. from PyQt5.QtCore import *
  25. from PyQt5.QtWidgets import *
  26. PYQT5 = True
  27. except ImportError:
  28. from PyQt4.QtGui import *
  29. from PyQt4.QtCore import *
  30. PYQT5 = False
  31. from labelme.shape import Shape
  32. from labelme.lib import distance
  33. # TODO:
  34. # - [maybe] Find optimal epsilon value.
  35. CURSOR_DEFAULT = Qt.ArrowCursor
  36. CURSOR_POINT = Qt.PointingHandCursor
  37. CURSOR_DRAW = Qt.CrossCursor
  38. CURSOR_MOVE = Qt.ClosedHandCursor
  39. CURSOR_GRAB = Qt.OpenHandCursor
  40. #class Canvas(QGLWidget):
  41. class Canvas(QWidget):
  42. zoomRequest = pyqtSignal(int)
  43. scrollRequest = pyqtSignal(int, int)
  44. newShape = pyqtSignal()
  45. selectionChanged = pyqtSignal(bool)
  46. shapeMoved = pyqtSignal()
  47. drawingPolygon = pyqtSignal(bool)
  48. CREATE, EDIT = 0, 1
  49. epsilon = 11.0
  50. def __init__(self, *args, **kwargs):
  51. super(Canvas, self).__init__(*args, **kwargs)
  52. # Initialise local state.
  53. self.mode = self.EDIT
  54. self.shapes = []
  55. self.current = None
  56. self.selectedShape=None # save the selected shape here
  57. self.selectedShapeCopy=None
  58. self.lineColor = QColor(0, 0, 255)
  59. self.line = Shape(line_color=self.lineColor)
  60. self.prevPoint = QPointF()
  61. self.offsets = QPointF(), QPointF()
  62. self.scale = 1.0
  63. self.pixmap = QPixmap()
  64. self.visible = {}
  65. self._hideBackround = False
  66. self.hideBackround = False
  67. self.hShape = None
  68. self.hVertex = None
  69. self._painter = QPainter()
  70. self._cursor = CURSOR_DEFAULT
  71. # Menus:
  72. self.menus = (QMenu(), QMenu())
  73. # Set widget options.
  74. self.setMouseTracking(True)
  75. self.setFocusPolicy(Qt.WheelFocus)
  76. def enterEvent(self, ev):
  77. self.overrideCursor(self._cursor)
  78. def leaveEvent(self, ev):
  79. self.restoreCursor()
  80. def focusOutEvent(self, ev):
  81. self.restoreCursor()
  82. def isVisible(self, shape):
  83. return self.visible.get(shape, True)
  84. def drawing(self):
  85. return self.mode == self.CREATE
  86. def editing(self):
  87. return self.mode == self.EDIT
  88. def setEditing(self, value=True):
  89. self.mode = self.EDIT if value else self.CREATE
  90. if not value: # Create
  91. self.unHighlight()
  92. self.deSelectShape()
  93. def unHighlight(self):
  94. if self.hShape:
  95. self.hShape.highlightClear()
  96. self.hVertex = self.hShape = None
  97. def selectedVertex(self):
  98. return self.hVertex is not None
  99. def mouseMoveEvent(self, ev):
  100. """Update line with last point and current coordinates."""
  101. if PYQT5:
  102. pos = self.transformPos(ev.pos())
  103. else:
  104. pos = self.transformPos(ev.posF())
  105. self.restoreCursor()
  106. # Polygon drawing.
  107. if self.drawing():
  108. self.overrideCursor(CURSOR_DRAW)
  109. if self.current:
  110. color = self.lineColor
  111. if self.outOfPixmap(pos):
  112. # Don't allow the user to draw outside the pixmap.
  113. # Project the point to the pixmap's edges.
  114. pos = self.intersectionPoint(self.current[-1], pos)
  115. elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  116. # Attract line to starting point and colorise to alert the user:
  117. pos = self.current[0]
  118. color = self.current.line_color
  119. self.overrideCursor(CURSOR_POINT)
  120. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  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 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. if Qt.LeftButton & ev.buttons():
  138. if self.selectedVertex():
  139. self.boundedMoveVertex(pos)
  140. self.shapeMoved.emit()
  141. self.repaint()
  142. elif self.selectedShape and self.prevPoint:
  143. self.overrideCursor(CURSOR_MOVE)
  144. self.boundedMoveShape(self.selectedShape, pos)
  145. self.shapeMoved.emit()
  146. self.repaint()
  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("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 PYQT5:
  183. pos = self.transformPos(ev.pos())
  184. else:
  185. pos = self.transformPos(ev.posF())
  186. if ev.button() == Qt.LeftButton:
  187. if self.drawing():
  188. if self.current:
  189. try:
  190. self.current.addPoint(self.line[1])
  191. except Exception as e:
  192. print(e, file=sys.stderr)
  193. return
  194. self.line[0] = self.current[-1]
  195. if self.current.isClosed():
  196. self.finalise()
  197. elif not self.outOfPixmap(pos):
  198. self.current = Shape()
  199. self.current.addPoint(pos)
  200. self.line.points = [pos, pos]
  201. self.setHiding()
  202. self.drawingPolygon.emit(True)
  203. self.update()
  204. else:
  205. self.selectShapePoint(pos)
  206. self.prevPoint = pos
  207. self.repaint()
  208. elif ev.button() == Qt.RightButton and self.editing():
  209. self.selectShapePoint(pos)
  210. self.prevPoint = pos
  211. self.repaint()
  212. def mouseReleaseEvent(self, ev):
  213. if ev.button() == Qt.RightButton:
  214. menu = self.menus[bool(self.selectedShapeCopy)]
  215. self.restoreCursor()
  216. if not menu.exec_(self.mapToGlobal(ev.pos()))\
  217. and self.selectedShapeCopy:
  218. # Cancel the move by deleting the shadow copy.
  219. self.selectedShapeCopy = None
  220. self.repaint()
  221. elif ev.button() == Qt.LeftButton and self.selectedShape:
  222. self.overrideCursor(CURSOR_GRAB)
  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.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 = QPointF(x1, y1), 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 -= QPointF(min(0, o1.x()), min(0, o1.y()))
  296. o2 = pos + self.offsets[1]
  297. if self.outOfPixmap(o2):
  298. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  299. min(0, self.pixmap.height()- o2.y()))
  300. # 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. XXX
  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.selectedShape = None
  323. self.update()
  324. return shape
  325. def copySelectedShape(self):
  326. if self.selectedShape:
  327. shape = self.selectedShape.copy()
  328. self.deSelectShape()
  329. self.shapes.append(shape)
  330. shape.selected = True
  331. self.selectedShape = shape
  332. self.boundedShiftShape(shape)
  333. return shape
  334. def boundedShiftShape(self, shape):
  335. # Try to move in one direction, and if it fails in another.
  336. # Give up if both fail.
  337. point = shape[0]
  338. offset = QPointF(2.0, 2.0)
  339. self.calculateOffsets(shape, point)
  340. self.prevPoint = point
  341. if not self.boundedMoveShape(shape, point - offset):
  342. self.boundedMoveShape(shape, point + offset)
  343. def paintEvent(self, event):
  344. if not self.pixmap:
  345. return super(Canvas, self).paintEvent(event)
  346. p = self._painter
  347. p.begin(self)
  348. p.setRenderHint(QPainter.Antialiasing)
  349. p.setRenderHint(QPainter.HighQualityAntialiasing)
  350. p.setRenderHint(QPainter.SmoothPixmapTransform)
  351. p.scale(self.scale, self.scale)
  352. p.translate(self.offsetToCenter())
  353. p.drawPixmap(0, 0, self.pixmap)
  354. Shape.scale = self.scale
  355. for shape in self.shapes:
  356. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  357. shape.fill = shape.selected or shape == self.hShape
  358. shape.paint(p)
  359. if self.current:
  360. self.current.paint(p)
  361. self.line.paint(p)
  362. if self.selectedShapeCopy:
  363. self.selectedShapeCopy.paint(p)
  364. p.end()
  365. def transformPos(self, point):
  366. """Convert from widget-logical coordinates to painter-logical coordinates."""
  367. return point / self.scale - self.offsetToCenter()
  368. def offsetToCenter(self):
  369. s = self.scale
  370. area = super(Canvas, self).size()
  371. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  372. aw, ah = area.width(), area.height()
  373. x = (aw-w)/(2*s) if aw > w else 0
  374. y = (ah-h)/(2*s) if ah > h else 0
  375. return QPointF(x, y)
  376. def outOfPixmap(self, p):
  377. w, h = self.pixmap.width(), self.pixmap.height()
  378. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  379. def finalise(self):
  380. assert self.current
  381. self.current.close()
  382. self.shapes.append(self.current)
  383. self.current = None
  384. self.setHiding(False)
  385. self.newShape.emit()
  386. self.update()
  387. def closeEnough(self, p1, p2):
  388. #d = distance(p1 - p2)
  389. #m = (p1-p2).manhattanLength()
  390. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  391. return distance(p1 - p2) < self.epsilon
  392. def intersectionPoint(self, p1, p2):
  393. # Cycle through each image edge in clockwise fashion,
  394. # and find the one intersecting the current line segment.
  395. # http://paulbourke.net/geometry/lineline2d/
  396. size = self.pixmap.size()
  397. points = [(0,0),
  398. (size.width(), 0),
  399. (size.width(), size.height()),
  400. (0, size.height())]
  401. x1, y1 = p1.x(), p1.y()
  402. x2, y2 = p2.x(), p2.y()
  403. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  404. x3, y3 = points[i]
  405. x4, y4 = points[(i+1)%4]
  406. if (x, y) == (x1, y1):
  407. # Handle cases where previous point is on one of the edges.
  408. if x3 == x4:
  409. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  410. else: # y3 == y4
  411. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  412. return QPointF(x, y)
  413. def intersectingEdges(self, point1, point2, points):
  414. """For each edge formed by `points', yield the intersection
  415. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  416. Also return the distance of `(x2,y2)' to the middle of the
  417. edge along with its index, so that the one closest can be chosen."""
  418. (x1, y1) = point1
  419. (x2, y2) = point2
  420. for i in range(4):
  421. x3, y3 = points[i]
  422. x4, y4 = points[(i+1) % 4]
  423. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  424. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  425. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  426. if denom == 0:
  427. # This covers two cases:
  428. # nua == nub == 0: Coincident
  429. # otherwise: Parallel
  430. continue
  431. ua, ub = nua / denom, nub / denom
  432. if 0 <= ua <= 1 and 0 <= ub <= 1:
  433. x = x1 + ua * (x2 - x1)
  434. y = y1 + ua * (y2 - y1)
  435. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  436. d = distance(m - QPointF(x2, y2))
  437. yield d, i, (x, y)
  438. # These two, along with a call to adjustSize are required for the
  439. # scroll area.
  440. def sizeHint(self):
  441. return self.minimumSizeHint()
  442. def minimumSizeHint(self):
  443. if self.pixmap:
  444. return self.scale * self.pixmap.size()
  445. return super(Canvas, self).minimumSizeHint()
  446. def wheelEvent(self, ev):
  447. if PYQT5:
  448. mods = ev.modifiers()
  449. delta = ev.pixelDelta()
  450. if Qt.ControlModifier == int(mods): # with Ctrl/Command key
  451. # zoom
  452. self.zoomRequest.emit(delta.y())
  453. else:
  454. # scroll
  455. self.scrollRequest.emit(delta.x(), Qt.Horizontal)
  456. self.scrollRequest.emit(delta.y(), Qt.Vertical)
  457. else:
  458. if ev.orientation() == Qt.Vertical:
  459. mods = ev.modifiers()
  460. if Qt.ControlModifier == int(mods): # with Ctrl/Command key
  461. self.zoomRequest.emit(ev.delta())
  462. else:
  463. self.scrollRequest.emit(ev.delta(),
  464. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  465. else Qt.Vertical)
  466. else:
  467. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  468. ev.accept()
  469. def keyPressEvent(self, ev):
  470. key = ev.key()
  471. if key == Qt.Key_Escape and self.current:
  472. self.current = None
  473. self.drawingPolygon.emit(False)
  474. self.update()
  475. elif key == Qt.Key_Return and self.canCloseShape():
  476. self.finalise()
  477. def setLastLabel(self, text):
  478. assert text
  479. self.shapes[-1].label = text
  480. return self.shapes[-1]
  481. def undoLastLine(self):
  482. assert self.shapes
  483. self.current = self.shapes.pop()
  484. self.current.setOpen()
  485. self.line.points = [self.current[-1], self.current[0]]
  486. self.drawingPolygon.emit(True)
  487. def loadPixmap(self, pixmap):
  488. self.pixmap = pixmap
  489. self.shapes = []
  490. self.repaint()
  491. def loadShapes(self, shapes):
  492. self.shapes = list(shapes)
  493. self.current = None
  494. self.repaint()
  495. def setShapeVisible(self, shape, value):
  496. self.visible[shape] = value
  497. self.repaint()
  498. def overrideCursor(self, cursor):
  499. self.restoreCursor()
  500. self._cursor = cursor
  501. QApplication.setOverrideCursor(cursor)
  502. def restoreCursor(self):
  503. QApplication.restoreOverrideCursor()
  504. def resetState(self):
  505. self.restoreCursor()
  506. self.pixmap = None
  507. self.update()