canvas.py 19 KB

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