canvas.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. import imgviz
  2. from qtpy import QtCore
  3. from qtpy import QtGui
  4. from qtpy import QtWidgets
  5. import labelme.ai
  6. import labelme.utils
  7. from labelme import QT5
  8. from labelme.logger import logger
  9. from labelme.shape import Shape
  10. # TODO(unknown):
  11. # - [maybe] Find optimal epsilon value.
  12. CURSOR_DEFAULT = QtCore.Qt.ArrowCursor
  13. CURSOR_POINT = QtCore.Qt.PointingHandCursor
  14. CURSOR_DRAW = QtCore.Qt.CrossCursor
  15. CURSOR_MOVE = QtCore.Qt.ClosedHandCursor
  16. CURSOR_GRAB = QtCore.Qt.OpenHandCursor
  17. MOVE_SPEED = 5.0
  18. class Canvas(QtWidgets.QWidget):
  19. zoomRequest = QtCore.Signal(int, QtCore.QPoint)
  20. scrollRequest = QtCore.Signal(int, int)
  21. newShape = QtCore.Signal()
  22. selectionChanged = QtCore.Signal(list)
  23. shapeMoved = QtCore.Signal()
  24. drawingPolygon = QtCore.Signal(bool)
  25. vertexSelected = QtCore.Signal(bool)
  26. CREATE, EDIT = 0, 1
  27. # polygon, rectangle, line, or point
  28. _createMode = "polygon"
  29. _fill_drawing = False
  30. def __init__(self, *args, **kwargs):
  31. self.epsilon = kwargs.pop("epsilon", 10.0)
  32. self.double_click = kwargs.pop("double_click", "close")
  33. if self.double_click not in [None, "close"]:
  34. raise ValueError(
  35. "Unexpected value for double_click event: {}".format(self.double_click)
  36. )
  37. self.num_backups = kwargs.pop("num_backups", 10)
  38. self._crosshair = kwargs.pop(
  39. "crosshair",
  40. {
  41. "polygon": False,
  42. "rectangle": True,
  43. "circle": False,
  44. "line": False,
  45. "point": False,
  46. "linestrip": False,
  47. "ai_polygon": False,
  48. "ai_mask": False,
  49. },
  50. )
  51. super(Canvas, self).__init__(*args, **kwargs)
  52. # Initialise local state.
  53. self.mode = self.EDIT
  54. self.shapes = []
  55. self.shapesBackups = []
  56. self.current = None
  57. self.selectedShapes = [] # save the selected shapes here
  58. self.selectedShapesCopy = []
  59. # self.line represents:
  60. # - createMode == 'polygon': edge from last point to current
  61. # - createMode == 'rectangle': diagonal line of the rectangle
  62. # - createMode == 'line': the line
  63. # - createMode == 'point': the point
  64. self.line = Shape()
  65. self.prevPoint = QtCore.QPoint()
  66. self.prevMovePoint = QtCore.QPoint()
  67. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  68. self.scale = 1.0
  69. self.pixmap = QtGui.QPixmap()
  70. self.visible = {}
  71. self._hideBackround = False
  72. self.hideBackround = False
  73. self.hShape = None
  74. self.prevhShape = None
  75. self.hVertex = None
  76. self.prevhVertex = None
  77. self.hEdge = None
  78. self.prevhEdge = None
  79. self.movingShape = False
  80. self.snapping = True
  81. self.hShapeIsSelected = False
  82. self._painter = QtGui.QPainter()
  83. self._cursor = CURSOR_DEFAULT
  84. # Menus:
  85. # 0: right-click without selection and dragging of shapes
  86. # 1: right-click with selection and dragging of shapes
  87. self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
  88. # Set widget options.
  89. self.setMouseTracking(True)
  90. self.setFocusPolicy(QtCore.Qt.WheelFocus)
  91. self._ai_model = None
  92. def fillDrawing(self):
  93. return self._fill_drawing
  94. def setFillDrawing(self, value):
  95. self._fill_drawing = value
  96. @property
  97. def createMode(self):
  98. return self._createMode
  99. @createMode.setter
  100. def createMode(self, value):
  101. if value not in [
  102. "polygon",
  103. "rectangle",
  104. "circle",
  105. "line",
  106. "point",
  107. "linestrip",
  108. "ai_polygon",
  109. "ai_mask",
  110. ]:
  111. raise ValueError("Unsupported createMode: %s" % value)
  112. self._createMode = value
  113. def initializeAiModel(self, name):
  114. if name not in [model.name for model in labelme.ai.MODELS]:
  115. raise ValueError("Unsupported ai model: %s" % name)
  116. model = [model for model in labelme.ai.MODELS if model.name == name][0]
  117. if self._ai_model is not None and self._ai_model.name == model.name:
  118. logger.debug("AI model is already initialized: %r" % model.name)
  119. else:
  120. logger.debug("Initializing AI model: %r" % model.name)
  121. self._ai_model = model()
  122. if self.pixmap is None:
  123. logger.warning("Pixmap is not set yet")
  124. return
  125. self._ai_model.set_image(
  126. image=labelme.utils.img_qt_to_arr(self.pixmap.toImage())
  127. )
  128. def storeShapes(self):
  129. shapesBackup = []
  130. for shape in self.shapes:
  131. shapesBackup.append(shape.copy())
  132. if len(self.shapesBackups) > self.num_backups:
  133. self.shapesBackups = self.shapesBackups[-self.num_backups - 1 :]
  134. self.shapesBackups.append(shapesBackup)
  135. @property
  136. def isShapeRestorable(self):
  137. # We save the state AFTER each edit (not before) so for an
  138. # edit to be undoable, we expect the CURRENT and the PREVIOUS state
  139. # to be in the undo stack.
  140. if len(self.shapesBackups) < 2:
  141. return False
  142. return True
  143. def restoreShape(self):
  144. # This does _part_ of the job of restoring shapes.
  145. # The complete process is also done in app.py::undoShapeEdit
  146. # and app.py::loadShapes and our own Canvas::loadShapes function.
  147. if not self.isShapeRestorable:
  148. return
  149. self.shapesBackups.pop() # latest
  150. # The application will eventually call Canvas.loadShapes which will
  151. # push this right back onto the stack.
  152. shapesBackup = self.shapesBackups.pop()
  153. self.shapes = shapesBackup
  154. self.selectedShapes = []
  155. for shape in self.shapes:
  156. shape.selected = False
  157. self.update()
  158. def enterEvent(self, ev):
  159. self.overrideCursor(self._cursor)
  160. def leaveEvent(self, ev):
  161. self.unHighlight()
  162. self.restoreCursor()
  163. def focusOutEvent(self, ev):
  164. self.restoreCursor()
  165. def isVisible(self, shape):
  166. return self.visible.get(shape, True)
  167. def drawing(self):
  168. return self.mode == self.CREATE
  169. def editing(self):
  170. return self.mode == self.EDIT
  171. def setEditing(self, value=True):
  172. self.mode = self.EDIT if value else self.CREATE
  173. if self.mode == self.EDIT:
  174. # CREATE -> EDIT
  175. self.repaint() # clear crosshair
  176. else:
  177. # EDIT -> CREATE
  178. self.unHighlight()
  179. self.deSelectShape()
  180. def unHighlight(self):
  181. if self.hShape:
  182. self.hShape.highlightClear()
  183. self.update()
  184. self.prevhShape = self.hShape
  185. self.prevhVertex = self.hVertex
  186. self.prevhEdge = self.hEdge
  187. self.hShape = self.hVertex = self.hEdge = None
  188. def selectedVertex(self):
  189. return self.hVertex is not None
  190. def selectedEdge(self):
  191. return self.hEdge is not None
  192. def mouseMoveEvent(self, ev):
  193. """Update line with last point and current coordinates."""
  194. try:
  195. if QT5:
  196. pos = self.transformPos(ev.localPos())
  197. else:
  198. pos = self.transformPos(ev.posF())
  199. except AttributeError:
  200. return
  201. self.prevMovePoint = pos
  202. self.restoreCursor()
  203. is_shift_pressed = ev.modifiers() & QtCore.Qt.ShiftModifier
  204. # Polygon drawing.
  205. if self.drawing():
  206. if self.createMode in ["ai_polygon", "ai_mask"]:
  207. self.line.shape_type = "points"
  208. else:
  209. self.line.shape_type = self.createMode
  210. self.overrideCursor(CURSOR_DRAW)
  211. if not self.current:
  212. self.repaint() # draw crosshair
  213. return
  214. if self.outOfPixmap(pos):
  215. # Don't allow the user to draw outside the pixmap.
  216. # Project the point to the pixmap's edges.
  217. pos = self.intersectionPoint(self.current[-1], pos)
  218. elif (
  219. self.snapping
  220. and len(self.current) > 1
  221. and self.createMode == "polygon"
  222. and self.closeEnough(pos, self.current[0])
  223. ):
  224. # Attract line to starting point and
  225. # colorise to alert the user.
  226. pos = self.current[0]
  227. self.overrideCursor(CURSOR_POINT)
  228. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  229. if self.createMode in ["polygon", "linestrip"]:
  230. self.line.points = [self.current[-1], pos]
  231. self.line.point_labels = [1, 1]
  232. elif self.createMode in ["ai_polygon", "ai_mask"]:
  233. self.line.points = [self.current.points[-1], pos]
  234. self.line.point_labels = [
  235. self.current.point_labels[-1],
  236. 0 if is_shift_pressed else 1,
  237. ]
  238. elif self.createMode == "rectangle":
  239. self.line.points = [self.current[0], pos]
  240. self.line.point_labels = [1, 1]
  241. self.line.close()
  242. elif self.createMode == "circle":
  243. self.line.points = [self.current[0], pos]
  244. self.line.point_labels = [1, 1]
  245. self.line.shape_type = "circle"
  246. elif self.createMode == "line":
  247. self.line.points = [self.current[0], pos]
  248. self.line.point_labels = [1, 1]
  249. self.line.close()
  250. elif self.createMode == "point":
  251. self.line.points = [self.current[0]]
  252. self.line.point_labels = [1]
  253. self.line.close()
  254. assert len(self.line.points) == len(self.line.point_labels)
  255. self.repaint()
  256. self.current.highlightClear()
  257. return
  258. # Polygon copy moving.
  259. if QtCore.Qt.RightButton & ev.buttons():
  260. if self.selectedShapesCopy and self.prevPoint:
  261. self.overrideCursor(CURSOR_MOVE)
  262. self.boundedMoveShapes(self.selectedShapesCopy, pos)
  263. self.repaint()
  264. elif self.selectedShapes:
  265. self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
  266. self.repaint()
  267. return
  268. # Polygon/Vertex moving.
  269. if QtCore.Qt.LeftButton & ev.buttons():
  270. if self.selectedVertex():
  271. self.boundedMoveVertex(pos)
  272. self.repaint()
  273. self.movingShape = True
  274. elif self.selectedShapes and self.prevPoint:
  275. self.overrideCursor(CURSOR_MOVE)
  276. self.boundedMoveShapes(self.selectedShapes, pos)
  277. self.repaint()
  278. self.movingShape = True
  279. return
  280. # Just hovering over the canvas, 2 possibilities:
  281. # - Highlight shapes
  282. # - Highlight vertex
  283. # Update shape/vertex fill and tooltip value accordingly.
  284. self.setToolTip(self.tr("Image"))
  285. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  286. # Look for a nearby vertex to highlight. If that fails,
  287. # check if we happen to be inside a shape.
  288. index = shape.nearestVertex(pos, self.epsilon / self.scale)
  289. index_edge = shape.nearestEdge(pos, self.epsilon / self.scale)
  290. if index is not None:
  291. if self.selectedVertex():
  292. self.hShape.highlightClear()
  293. self.prevhVertex = self.hVertex = index
  294. self.prevhShape = self.hShape = shape
  295. self.prevhEdge = self.hEdge
  296. self.hEdge = None
  297. shape.highlightVertex(index, shape.MOVE_VERTEX)
  298. self.overrideCursor(CURSOR_POINT)
  299. self.setToolTip(self.tr("Click & drag to move point"))
  300. self.setStatusTip(self.toolTip())
  301. self.update()
  302. break
  303. elif index_edge is not None and shape.canAddPoint():
  304. if self.selectedVertex():
  305. self.hShape.highlightClear()
  306. self.prevhVertex = self.hVertex
  307. self.hVertex = None
  308. self.prevhShape = self.hShape = shape
  309. self.prevhEdge = self.hEdge = index_edge
  310. self.overrideCursor(CURSOR_POINT)
  311. self.setToolTip(self.tr("Click to create point"))
  312. self.setStatusTip(self.toolTip())
  313. self.update()
  314. break
  315. elif shape.containsPoint(pos):
  316. if self.selectedVertex():
  317. self.hShape.highlightClear()
  318. self.prevhVertex = self.hVertex
  319. self.hVertex = None
  320. self.prevhShape = self.hShape = shape
  321. self.prevhEdge = self.hEdge
  322. self.hEdge = None
  323. self.setToolTip(
  324. self.tr("Click & drag to move shape '%s'") % shape.label
  325. )
  326. self.setStatusTip(self.toolTip())
  327. self.overrideCursor(CURSOR_GRAB)
  328. self.update()
  329. break
  330. else: # Nothing found, clear highlights, reset state.
  331. self.unHighlight()
  332. self.vertexSelected.emit(self.hVertex is not None)
  333. def addPointToEdge(self):
  334. shape = self.prevhShape
  335. index = self.prevhEdge
  336. point = self.prevMovePoint
  337. if shape is None or index is None or point is None:
  338. return
  339. shape.insertPoint(index, point)
  340. shape.highlightVertex(index, shape.MOVE_VERTEX)
  341. self.hShape = shape
  342. self.hVertex = index
  343. self.hEdge = None
  344. self.movingShape = True
  345. def removeSelectedPoint(self):
  346. shape = self.prevhShape
  347. index = self.prevhVertex
  348. if shape is None or index is None:
  349. return
  350. shape.removePoint(index)
  351. shape.highlightClear()
  352. self.hShape = shape
  353. self.prevhVertex = None
  354. self.movingShape = True # Save changes
  355. def mousePressEvent(self, ev):
  356. if QT5:
  357. pos = self.transformPos(ev.localPos())
  358. else:
  359. pos = self.transformPos(ev.posF())
  360. is_shift_pressed = ev.modifiers() & QtCore.Qt.ShiftModifier
  361. if ev.button() == QtCore.Qt.LeftButton:
  362. if self.drawing():
  363. if self.current:
  364. # Add point to existing shape.
  365. if self.createMode == "polygon":
  366. self.current.addPoint(self.line[1])
  367. self.line[0] = self.current[-1]
  368. if self.current.isClosed():
  369. self.finalise()
  370. elif self.createMode in ["rectangle", "circle", "line"]:
  371. assert len(self.current.points) == 1
  372. self.current.points = self.line.points
  373. self.finalise()
  374. elif self.createMode == "linestrip":
  375. self.current.addPoint(self.line[1])
  376. self.line[0] = self.current[-1]
  377. if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
  378. self.finalise()
  379. elif self.createMode in ["ai_polygon", "ai_mask"]:
  380. self.current.addPoint(
  381. self.line.points[1],
  382. label=self.line.point_labels[1],
  383. )
  384. self.line.points[0] = self.current.points[-1]
  385. self.line.point_labels[0] = self.current.point_labels[-1]
  386. if ev.modifiers() & QtCore.Qt.ControlModifier:
  387. self.finalise()
  388. elif not self.outOfPixmap(pos):
  389. # Create new shape.
  390. self.current = Shape(
  391. shape_type="points"
  392. if self.createMode in ["ai_polygon", "ai_mask"]
  393. else self.createMode
  394. )
  395. self.current.addPoint(pos, label=0 if is_shift_pressed else 1)
  396. if self.createMode == "point":
  397. self.finalise()
  398. elif (
  399. self.createMode in ["ai_polygon", "ai_mask"]
  400. and ev.modifiers() & QtCore.Qt.ControlModifier
  401. ):
  402. self.finalise()
  403. else:
  404. if self.createMode == "circle":
  405. self.current.shape_type = "circle"
  406. self.line.points = [pos, pos]
  407. if (
  408. self.createMode in ["ai_polygon", "ai_mask"]
  409. and is_shift_pressed
  410. ):
  411. self.line.point_labels = [0, 0]
  412. else:
  413. self.line.point_labels = [1, 1]
  414. self.setHiding()
  415. self.drawingPolygon.emit(True)
  416. self.update()
  417. elif self.editing():
  418. if self.selectedEdge():
  419. self.addPointToEdge()
  420. elif (
  421. self.selectedVertex()
  422. and int(ev.modifiers()) == QtCore.Qt.ShiftModifier
  423. ):
  424. # Delete point if: left-click + SHIFT on a point
  425. self.removeSelectedPoint()
  426. group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
  427. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  428. self.prevPoint = pos
  429. self.repaint()
  430. elif ev.button() == QtCore.Qt.RightButton and self.editing():
  431. group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
  432. if not self.selectedShapes or (
  433. self.hShape is not None and self.hShape not in self.selectedShapes
  434. ):
  435. self.selectShapePoint(pos, multiple_selection_mode=group_mode)
  436. self.repaint()
  437. self.prevPoint = pos
  438. def mouseReleaseEvent(self, ev):
  439. if ev.button() == QtCore.Qt.RightButton:
  440. menu = self.menus[len(self.selectedShapesCopy) > 0]
  441. self.restoreCursor()
  442. if not menu.exec_(self.mapToGlobal(ev.pos())) and self.selectedShapesCopy:
  443. # Cancel the move by deleting the shadow copy.
  444. self.selectedShapesCopy = []
  445. self.repaint()
  446. elif ev.button() == QtCore.Qt.LeftButton:
  447. if self.editing():
  448. if (
  449. self.hShape is not None
  450. and self.hShapeIsSelected
  451. and not self.movingShape
  452. ):
  453. self.selectionChanged.emit(
  454. [x for x in self.selectedShapes if x != self.hShape]
  455. )
  456. if self.movingShape and self.hShape:
  457. index = self.shapes.index(self.hShape)
  458. if self.shapesBackups[-1][index].points != self.shapes[index].points:
  459. self.storeShapes()
  460. self.shapeMoved.emit()
  461. self.movingShape = False
  462. def endMove(self, copy):
  463. assert self.selectedShapes and self.selectedShapesCopy
  464. assert len(self.selectedShapesCopy) == len(self.selectedShapes)
  465. if copy:
  466. for i, shape in enumerate(self.selectedShapesCopy):
  467. self.shapes.append(shape)
  468. self.selectedShapes[i].selected = False
  469. self.selectedShapes[i] = shape
  470. else:
  471. for i, shape in enumerate(self.selectedShapesCopy):
  472. self.selectedShapes[i].points = shape.points
  473. self.selectedShapesCopy = []
  474. self.repaint()
  475. self.storeShapes()
  476. return True
  477. def hideBackroundShapes(self, value):
  478. self.hideBackround = value
  479. if self.selectedShapes:
  480. # Only hide other shapes if there is a current selection.
  481. # Otherwise the user will not be able to select a shape.
  482. self.setHiding(True)
  483. self.update()
  484. def setHiding(self, enable=True):
  485. self._hideBackround = self.hideBackround if enable else False
  486. def canCloseShape(self):
  487. return self.drawing() and ((self.current and len(self.current) > 2) or self.createMode in ["ai_polygon", "ai_mask"])
  488. def mouseDoubleClickEvent(self, ev):
  489. if self.double_click != "close":
  490. return
  491. if (
  492. self.createMode == "polygon" and self.canCloseShape()
  493. ) or self.createMode in ["ai_polygon", "ai_mask"]:
  494. self.finalise()
  495. def selectShapes(self, shapes):
  496. self.setHiding()
  497. self.selectionChanged.emit(shapes)
  498. self.update()
  499. def selectShapePoint(self, point, multiple_selection_mode):
  500. """Select the first shape created which contains this point."""
  501. if self.selectedVertex(): # A vertex is marked for selection.
  502. index, shape = self.hVertex, self.hShape
  503. shape.highlightVertex(index, shape.MOVE_VERTEX)
  504. else:
  505. for shape in reversed(self.shapes):
  506. if self.isVisible(shape) and shape.containsPoint(point):
  507. self.setHiding()
  508. if shape not in self.selectedShapes:
  509. if multiple_selection_mode:
  510. self.selectionChanged.emit(self.selectedShapes + [shape])
  511. else:
  512. self.selectionChanged.emit([shape])
  513. self.hShapeIsSelected = False
  514. else:
  515. self.hShapeIsSelected = True
  516. self.calculateOffsets(point)
  517. return
  518. self.deSelectShape()
  519. def calculateOffsets(self, point):
  520. left = self.pixmap.width() - 1
  521. right = 0
  522. top = self.pixmap.height() - 1
  523. bottom = 0
  524. for s in self.selectedShapes:
  525. rect = s.boundingRect()
  526. if rect.left() < left:
  527. left = rect.left()
  528. if rect.right() > right:
  529. right = rect.right()
  530. if rect.top() < top:
  531. top = rect.top()
  532. if rect.bottom() > bottom:
  533. bottom = rect.bottom()
  534. x1 = left - point.x()
  535. y1 = top - point.y()
  536. x2 = right - point.x()
  537. y2 = bottom - point.y()
  538. self.offsets = QtCore.QPointF(x1, y1), QtCore.QPointF(x2, y2)
  539. def boundedMoveVertex(self, pos):
  540. index, shape = self.hVertex, self.hShape
  541. point = shape[index]
  542. if self.outOfPixmap(pos):
  543. pos = self.intersectionPoint(point, pos)
  544. shape.moveVertexBy(index, pos - point)
  545. def boundedMoveShapes(self, shapes, pos):
  546. if self.outOfPixmap(pos):
  547. return False # No need to move
  548. o1 = pos + self.offsets[0]
  549. if self.outOfPixmap(o1):
  550. pos -= QtCore.QPointF(min(0, o1.x()), min(0, o1.y()))
  551. o2 = pos + self.offsets[1]
  552. if self.outOfPixmap(o2):
  553. pos += QtCore.QPointF(
  554. min(0, self.pixmap.width() - o2.x()),
  555. min(0, self.pixmap.height() - o2.y()),
  556. )
  557. # XXX: The next line tracks the new position of the cursor
  558. # relative to the shape, but also results in making it
  559. # a bit "shaky" when nearing the border and allows it to
  560. # go outside of the shape's area for some reason.
  561. # self.calculateOffsets(self.selectedShapes, pos)
  562. dp = pos - self.prevPoint
  563. if dp:
  564. for shape in shapes:
  565. shape.moveBy(dp)
  566. self.prevPoint = pos
  567. return True
  568. return False
  569. def deSelectShape(self):
  570. if self.selectedShapes:
  571. self.setHiding(False)
  572. self.selectionChanged.emit([])
  573. self.hShapeIsSelected = False
  574. self.update()
  575. def deleteSelected(self):
  576. deleted_shapes = []
  577. if self.selectedShapes:
  578. for shape in self.selectedShapes:
  579. self.shapes.remove(shape)
  580. deleted_shapes.append(shape)
  581. self.storeShapes()
  582. self.selectedShapes = []
  583. self.update()
  584. return deleted_shapes
  585. def deleteShape(self, shape):
  586. if shape in self.selectedShapes:
  587. self.selectedShapes.remove(shape)
  588. if shape in self.shapes:
  589. self.shapes.remove(shape)
  590. self.storeShapes()
  591. self.update()
  592. def duplicateSelectedShapes(self):
  593. if self.selectedShapes:
  594. self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
  595. self.boundedShiftShapes(self.selectedShapesCopy)
  596. self.endMove(copy=True)
  597. return self.selectedShapes
  598. def boundedShiftShapes(self, shapes):
  599. # Try to move in one direction, and if it fails in another.
  600. # Give up if both fail.
  601. point = shapes[0][0]
  602. offset = QtCore.QPointF(2.0, 2.0)
  603. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  604. self.prevPoint = point
  605. if not self.boundedMoveShapes(shapes, point - offset):
  606. self.boundedMoveShapes(shapes, point + offset)
  607. def paintEvent(self, event):
  608. if not self.pixmap:
  609. return super(Canvas, self).paintEvent(event)
  610. p = self._painter
  611. p.begin(self)
  612. p.setRenderHint(QtGui.QPainter.Antialiasing)
  613. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  614. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  615. p.scale(self.scale, self.scale)
  616. p.translate(self.offsetToCenter())
  617. p.drawPixmap(0, 0, self.pixmap)
  618. # draw crosshair
  619. if (
  620. self._crosshair[self._createMode]
  621. and self.drawing()
  622. and self.prevMovePoint
  623. and not self.outOfPixmap(self.prevMovePoint)
  624. ):
  625. p.setPen(QtGui.QColor(0, 0, 0))
  626. p.drawLine(
  627. 0,
  628. int(self.prevMovePoint.y()),
  629. self.width() - 1,
  630. int(self.prevMovePoint.y()),
  631. )
  632. p.drawLine(
  633. int(self.prevMovePoint.x()),
  634. 0,
  635. int(self.prevMovePoint.x()),
  636. self.height() - 1,
  637. )
  638. Shape.scale = self.scale
  639. for shape in self.shapes:
  640. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  641. shape.fill = shape.selected or shape == self.hShape
  642. shape.paint(p)
  643. if self.current:
  644. self.current.paint(p)
  645. assert len(self.line.points) == len(self.line.point_labels)
  646. self.line.paint(p)
  647. if self.selectedShapesCopy:
  648. for s in self.selectedShapesCopy:
  649. s.paint(p)
  650. if (
  651. self.fillDrawing()
  652. and self.createMode == "polygon"
  653. and self.current is not None
  654. and len(self.current.points) >= 2
  655. ):
  656. drawing_shape = self.current.copy()
  657. if drawing_shape.fill_color.getRgb()[3] == 0:
  658. logger.warning(
  659. "fill_drawing=true, but fill_color is transparent,"
  660. " so forcing to be opaque."
  661. )
  662. drawing_shape.fill_color.setAlpha(64)
  663. drawing_shape.addPoint(self.line[1])
  664. drawing_shape.fill = True
  665. drawing_shape.paint(p)
  666. elif self.createMode == "ai_polygon" and self.current is not None:
  667. drawing_shape = self.current.copy()
  668. drawing_shape.addPoint(
  669. point=self.line.points[1],
  670. label=self.line.point_labels[1],
  671. )
  672. points = self._ai_model.predict_polygon_from_points(
  673. points=[[point.x(), point.y()] for point in drawing_shape.points],
  674. point_labels=drawing_shape.point_labels,
  675. )
  676. if len(points) > 2:
  677. drawing_shape.setShapeRefined(
  678. shape_type="polygon",
  679. points=[QtCore.QPointF(point[0], point[1]) for point in points],
  680. point_labels=[1] * len(points),
  681. )
  682. drawing_shape.fill = self.fillDrawing()
  683. drawing_shape.selected = True
  684. drawing_shape.paint(p)
  685. elif self.createMode == "ai_mask" and self.current is not None:
  686. drawing_shape = self.current.copy()
  687. drawing_shape.addPoint(
  688. point=self.line.points[1],
  689. label=self.line.point_labels[1],
  690. )
  691. mask = self._ai_model.predict_mask_from_points(
  692. points=[[point.x(), point.y()] for point in drawing_shape.points],
  693. point_labels=drawing_shape.point_labels,
  694. )
  695. y1, x1, y2, x2 = imgviz.instances.masks_to_bboxes([mask])[0].astype(int)
  696. drawing_shape.setShapeRefined(
  697. shape_type="mask",
  698. points=[QtCore.QPointF(x1, y1), QtCore.QPointF(x2, y2)],
  699. point_labels=[1, 1],
  700. mask=mask[y1 : y2 + 1, x1 : x2 + 1],
  701. )
  702. drawing_shape.selected = True
  703. drawing_shape.paint(p)
  704. p.end()
  705. def transformPos(self, point):
  706. """Convert from widget-logical coordinates to painter-logical ones."""
  707. return point / self.scale - self.offsetToCenter()
  708. def offsetToCenter(self):
  709. s = self.scale
  710. area = super(Canvas, self).size()
  711. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  712. aw, ah = area.width(), area.height()
  713. x = (aw - w) / (2 * s) if aw > w else 0
  714. y = (ah - h) / (2 * s) if ah > h else 0
  715. return QtCore.QPointF(x, y)
  716. def outOfPixmap(self, p):
  717. w, h = self.pixmap.width(), self.pixmap.height()
  718. return not (0 <= p.x() <= w - 1 and 0 <= p.y() <= h - 1)
  719. def finalise(self):
  720. assert self.current
  721. if self.createMode == "ai_polygon":
  722. # convert points to polygon by an AI model
  723. assert self.current.shape_type == "points"
  724. points = self._ai_model.predict_polygon_from_points(
  725. points=[[point.x(), point.y()] for point in self.current.points],
  726. point_labels=self.current.point_labels,
  727. )
  728. self.current.setShapeRefined(
  729. points=[QtCore.QPointF(point[0], point[1]) for point in points],
  730. point_labels=[1] * len(points),
  731. shape_type="polygon",
  732. )
  733. elif self.createMode == "ai_mask":
  734. # convert points to mask by an AI model
  735. assert self.current.shape_type == "points"
  736. mask = self._ai_model.predict_mask_from_points(
  737. points=[[point.x(), point.y()] for point in self.current.points],
  738. point_labels=self.current.point_labels,
  739. )
  740. y1, x1, y2, x2 = imgviz.instances.masks_to_bboxes([mask])[0].astype(int)
  741. self.current.setShapeRefined(
  742. shape_type="mask",
  743. points=[QtCore.QPointF(x1, y1), QtCore.QPointF(x2, y2)],
  744. point_labels=[1, 1],
  745. mask=mask[y1 : y2 + 1, x1 : x2 + 1],
  746. )
  747. self.current.close()
  748. self.shapes.append(self.current)
  749. self.storeShapes()
  750. self.current = None
  751. self.setHiding(False)
  752. self.newShape.emit()
  753. self.update()
  754. def closeEnough(self, p1, p2):
  755. # d = distance(p1 - p2)
  756. # m = (p1-p2).manhattanLength()
  757. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  758. # divide by scale to allow more precision when zoomed in
  759. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  760. def intersectionPoint(self, p1, p2):
  761. # Cycle through each image edge in clockwise fashion,
  762. # and find the one intersecting the current line segment.
  763. # http://paulbourke.net/geometry/lineline2d/
  764. size = self.pixmap.size()
  765. points = [
  766. (0, 0),
  767. (size.width() - 1, 0),
  768. (size.width() - 1, size.height() - 1),
  769. (0, size.height() - 1),
  770. ]
  771. # x1, y1 should be in the pixmap, x2, y2 should be out of the pixmap
  772. x1 = min(max(p1.x(), 0), size.width() - 1)
  773. y1 = min(max(p1.y(), 0), size.height() - 1)
  774. x2, y2 = p2.x(), p2.y()
  775. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  776. x3, y3 = points[i]
  777. x4, y4 = points[(i + 1) % 4]
  778. if (x, y) == (x1, y1):
  779. # Handle cases where previous point is on one of the edges.
  780. if x3 == x4:
  781. return QtCore.QPointF(x3, min(max(0, y2), max(y3, y4)))
  782. else: # y3 == y4
  783. return QtCore.QPointF(min(max(0, x2), max(x3, x4)), y3)
  784. return QtCore.QPointF(x, y)
  785. def intersectingEdges(self, point1, point2, points):
  786. """Find intersecting edges.
  787. For each edge formed by `points', yield the intersection
  788. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  789. Also return the distance of `(x2,y2)' to the middle of the
  790. edge along with its index, so that the one closest can be chosen.
  791. """
  792. (x1, y1) = point1
  793. (x2, y2) = point2
  794. for i in range(4):
  795. x3, y3 = points[i]
  796. x4, y4 = points[(i + 1) % 4]
  797. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  798. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  799. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  800. if denom == 0:
  801. # This covers two cases:
  802. # nua == nub == 0: Coincident
  803. # otherwise: Parallel
  804. continue
  805. ua, ub = nua / denom, nub / denom
  806. if 0 <= ua <= 1 and 0 <= ub <= 1:
  807. x = x1 + ua * (x2 - x1)
  808. y = y1 + ua * (y2 - y1)
  809. m = QtCore.QPointF((x3 + x4) / 2, (y3 + y4) / 2)
  810. d = labelme.utils.distance(m - QtCore.QPointF(x2, y2))
  811. yield d, i, (x, y)
  812. # These two, along with a call to adjustSize are required for the
  813. # scroll area.
  814. def sizeHint(self):
  815. return self.minimumSizeHint()
  816. def minimumSizeHint(self):
  817. if self.pixmap:
  818. return self.scale * self.pixmap.size()
  819. return super(Canvas, self).minimumSizeHint()
  820. def wheelEvent(self, ev):
  821. if QT5:
  822. mods = ev.modifiers()
  823. delta = ev.angleDelta()
  824. if QtCore.Qt.ControlModifier == int(mods):
  825. # with Ctrl/Command key
  826. # zoom
  827. self.zoomRequest.emit(delta.y(), ev.pos())
  828. else:
  829. # scroll
  830. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  831. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  832. else:
  833. if ev.orientation() == QtCore.Qt.Vertical:
  834. mods = ev.modifiers()
  835. if QtCore.Qt.ControlModifier == int(mods):
  836. # with Ctrl/Command key
  837. self.zoomRequest.emit(ev.delta(), ev.pos())
  838. else:
  839. self.scrollRequest.emit(
  840. ev.delta(),
  841. QtCore.Qt.Horizontal
  842. if (QtCore.Qt.ShiftModifier == int(mods))
  843. else QtCore.Qt.Vertical,
  844. )
  845. else:
  846. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  847. ev.accept()
  848. def moveByKeyboard(self, offset):
  849. if self.selectedShapes:
  850. self.boundedMoveShapes(self.selectedShapes, self.prevPoint + offset)
  851. self.repaint()
  852. self.movingShape = True
  853. def keyPressEvent(self, ev):
  854. modifiers = ev.modifiers()
  855. key = ev.key()
  856. if self.drawing():
  857. if key == QtCore.Qt.Key_Escape and self.current:
  858. self.current = None
  859. self.drawingPolygon.emit(False)
  860. self.update()
  861. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  862. self.finalise()
  863. elif modifiers == QtCore.Qt.AltModifier:
  864. self.snapping = False
  865. elif self.editing():
  866. if key == QtCore.Qt.Key_Up:
  867. self.moveByKeyboard(QtCore.QPointF(0.0, -MOVE_SPEED))
  868. elif key == QtCore.Qt.Key_Down:
  869. self.moveByKeyboard(QtCore.QPointF(0.0, MOVE_SPEED))
  870. elif key == QtCore.Qt.Key_Left:
  871. self.moveByKeyboard(QtCore.QPointF(-MOVE_SPEED, 0.0))
  872. elif key == QtCore.Qt.Key_Right:
  873. self.moveByKeyboard(QtCore.QPointF(MOVE_SPEED, 0.0))
  874. def keyReleaseEvent(self, ev):
  875. modifiers = ev.modifiers()
  876. if self.drawing():
  877. if int(modifiers) == 0:
  878. self.snapping = True
  879. elif self.editing():
  880. if self.movingShape and self.selectedShapes:
  881. index = self.shapes.index(self.selectedShapes[0])
  882. if self.shapesBackups[-1][index].points != self.shapes[index].points:
  883. self.storeShapes()
  884. self.shapeMoved.emit()
  885. self.movingShape = False
  886. def setLastLabel(self, text, flags):
  887. assert text
  888. self.shapes[-1].label = text
  889. self.shapes[-1].flags = flags
  890. self.shapesBackups.pop()
  891. self.storeShapes()
  892. return self.shapes[-1]
  893. def undoLastLine(self):
  894. assert self.shapes
  895. self.current = self.shapes.pop()
  896. self.current.setOpen()
  897. self.current.restoreShapeRaw()
  898. if self.createMode in ["polygon", "linestrip"]:
  899. self.line.points = [self.current[-1], self.current[0]]
  900. elif self.createMode in ["rectangle", "line", "circle"]:
  901. self.current.points = self.current.points[0:1]
  902. elif self.createMode == "point":
  903. self.current = None
  904. self.drawingPolygon.emit(True)
  905. def undoLastPoint(self):
  906. if not self.current or self.current.isClosed():
  907. return
  908. self.current.popPoint()
  909. if len(self.current) > 0:
  910. self.line[0] = self.current[-1]
  911. else:
  912. self.current = None
  913. self.drawingPolygon.emit(False)
  914. self.update()
  915. def loadPixmap(self, pixmap, clear_shapes=True):
  916. self.pixmap = pixmap
  917. if self._ai_model:
  918. self._ai_model.set_image(
  919. image=labelme.utils.img_qt_to_arr(self.pixmap.toImage())
  920. )
  921. if clear_shapes:
  922. self.shapes = []
  923. self.update()
  924. def loadShapes(self, shapes, replace=True):
  925. if replace:
  926. self.shapes = list(shapes)
  927. else:
  928. self.shapes.extend(shapes)
  929. self.storeShapes()
  930. self.current = None
  931. self.hShape = None
  932. self.hVertex = None
  933. self.hEdge = None
  934. self.update()
  935. def setShapeVisible(self, shape, value):
  936. self.visible[shape] = value
  937. self.update()
  938. def overrideCursor(self, cursor):
  939. self.restoreCursor()
  940. self._cursor = cursor
  941. QtWidgets.QApplication.setOverrideCursor(cursor)
  942. def restoreCursor(self):
  943. QtWidgets.QApplication.restoreOverrideCursor()
  944. def resetState(self):
  945. self.restoreCursor()
  946. self.pixmap = None
  947. self.shapesBackups = []
  948. self.update()