app.py 47 KB

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