canvas.py 20 KB

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