app.py 48 KB

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