app.py 45 KB

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