app.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. import argparse
  2. import functools
  3. import os.path
  4. import subprocess
  5. import sys
  6. import warnings
  7. from qtpy import QT_VERSION
  8. from qtpy import QtCore
  9. from qtpy.QtCore import Qt
  10. from qtpy import QtGui
  11. from qtpy import QtWidgets
  12. import yaml
  13. QT5 = QT_VERSION[0] == '5'
  14. from labelme.canvas import Canvas
  15. from labelme.colorDialog import ColorDialog
  16. from labelme.config import default_config
  17. from labelme.labelDialog import LabelDialog
  18. from labelme.labelFile import LabelFile
  19. from labelme.labelFile import LabelFileError
  20. from labelme.lib import addActions
  21. from labelme.lib import fmtShortcut
  22. from labelme.lib import newAction
  23. from labelme.lib import newIcon
  24. from labelme.lib import struct
  25. from labelme.shape import DEFAULT_FILL_COLOR
  26. from labelme.shape import DEFAULT_LINE_COLOR
  27. from labelme.shape import Shape
  28. from labelme.toolBar import ToolBar
  29. from labelme.zoomWidget import ZoomWidget
  30. __appname__ = 'labelme'
  31. # FIXME
  32. # - [medium] Set max zoom value to something big enough for FitWidth/Window
  33. # TODO(unknown):
  34. # - [high] Automatically add file suffix when saving.
  35. # - [high] Add polygon movement with arrow keys
  36. # - [high] Deselect shape when clicking and already selected(?)
  37. # - [high] Sanitize shortcuts between beginner/advanced mode.
  38. # - [medium] Zoom should keep the image centered.
  39. # - [medium] Add undo button for vertex addition.
  40. # - [low,maybe] Open images with drag & drop.
  41. # - [low,maybe] Preview images on file dialogs.
  42. # - [low,maybe] Sortable label list.
  43. # - Zoom is too "steppy".
  44. # Utility functions and classes.
  45. class WindowMixin(object):
  46. def menu(self, title, actions=None):
  47. menu = self.menuBar().addMenu(title)
  48. if actions:
  49. addActions(menu, actions)
  50. return menu
  51. def toolbar(self, title, actions=None):
  52. toolbar = ToolBar(title)
  53. toolbar.setObjectName('%sToolBar' % title)
  54. # toolbar.setOrientation(Qt.Vertical)
  55. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  56. if actions:
  57. addActions(toolbar, actions)
  58. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  59. return toolbar
  60. class EscapableQListWidget(QtWidgets.QListWidget):
  61. def keyPressEvent(self, event):
  62. if event.key() == Qt.Key_Escape:
  63. self.clearSelection()
  64. class LabelQListWidget(QtWidgets.QListWidget):
  65. def __init__(self, *args, **kwargs):
  66. super(LabelQListWidget, self).__init__(*args, **kwargs)
  67. self.canvas = None
  68. self.itemsToShapes = []
  69. def get_shape_from_item(self, item):
  70. for index, (item_, shape) in enumerate(self.itemsToShapes):
  71. if item_ is item:
  72. return shape
  73. def get_item_from_shape(self, shape):
  74. for index, (item, shape_) in enumerate(self.itemsToShapes):
  75. if shape_ is shape:
  76. return item
  77. def clear(self):
  78. super(LabelQListWidget, self).clear()
  79. self.itemsToShapes = []
  80. def setParent(self, parent):
  81. self.parent = parent
  82. def dropEvent(self, event):
  83. shapes = self.shapes
  84. super(LabelQListWidget, self).dropEvent(event)
  85. if self.shapes == shapes:
  86. return
  87. if self.canvas is None:
  88. raise RuntimeError('self.canvas must be set beforehand.')
  89. self.parent.setDirty()
  90. self.canvas.shapes = self.shapes
  91. @property
  92. def shapes(self):
  93. shapes = []
  94. for i in range(self.count()):
  95. item = self.item(i)
  96. shape = self.get_shape_from_item(item)
  97. shapes.append(shape)
  98. return shapes
  99. class MainWindow(QtWidgets.QMainWindow, WindowMixin):
  100. FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = 0, 1, 2
  101. def __init__(self, filename=None, output=None, store_data=True,
  102. labels=None, sort_labels=True):
  103. super(MainWindow, self).__init__()
  104. self.setWindowTitle(__appname__)
  105. # Whether we need to save or not.
  106. self.dirty = False
  107. self._noSelectionSlot = False
  108. self.screencastViewer = "firefox"
  109. self.screencast = "screencast.ogv"
  110. # Main widgets and related state.
  111. self.labelDialog = LabelDialog(parent=self, labels=labels,
  112. sort_labels=sort_labels)
  113. self.labelList = LabelQListWidget()
  114. self.lastOpenDir = None
  115. self.labelList.itemActivated.connect(self.labelSelectionChanged)
  116. self.labelList.itemSelectionChanged.connect(self.labelSelectionChanged)
  117. self.labelList.itemDoubleClicked.connect(self.editLabel)
  118. # Connect to itemChanged to detect checkbox changes.
  119. self.labelList.itemChanged.connect(self.labelItemChanged)
  120. self.labelList.setDragDropMode(
  121. QtWidgets.QAbstractItemView.InternalMove)
  122. self.labelList.setParent(self)
  123. listLayout = QtWidgets.QVBoxLayout()
  124. listLayout.setContentsMargins(0, 0, 0, 0)
  125. self.editButton = QtWidgets.QToolButton()
  126. self.editButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
  127. listLayout.addWidget(self.editButton) # 0, Qt.AlignCenter)
  128. listLayout.addWidget(self.labelList)
  129. self.labelListContainer = QtWidgets.QWidget()
  130. self.labelListContainer.setLayout(listLayout)
  131. self.uniqLabelList = EscapableQListWidget()
  132. self.uniqLabelList.setToolTip(
  133. "Select label to start annotating for it. "
  134. "Press 'Esc' to deselect.")
  135. if labels:
  136. self.uniqLabelList.addItems(labels)
  137. self.uniqLabelList.sortItems()
  138. self.labelsdock = QtWidgets.QDockWidget(u'Label List', self)
  139. self.labelsdock.setObjectName(u'Label List')
  140. self.labelsdock.setWidget(self.uniqLabelList)
  141. self.dock = QtWidgets.QDockWidget('Polygon Labels', self)
  142. self.dock.setObjectName('Labels')
  143. self.dock.setWidget(self.labelListContainer)
  144. self.fileListWidget = QtWidgets.QListWidget()
  145. self.fileListWidget.itemSelectionChanged.connect(
  146. self.fileSelectionChanged)
  147. filelistLayout = QtWidgets.QVBoxLayout()
  148. filelistLayout.setContentsMargins(0, 0, 0, 0)
  149. filelistLayout.addWidget(self.fileListWidget)
  150. fileListContainer = QtWidgets.QWidget()
  151. fileListContainer.setLayout(filelistLayout)
  152. self.filedock = QtWidgets.QDockWidget(u'File List', self)
  153. self.filedock.setObjectName(u'Files')
  154. self.filedock.setWidget(fileListContainer)
  155. self.zoomWidget = ZoomWidget()
  156. self.colorDialog = ColorDialog(parent=self)
  157. self.canvas = self.labelList.canvas = Canvas()
  158. self.canvas.zoomRequest.connect(self.zoomRequest)
  159. scrollArea = QtWidgets.QScrollArea()
  160. scrollArea.setWidget(self.canvas)
  161. scrollArea.setWidgetResizable(True)
  162. self.scrollBars = {
  163. Qt.Vertical: scrollArea.verticalScrollBar(),
  164. Qt.Horizontal: scrollArea.horizontalScrollBar(),
  165. }
  166. self.canvas.scrollRequest.connect(self.scrollRequest)
  167. self.canvas.newShape.connect(self.newShape)
  168. self.canvas.shapeMoved.connect(self.setDirty)
  169. self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
  170. self.canvas.drawingPolygon.connect(self.toggleDrawingSensitive)
  171. self.setCentralWidget(scrollArea)
  172. self.addDockWidget(Qt.RightDockWidgetArea, self.labelsdock)
  173. self.addDockWidget(Qt.RightDockWidgetArea, self.dock)
  174. self.addDockWidget(Qt.RightDockWidgetArea, self.filedock)
  175. self.filedock.setFeatures(QtWidgets.QDockWidget.DockWidgetFloatable)
  176. self.dockFeatures = (QtWidgets.QDockWidget.DockWidgetClosable |
  177. QtWidgets.QDockWidget.DockWidgetFloatable)
  178. self.dock.setFeatures(self.dock.features() ^ self.dockFeatures)
  179. config = self.getConfig()
  180. # Actions
  181. action = functools.partial(newAction, self)
  182. shortcuts = config['shortcuts']
  183. quit = action('&Quit', self.close, shortcuts['quit'], 'quit',
  184. 'Quit application')
  185. open_ = action('&Open', self.openFile, shortcuts['open'], 'open',
  186. 'Open image or label file')
  187. opendir = action('&Open Dir', self.openDirDialog,
  188. shortcuts['open_dir'], 'open', u'Open Dir')
  189. openNextImg = action('&Next Image', self.openNextImg,
  190. shortcuts['open_next'], 'next', u'Open Next')
  191. openPrevImg = action('&Prev Image', self.openPrevImg,
  192. shortcuts['open_prev'], 'prev', u'Open Prev')
  193. save = action('&Save', self.saveFile, shortcuts['save'], 'save',
  194. 'Save labels to file', enabled=False)
  195. saveAs = action('&Save As', self.saveFileAs, shortcuts['save_as'],
  196. 'save-as', 'Save labels to a different file',
  197. enabled=False)
  198. close = action('&Close', self.closeFile, shortcuts['close'], 'close',
  199. 'Close current file')
  200. color1 = action('Polygon &Line Color', self.chooseColor1,
  201. shortcuts['edit_line_color'], 'color_line',
  202. 'Choose polygon line color')
  203. color2 = action('Polygon &Fill Color', self.chooseColor2,
  204. shortcuts['edit_fill_color'], 'color',
  205. 'Choose polygon fill color')
  206. createMode = action('Create\nPolygo&ns', self.setCreateMode,
  207. shortcuts['create_polygon'], 'objects',
  208. 'Start drawing polygons', enabled=True)
  209. editMode = action('&Edit\nPolygons', self.setEditMode,
  210. shortcuts['edit_polygon'], 'edit',
  211. 'Move and edit polygons', enabled=False)
  212. delete = action('Delete\nPolygon', self.deleteSelectedShape,
  213. shortcuts['delete_polygon'], 'cancel',
  214. 'Delete', enabled=False)
  215. copy = action('&Duplicate\nPolygon', self.copySelectedShape,
  216. shortcuts['duplicate_polygon'], 'copy',
  217. 'Create a duplicate of the selected polygon',
  218. enabled=False)
  219. undoLastPoint = action('Undo last point', self.canvas.undoLastPoint,
  220. shortcuts['undo_last_point'], 'undoLastPoint',
  221. 'Undo last drawn point', enabled=False)
  222. hideAll = action('&Hide\nPolygons',
  223. functools.partial(self.togglePolygons, False),
  224. icon='eye', tip='Hide all polygons', enabled=False)
  225. showAll = action('&Show\nPolygons',
  226. functools.partial(self.togglePolygons, True),
  227. icon='eye', tip='Show all polygons', enabled=False)
  228. help = action('&Tutorial', self.tutorial, icon='help',
  229. tip='Show screencast of introductory tutorial')
  230. zoom = QtWidgets.QWidgetAction(self)
  231. zoom.setDefaultWidget(self.zoomWidget)
  232. self.zoomWidget.setWhatsThis(
  233. "Zoom in or out of the image. Also accessible with"
  234. " %s and %s from the canvas." %
  235. (fmtShortcut('%s,%s' % (shortcuts['zoom_in'],
  236. shortcuts['zoom_out'])),
  237. fmtShortcut("Ctrl+Wheel")))
  238. self.zoomWidget.setEnabled(False)
  239. zoomIn = action('Zoom &In', functools.partial(self.addZoom, 10),
  240. shortcuts['zoom_in'], 'zoom-in',
  241. 'Increase zoom level', enabled=False)
  242. zoomOut = action('&Zoom Out', functools.partial(self.addZoom, -10),
  243. shortcuts['zoom_out'], 'zoom-out',
  244. 'Decrease zoom level', enabled=False)
  245. zoomOrg = action('&Original size',
  246. functools.partial(self.setZoom, 100),
  247. shortcuts['zoom_to_original'], 'zoom',
  248. 'Zoom to original size', enabled=False)
  249. fitWindow = action('&Fit Window', self.setFitWindow,
  250. shortcuts['fit_window'], 'fit-window',
  251. 'Zoom follows window size', checkable=True,
  252. enabled=False)
  253. fitWidth = action('Fit &Width', self.setFitWidth,
  254. shortcuts['fit_width'], 'fit-width',
  255. 'Zoom follows window width',
  256. checkable=True, enabled=False)
  257. # Group zoom controls into a list for easier toggling.
  258. zoomActions = (self.zoomWidget, zoomIn, zoomOut, zoomOrg,
  259. fitWindow, fitWidth)
  260. self.zoomMode = self.MANUAL_ZOOM
  261. self.scalers = {
  262. self.FIT_WINDOW: self.scaleFitWindow,
  263. self.FIT_WIDTH: self.scaleFitWidth,
  264. # Set to one to scale to 100% when loading files.
  265. self.MANUAL_ZOOM: lambda: 1,
  266. }
  267. edit = action('&Edit Label', self.editLabel, shortcuts['edit_label'],
  268. 'edit', 'Modify the label of the selected polygon',
  269. enabled=False)
  270. self.editButton.setDefaultAction(edit)
  271. shapeLineColor = action(
  272. 'Shape &Line Color', self.chshapeLineColor, icon='color-line',
  273. tip='Change the line color for this specific shape', enabled=False)
  274. shapeFillColor = action(
  275. 'Shape &Fill Color', self.chshapeFillColor, icon='color',
  276. tip='Change the fill color for this specific shape', enabled=False)
  277. labels = self.dock.toggleViewAction()
  278. labels.setText('Show/Hide Label Panel')
  279. # Lavel list context menu.
  280. labelMenu = QtWidgets.QMenu()
  281. addActions(labelMenu, (edit, delete))
  282. self.labelList.setContextMenuPolicy(Qt.CustomContextMenu)
  283. self.labelList.customContextMenuRequested.connect(
  284. self.popLabelListMenu)
  285. # Store actions for further handling.
  286. self.actions = struct(
  287. save=save, saveAs=saveAs, open=open_, close=close,
  288. lineColor=color1, fillColor=color2,
  289. delete=delete, edit=edit, copy=copy,
  290. undoLastPoint=undoLastPoint,
  291. createMode=createMode, editMode=editMode,
  292. shapeLineColor=shapeLineColor, shapeFillColor=shapeFillColor,
  293. zoom=zoom, zoomIn=zoomIn, zoomOut=zoomOut, zoomOrg=zoomOrg,
  294. fitWindow=fitWindow, fitWidth=fitWidth,
  295. zoomActions=zoomActions,
  296. fileMenuActions=(open_, opendir, save, saveAs, close, quit),
  297. advanced=(),
  298. editMenu=(edit, copy, delete, None, undoLastPoint,
  299. None, color1, color2),
  300. advancedContext=(
  301. createMode, editMode, edit, copy,
  302. delete, shapeLineColor, shapeFillColor,
  303. undoLastPoint,
  304. ),
  305. onLoadActive=(close, createMode, editMode),
  306. onShapesPresent=(saveAs, hideAll, showAll),
  307. )
  308. self.menus = struct(
  309. file=self.menu('&File'),
  310. edit=self.menu('&Edit'),
  311. view=self.menu('&View'),
  312. help=self.menu('&Help'),
  313. recentFiles=QtWidgets.QMenu('Open &Recent'),
  314. labelList=labelMenu,
  315. )
  316. addActions(self.menus.file, (open_, opendir, self.menus.recentFiles,
  317. save, saveAs, close, None, quit))
  318. addActions(self.menus.help, (help,))
  319. addActions(self.menus.view, (
  320. labels, None,
  321. hideAll, showAll, None,
  322. zoomIn, zoomOut, zoomOrg, None,
  323. fitWindow, fitWidth))
  324. self.menus.file.aboutToShow.connect(self.updateFileMenu)
  325. # Custom context menu for the canvas widget:
  326. addActions(self.canvas.menus[0], self.actions.advancedContext)
  327. addActions(self.canvas.menus[1], (
  328. action('&Copy here', self.copyShape),
  329. action('&Move here', self.moveShape)))
  330. self.tools = self.toolbar('Tools')
  331. self.actions.advanced = (
  332. open_, opendir, openNextImg, openPrevImg, save,
  333. None, createMode, copy, delete, editMode, None,
  334. zoomIn, zoom, zoomOut, fitWindow, fitWidth)
  335. self.statusBar().showMessage('%s started.' % __appname__)
  336. self.statusBar().show()
  337. # Application state.
  338. self.image = QtGui.QImage()
  339. self.imagePath = None
  340. self.labeling_once = output is not None
  341. self.output = output
  342. self._store_data = store_data
  343. self.recentFiles = []
  344. self.maxRecent = 7
  345. self.lineColor = None
  346. self.fillColor = None
  347. self.zoom_level = 100
  348. self.fit_window = False
  349. if filename is not None and os.path.isdir(filename):
  350. self.importDirImages(filename)
  351. else:
  352. self.filename = filename
  353. # XXX: Could be completely declarative.
  354. # Restore application settings.
  355. self.settings = QtCore.QSettings('labelme', 'labelme')
  356. # FIXME: QSettings.value can return None on PyQt4
  357. self.recentFiles = self.settings.value('recentFiles', []) or []
  358. size = self.settings.value('window/size', QtCore.QSize(600, 500))
  359. position = self.settings.value('window/position', QtCore.QPoint(0, 0))
  360. self.resize(size)
  361. self.move(position)
  362. # or simply:
  363. # self.restoreGeometry(settings['window/geometry']
  364. self.restoreState(
  365. self.settings.value('window/state', QtCore.QByteArray()))
  366. self.lineColor = QtGui.QColor(
  367. self.settings.value('line/color', Shape.line_color))
  368. self.fillColor = QtGui.QColor(
  369. self.settings.value('fill/color', Shape.fill_color))
  370. Shape.line_color = self.lineColor
  371. Shape.fill_color = self.fillColor
  372. # Populate the File menu dynamically.
  373. self.updateFileMenu()
  374. # Since loading the file may take some time,
  375. # make sure it runs in the background.
  376. if self.filename is not None:
  377. self.queueEvent(functools.partial(self.loadFile, self.filename))
  378. # Callbacks:
  379. self.zoomWidget.valueChanged.connect(self.paintCanvas)
  380. self.populateModeActions()
  381. # self.firstStart = True
  382. # if self.firstStart:
  383. # QWhatsThis.enterWhatsThisMode()
  384. # Support Functions
  385. def getConfig(self):
  386. # shortcuts for actions
  387. home = os.path.expanduser('~')
  388. config_file = os.path.join(home, '.labelmerc')
  389. # default config
  390. config = default_config.copy()
  391. def update_dict(target_dict, new_dict):
  392. for key, value in new_dict.items():
  393. if key not in target_dict:
  394. print('Skipping unexpected key in config: {}'.format(key))
  395. continue
  396. if isinstance(target_dict[key], dict) and \
  397. isinstance(value, dict):
  398. update_dict(target_dict[key], value)
  399. else:
  400. target_dict[key] = value
  401. if os.path.exists(config_file):
  402. user_config = yaml.load(open(config_file)) or {}
  403. update_dict(config, user_config)
  404. # save config
  405. try:
  406. yaml.safe_dump(config, open(config_file, 'w'),
  407. default_flow_style=False)
  408. except Exception:
  409. warnings.warn('Failed to save config: {}'.format(config_file))
  410. return config
  411. def noShapes(self):
  412. return not self.labelList.itemsToShapes
  413. def populateModeActions(self):
  414. tool, menu = self.actions.advanced, self.actions.advancedContext
  415. self.tools.clear()
  416. addActions(self.tools, tool)
  417. self.canvas.menus[0].clear()
  418. addActions(self.canvas.menus[0], menu)
  419. self.menus.edit.clear()
  420. actions = (self.actions.createMode, self.actions.editMode)
  421. addActions(self.menus.edit, actions + self.actions.editMenu)
  422. def setAdvanced(self):
  423. self.tools.clear()
  424. addActions(self.tools, self.actions.advanced)
  425. def setDirty(self):
  426. self.dirty = True
  427. self.actions.save.setEnabled(True)
  428. title = __appname__
  429. if self.filename is not None:
  430. title = '{} - {}*'.format(title, self.filename)
  431. self.setWindowTitle(title)
  432. def setClean(self):
  433. self.dirty = False
  434. self.actions.save.setEnabled(False)
  435. self.actions.createMode.setEnabled(True)
  436. title = __appname__
  437. if self.filename is not None:
  438. title = '{} - {}'.format(title, self.filename)
  439. self.setWindowTitle(title)
  440. def toggleActions(self, value=True):
  441. """Enable/Disable widgets which depend on an opened image."""
  442. for z in self.actions.zoomActions:
  443. z.setEnabled(value)
  444. for action in self.actions.onLoadActive:
  445. action.setEnabled(value)
  446. def queueEvent(self, function):
  447. QtCore.QTimer.singleShot(0, function)
  448. def status(self, message, delay=5000):
  449. self.statusBar().showMessage(message, delay)
  450. def resetState(self):
  451. self.labelList.clear()
  452. self.filename = None
  453. self.imageData = None
  454. self.labelFile = None
  455. self.canvas.resetState()
  456. def currentItem(self):
  457. items = self.labelList.selectedItems()
  458. if items:
  459. return items[0]
  460. return None
  461. def addRecentFile(self, filename):
  462. if filename in self.recentFiles:
  463. self.recentFiles.remove(filename)
  464. elif len(self.recentFiles) >= self.maxRecent:
  465. self.recentFiles.pop()
  466. self.recentFiles.insert(0, filename)
  467. # Callbacks
  468. def tutorial(self):
  469. subprocess.Popen([self.screencastViewer, self.screencast])
  470. def toggleDrawingSensitive(self, drawing=True):
  471. """Toggle drawing sensitive.
  472. In the middle of drawing, toggling between modes should be disabled.
  473. """
  474. self.actions.editMode.setEnabled(not drawing)
  475. self.actions.undoLastPoint.setEnabled(drawing)
  476. def toggleDrawMode(self, edit=True):
  477. self.canvas.setEditing(edit)
  478. self.actions.createMode.setEnabled(edit)
  479. self.actions.editMode.setEnabled(not edit)
  480. def setCreateMode(self):
  481. self.toggleDrawMode(False)
  482. def setEditMode(self):
  483. self.toggleDrawMode(True)
  484. def updateFileMenu(self):
  485. current = self.filename
  486. def exists(filename):
  487. return os.path.exists(str(filename))
  488. menu = self.menus.recentFiles
  489. menu.clear()
  490. files = [f for f in self.recentFiles if f != current and exists(f)]
  491. for i, f in enumerate(files):
  492. icon = newIcon('labels')
  493. action = QtWidgets.QAction(
  494. icon, '&%d %s' % (i + 1, QtCore.QFileInfo(f).fileName()), self)
  495. action.triggered.connect(functools.partial(self.loadRecent, f))
  496. menu.addAction(action)
  497. def popLabelListMenu(self, point):
  498. self.menus.labelList.exec_(self.labelList.mapToGlobal(point))
  499. def editLabel(self, item=None):
  500. if not self.canvas.editing():
  501. return
  502. item = item if item else self.currentItem()
  503. text = self.labelDialog.popUp(item.text())
  504. if text is None:
  505. return
  506. item.setText(text)
  507. self.setDirty()
  508. if not self.uniqLabelList.findItems(text, Qt.MatchExactly):
  509. self.uniqLabelList.addItem(text)
  510. self.uniqLabelList.sortItems()
  511. def fileSelectionChanged(self):
  512. items = self.fileListWidget.selectedItems()
  513. if not items:
  514. return
  515. item = items[0]
  516. if not self.mayContinue():
  517. return
  518. currIndex = self.imageList.index(str(item.text()))
  519. if currIndex < len(self.imageList):
  520. filename = self.imageList[currIndex]
  521. if filename:
  522. self.loadFile(filename)
  523. # React to canvas signals.
  524. def shapeSelectionChanged(self, selected=False):
  525. if self._noSelectionSlot:
  526. self._noSelectionSlot = False
  527. else:
  528. shape = self.canvas.selectedShape
  529. if shape:
  530. item = self.labelList.get_item_from_shape(shape)
  531. item.setSelected(True)
  532. else:
  533. self.labelList.clearSelection()
  534. self.actions.delete.setEnabled(selected)
  535. self.actions.copy.setEnabled(selected)
  536. self.actions.edit.setEnabled(selected)
  537. self.actions.shapeLineColor.setEnabled(selected)
  538. self.actions.shapeFillColor.setEnabled(selected)
  539. def addLabel(self, shape):
  540. item = QtWidgets.QListWidgetItem(shape.label)
  541. item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
  542. item.setCheckState(Qt.Checked)
  543. self.labelList.itemsToShapes.append((item, shape))
  544. self.labelList.addItem(item)
  545. if not self.uniqLabelList.findItems(shape.label, Qt.MatchExactly):
  546. self.uniqLabelList.addItem(shape.label)
  547. self.uniqLabelList.sortItems()
  548. self.labelDialog.addLabelHistory(item.text())
  549. for action in self.actions.onShapesPresent:
  550. action.setEnabled(True)
  551. def remLabel(self, shape):
  552. item = self.labelList.get_item_from_shape(shape)
  553. self.labelList.takeItem(self.labelList.row(item))
  554. def loadLabels(self, shapes):
  555. s = []
  556. for label, points, line_color, fill_color in shapes:
  557. shape = Shape(label=label)
  558. for x, y in points:
  559. shape.addPoint(QtCore.QPointF(x, y))
  560. shape.close()
  561. s.append(shape)
  562. self.addLabel(shape)
  563. if line_color:
  564. shape.line_color = QtGui.QColor(*line_color)
  565. if fill_color:
  566. shape.fill_color = QtGui.QColor(*fill_color)
  567. self.canvas.loadShapes(s)
  568. def saveLabels(self, filename):
  569. lf = LabelFile()
  570. def format_shape(s):
  571. return dict(label=str(s.label),
  572. line_color=s.line_color.getRgb()
  573. if s.line_color != self.lineColor else None,
  574. fill_color=s.fill_color.getRgb()
  575. if s.fill_color != self.fillColor else None,
  576. points=[(p.x(), p.y()) for p in s.points])
  577. shapes = [format_shape(shape) for shape in self.labelList.shapes]
  578. try:
  579. imagePath = os.path.relpath(
  580. self.imagePath, os.path.dirname(filename))
  581. imageData = self.imageData if self._store_data else None
  582. lf.save(filename, shapes, imagePath, imageData,
  583. self.lineColor.getRgb(), self.fillColor.getRgb())
  584. self.labelFile = lf
  585. # disable allows next and previous image to proceed
  586. # self.filename = filename
  587. return True
  588. except LabelFileError as e:
  589. self.errorMessage('Error saving label data', '<b>%s</b>' % e)
  590. return False
  591. def copySelectedShape(self):
  592. self.addLabel(self.canvas.copySelectedShape())
  593. # fix copy and delete
  594. self.shapeSelectionChanged(True)
  595. def labelSelectionChanged(self):
  596. item = self.currentItem()
  597. if item and self.canvas.editing():
  598. self._noSelectionSlot = True
  599. shape = self.labelList.get_shape_from_item(item)
  600. self.canvas.selectShape(shape)
  601. def labelItemChanged(self, item):
  602. shape = self.labelList.get_shape_from_item(item)
  603. label = str(item.text())
  604. if label != shape.label:
  605. shape.label = str(item.text())
  606. self.setDirty()
  607. else: # User probably changed item visibility
  608. self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
  609. # Callback functions:
  610. def newShape(self):
  611. """Pop-up and give focus to the label editor.
  612. position MUST be in global coordinates.
  613. """
  614. items = self.uniqLabelList.selectedItems()
  615. text = None
  616. if items:
  617. text = items[0].text()
  618. text = self.labelDialog.popUp(text)
  619. if text is not None:
  620. self.addLabel(self.canvas.setLastLabel(text))
  621. self.actions.editMode.setEnabled(True)
  622. self.setDirty()
  623. else:
  624. self.canvas.undoLastLine()
  625. def scrollRequest(self, delta, orientation):
  626. units = - delta * 0.1 # natural scroll
  627. bar = self.scrollBars[orientation]
  628. bar.setValue(bar.value() + bar.singleStep() * units)
  629. def setZoom(self, value):
  630. self.actions.fitWidth.setChecked(False)
  631. self.actions.fitWindow.setChecked(False)
  632. self.zoomMode = self.MANUAL_ZOOM
  633. self.zoomWidget.setValue(value)
  634. def addZoom(self, increment=10):
  635. self.setZoom(self.zoomWidget.value() + increment)
  636. def zoomRequest(self, delta, pos):
  637. canvas_width_old = self.canvas.width()
  638. units = delta * 0.1
  639. self.addZoom(units)
  640. canvas_width_new = self.canvas.width()
  641. if canvas_width_old != canvas_width_new:
  642. canvas_scale_factor = canvas_width_new / canvas_width_old
  643. x_shift = round(pos.x() * canvas_scale_factor) - pos.x()
  644. y_shift = round(pos.y() * canvas_scale_factor) - pos.y()
  645. self.scrollBars[Qt.Horizontal].setValue(
  646. self.scrollBars[Qt.Horizontal].value() + x_shift)
  647. self.scrollBars[Qt.Vertical].setValue(
  648. self.scrollBars[Qt.Vertical].value() + y_shift)
  649. def setFitWindow(self, value=True):
  650. if value:
  651. self.actions.fitWidth.setChecked(False)
  652. self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM
  653. self.adjustScale()
  654. def setFitWidth(self, value=True):
  655. if value:
  656. self.actions.fitWindow.setChecked(False)
  657. self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM
  658. self.adjustScale()
  659. def togglePolygons(self, value):
  660. for item, shape in self.labelList.itemsToShapes:
  661. item.setCheckState(Qt.Checked if value else Qt.Unchecked)
  662. def loadFile(self, filename=None):
  663. """Load the specified file, or the last opened file if None."""
  664. self.resetState()
  665. self.canvas.setEnabled(False)
  666. if filename is None:
  667. filename = self.settings.value('filename', '')
  668. filename = str(filename)
  669. if not QtCore.QFile.exists(filename):
  670. self.errorMessage(
  671. 'Error opening file', 'No such file: <b>%s</b>' % filename)
  672. return False
  673. # assumes same name, but json extension
  674. self.status("Loading %s..." % os.path.basename(str(filename)))
  675. label_file = os.path.splitext(filename)[0] + '.json'
  676. if QtCore.QFile.exists(label_file) and \
  677. LabelFile.isLabelFile(label_file):
  678. try:
  679. self.labelFile = LabelFile(label_file)
  680. # FIXME: PyQt4 installed via Anaconda fails to load JPEG
  681. # and JSON encoded images.
  682. # https://github.com/ContinuumIO/anaconda-issues/issues/131
  683. if QtGui.QImage.fromData(self.labelFile.imageData).isNull():
  684. raise LabelFileError(
  685. 'Failed loading image data from label file.\n'
  686. 'Maybe this is a known issue of PyQt4 built on'
  687. ' Anaconda, and may be fixed by installing PyQt5.')
  688. except LabelFileError as e:
  689. self.errorMessage(
  690. 'Error opening file',
  691. "<p><b>%s</b></p>"
  692. "<p>Make sure <i>%s</i> is a valid label file."
  693. % (e, label_file))
  694. self.status("Error reading %s" % label_file)
  695. return False
  696. self.imageData = self.labelFile.imageData
  697. self.imagePath = os.path.join(os.path.dirname(label_file),
  698. self.labelFile.imagePath)
  699. self.lineColor = QtGui.QColor(*self.labelFile.lineColor)
  700. self.fillColor = QtGui.QColor(*self.labelFile.fillColor)
  701. else:
  702. # Load image:
  703. # read data first and store for saving into label file.
  704. self.imageData = read(filename, None)
  705. if self.imageData is not None:
  706. # the filename is image not JSON
  707. self.imagePath = filename
  708. self.labelFile = None
  709. image = QtGui.QImage.fromData(self.imageData)
  710. if image.isNull():
  711. formats = ['*.{}'.format(fmt.data().decode())
  712. for fmt in QtGui.QImageReader.supportedImageFormats()]
  713. self.errorMessage(
  714. 'Error opening file',
  715. '<p>Make sure <i>{0}</i> is a valid image file.<br/>'
  716. 'Supported image formats: {1}</p>'
  717. .format(filename, ','.join(formats)))
  718. self.status("Error reading %s" % filename)
  719. return False
  720. self.image = image
  721. self.filename = filename
  722. self.canvas.loadPixmap(QtGui.QPixmap.fromImage(image))
  723. if self.labelFile:
  724. self.loadLabels(self.labelFile.shapes)
  725. self.setClean()
  726. self.canvas.setEnabled(True)
  727. self.adjustScale(initial=True)
  728. self.paintCanvas()
  729. self.addRecentFile(self.filename)
  730. self.toggleActions(True)
  731. self.status("Loaded %s" % os.path.basename(str(filename)))
  732. if filename in self.imageList:
  733. self.fileListWidget.setCurrentRow(self.imageList.index(filename))
  734. return True
  735. def resizeEvent(self, event):
  736. if self.canvas and not self.image.isNull()\
  737. and self.zoomMode != self.MANUAL_ZOOM:
  738. self.adjustScale()
  739. super(MainWindow, self).resizeEvent(event)
  740. def paintCanvas(self):
  741. assert not self.image.isNull(), "cannot paint null image"
  742. self.canvas.scale = 0.01 * self.zoomWidget.value()
  743. self.canvas.adjustSize()
  744. self.canvas.update()
  745. def adjustScale(self, initial=False):
  746. value = self.scalers[self.FIT_WINDOW if initial else self.zoomMode]()
  747. self.zoomWidget.setValue(int(100 * value))
  748. def scaleFitWindow(self):
  749. """Figure out the size of the pixmap to fit the main widget."""
  750. e = 2.0 # So that no scrollbars are generated.
  751. w1 = self.centralWidget().width() - e
  752. h1 = self.centralWidget().height() - e
  753. a1 = w1 / h1
  754. # Calculate a new scale value based on the pixmap's aspect ratio.
  755. w2 = self.canvas.pixmap.width() - 0.0
  756. h2 = self.canvas.pixmap.height() - 0.0
  757. a2 = w2 / h2
  758. return w1 / w2 if a2 >= a1 else h1 / h2
  759. def scaleFitWidth(self):
  760. # The epsilon does not seem to work too well here.
  761. w = self.centralWidget().width() - 2.0
  762. return w / self.canvas.pixmap.width()
  763. def closeEvent(self, event):
  764. if not self.mayContinue():
  765. event.ignore()
  766. self.settings.setValue(
  767. 'filename', self.filename if self.filename else '')
  768. self.settings.setValue('window/size', self.size())
  769. self.settings.setValue('window/position', self.pos())
  770. self.settings.setValue('window/state', self.saveState())
  771. self.settings.setValue('line/color', self.lineColor)
  772. self.settings.setValue('fill/color', self.fillColor)
  773. self.settings.setValue('recentFiles', self.recentFiles)
  774. # ask the use for where to save the labels
  775. # self.settings.setValue('window/geometry', self.saveGeometry())
  776. # User Dialogs #
  777. def loadRecent(self, filename):
  778. if self.mayContinue():
  779. self.loadFile(filename)
  780. def openPrevImg(self, _value=False):
  781. if not self.mayContinue():
  782. return
  783. if len(self.imageList) <= 0:
  784. return
  785. if self.filename is None:
  786. return
  787. currIndex = self.imageList.index(self.filename)
  788. if currIndex - 1 >= 0:
  789. filename = self.imageList[currIndex - 1]
  790. if filename:
  791. self.loadFile(filename)
  792. def openNextImg(self, _value=False):
  793. if not self.mayContinue():
  794. return
  795. if len(self.imageList) <= 0:
  796. return
  797. filename = None
  798. if self.filename is None:
  799. filename = self.imageList[0]
  800. else:
  801. currIndex = self.imageList.index(self.filename)
  802. if currIndex + 1 < len(self.imageList):
  803. filename = self.imageList[currIndex + 1]
  804. if filename:
  805. self.loadFile(filename)
  806. def openFile(self, _value=False):
  807. if not self.mayContinue():
  808. return
  809. path = os.path.dirname(str(self.filename)) if self.filename else '.'
  810. formats = ['*.{}'.format(fmt.data().decode())
  811. for fmt in QtGui.QImageReader.supportedImageFormats()]
  812. filters = "Image & Label files (%s)" % ' '.join(
  813. formats + ['*%s' % LabelFile.suffix])
  814. filename = QtWidgets.QFileDialog.getOpenFileName(
  815. self, '%s - Choose Image or Label file' % __appname__,
  816. path, filters)
  817. if QT5:
  818. filename, _ = filename
  819. filename = str(filename)
  820. if filename:
  821. self.loadFile(filename)
  822. def saveFile(self, _value=False):
  823. assert not self.image.isNull(), "cannot save empty image"
  824. if self.hasLabels():
  825. if self.labelFile:
  826. # DL20180323 - overwrite when in directory
  827. self._saveFile(self.labelFile.filename)
  828. elif self.output:
  829. self._saveFile(self.output)
  830. else:
  831. self._saveFile(self.saveFileDialog())
  832. def saveFileAs(self, _value=False):
  833. assert not self.image.isNull(), "cannot save empty image"
  834. if self.hasLabels():
  835. self._saveFile(self.saveFileDialog())
  836. def saveFileDialog(self):
  837. caption = '%s - Choose File' % __appname__
  838. filters = 'Label files (*%s)' % LabelFile.suffix
  839. dlg = QtWidgets.QFileDialog(self, caption, self.currentPath(), filters)
  840. dlg.setDefaultSuffix(LabelFile.suffix[1:])
  841. dlg.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
  842. dlg.setOption(QtWidgets.QFileDialog.DontConfirmOverwrite, False)
  843. dlg.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, False)
  844. basename = os.path.splitext(self.filename)[0]
  845. default_labelfile_name = os.path.join(
  846. self.currentPath(), basename + LabelFile.suffix)
  847. filename = dlg.getSaveFileName(
  848. self, 'Choose File', default_labelfile_name,
  849. 'Label files (*%s)' % LabelFile.suffix)
  850. if QT5:
  851. filename, _ = filename
  852. filename = str(filename)
  853. return filename
  854. def _saveFile(self, filename):
  855. if filename and self.saveLabels(filename):
  856. self.addRecentFile(filename)
  857. self.setClean()
  858. if self.labeling_once:
  859. self.close()
  860. def closeFile(self, _value=False):
  861. if not self.mayContinue():
  862. return
  863. self.resetState()
  864. self.setClean()
  865. self.toggleActions(False)
  866. self.canvas.setEnabled(False)
  867. self.actions.saveAs.setEnabled(False)
  868. # Message Dialogs. #
  869. def hasLabels(self):
  870. if not self.labelList.itemsToShapes:
  871. self.errorMessage(
  872. 'No objects labeled',
  873. 'You must label at least one object to save the file.')
  874. return False
  875. return True
  876. def mayContinue(self):
  877. if not self.dirty:
  878. return True
  879. mb = QtWidgets.QMessageBox
  880. msg = 'Save annotations to "{}" before closing?'.format(self.filename)
  881. answer = mb.question(self,
  882. 'Save annotations?',
  883. msg,
  884. mb.Save | mb.Discard | mb.Cancel,
  885. mb.Save)
  886. if answer == mb.Discard:
  887. return True
  888. elif answer == mb.Save:
  889. self.saveFile()
  890. return True
  891. else: # answer == mb.Cancel
  892. return False
  893. def errorMessage(self, title, message):
  894. return QtWidgets.QMessageBox.critical(
  895. self, title, '<p><b>%s</b></p>%s' % (title, message))
  896. def currentPath(self):
  897. return os.path.dirname(str(self.filename)) if self.filename else '.'
  898. def chooseColor1(self):
  899. color = self.colorDialog.getColor(
  900. self.lineColor, 'Choose line color', default=DEFAULT_LINE_COLOR)
  901. if color:
  902. self.lineColor = color
  903. # Change the color for all shape lines:
  904. Shape.line_color = self.lineColor
  905. self.canvas.update()
  906. self.setDirty()
  907. def chooseColor2(self):
  908. color = self.colorDialog.getColor(
  909. self.fillColor, 'Choose fill color', default=DEFAULT_FILL_COLOR)
  910. if color:
  911. self.fillColor = color
  912. Shape.fill_color = self.fillColor
  913. self.canvas.update()
  914. self.setDirty()
  915. def deleteSelectedShape(self):
  916. yes, no = QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No
  917. msg = 'You are about to permanently delete this polygon, ' \
  918. 'proceed anyway?'
  919. if yes == QtWidgets.QMessageBox.warning(self, 'Attention', msg,
  920. yes | no):
  921. self.remLabel(self.canvas.deleteSelected())
  922. self.setDirty()
  923. if self.noShapes():
  924. for action in self.actions.onShapesPresent:
  925. action.setEnabled(False)
  926. def chshapeLineColor(self):
  927. color = self.colorDialog.getColor(
  928. self.lineColor, 'Choose line color', default=DEFAULT_LINE_COLOR)
  929. if color:
  930. self.canvas.selectedShape.line_color = color
  931. self.canvas.update()
  932. self.setDirty()
  933. def chshapeFillColor(self):
  934. color = self.colorDialog.getColor(
  935. self.fillColor, 'Choose fill color', default=DEFAULT_FILL_COLOR)
  936. if color:
  937. self.canvas.selectedShape.fill_color = color
  938. self.canvas.update()
  939. self.setDirty()
  940. def copyShape(self):
  941. self.canvas.endMove(copy=True)
  942. self.addLabel(self.canvas.selectedShape)
  943. self.setDirty()
  944. def moveShape(self):
  945. self.canvas.endMove(copy=False)
  946. self.setDirty()
  947. def openDirDialog(self, _value=False, dirpath=None):
  948. if not self.mayContinue():
  949. return
  950. defaultOpenDirPath = dirpath if dirpath else '.'
  951. if self.lastOpenDir and os.path.exists(self.lastOpenDir):
  952. defaultOpenDirPath = self.lastOpenDir
  953. else:
  954. defaultOpenDirPath = os.path.dirname(self.filename) \
  955. if self.filename else '.'
  956. targetDirPath = str(QtWidgets.QFileDialog.getExistingDirectory(
  957. self, '%s - Open Directory' % __appname__, defaultOpenDirPath,
  958. QtWidgets.QFileDialog.ShowDirsOnly |
  959. QtWidgets.QFileDialog.DontResolveSymlinks))
  960. self.importDirImages(targetDirPath)
  961. @property
  962. def imageList(self):
  963. lst = []
  964. for i in range(self.fileListWidget.count()):
  965. item = self.fileListWidget.item(i)
  966. lst.append(item.text())
  967. return lst
  968. def importDirImages(self, dirpath):
  969. if not self.mayContinue() or not dirpath:
  970. return
  971. self.lastOpenDir = dirpath
  972. self.filename = None
  973. self.fileListWidget.clear()
  974. for imgPath in self.scanAllImages(dirpath):
  975. item = QtWidgets.QListWidgetItem(imgPath)
  976. self.fileListWidget.addItem(item)
  977. self.openNextImg()
  978. def scanAllImages(self, folderPath):
  979. extensions = ['.%s' % fmt.data().decode("ascii").lower()
  980. for fmt in QtGui.QImageReader.supportedImageFormats()]
  981. images = []
  982. for root, dirs, files in os.walk(folderPath):
  983. for file in files:
  984. if file.lower().endswith(tuple(extensions)):
  985. relativePath = os.path.join(root, file)
  986. images.append(relativePath)
  987. images.sort(key=lambda x: x.lower())
  988. return images
  989. def inverted(color):
  990. return QtGui.QColor(*[255 - v for v in color.getRgb()])
  991. def read(filename, default=None):
  992. try:
  993. with open(filename, 'rb') as f:
  994. return f.read()
  995. except Exception:
  996. return default
  997. def main():
  998. """Standard boilerplate Qt application code."""
  999. parser = argparse.ArgumentParser()
  1000. parser.add_argument('filename', nargs='?', help='image or label filename')
  1001. parser.add_argument('--output', '-O', '-o', help='output label name')
  1002. parser.add_argument('--nodata', dest='store_data', action='store_false',
  1003. help='stop storing image data to JSON file')
  1004. parser.add_argument('--labels',
  1005. help='comma separated list of labels OR file '
  1006. 'containing one label per line')
  1007. parser.add_argument('--nosortlabels', dest='sort_labels',
  1008. action='store_false', help='stop sorting labels')
  1009. args = parser.parse_args()
  1010. if args.labels is not None:
  1011. if os.path.isfile(args.labels):
  1012. args.labels = [l.strip() for l in open(args.labels, 'r')
  1013. if l.strip()]
  1014. else:
  1015. args.labels = [l for l in args.labels.split(',') if l]
  1016. app = QtWidgets.QApplication(sys.argv)
  1017. app.setApplicationName(__appname__)
  1018. app.setWindowIcon(newIcon("icon"))
  1019. win = MainWindow(
  1020. filename=args.filename,
  1021. output=args.output,
  1022. store_data=args.store_data,
  1023. labels=args.labels,
  1024. sort_labels=args.sort_labels,
  1025. )
  1026. win.show()
  1027. win.raise_()
  1028. sys.exit(app.exec_())