canvas.py 41 KB

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