app.py 47 KB

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