canvas.py 20 KB

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