app.py 47 KB

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