app.py 49 KB

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