canvas.py 40 KB

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