app.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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.loadShapes(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'], '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 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._auto_save = auto_save
  351. self._store_data = store_data
  352. if validate_label not in [None, 'exact', 'instance']:
  353. raise ValueError('Unexpected `validate_label`: {}'
  354. .format(validate_label))
  355. self._validate_label = validate_label
  356. self.recentFiles = []
  357. self.maxRecent = 7
  358. self.lineColor = None
  359. self.fillColor = None
  360. self.otherData = None
  361. self.zoom_level = 100
  362. self.fit_window = False
  363. if filename is not None and os.path.isdir(filename):
  364. self.importDirImages(filename)
  365. else:
  366. self.filename = filename
  367. # XXX: Could be completely declarative.
  368. # Restore application settings.
  369. self.settings = QtCore.QSettings('labelme', 'labelme')
  370. # FIXME: QSettings.value can return None on PyQt4
  371. self.recentFiles = self.settings.value('recentFiles', []) or []
  372. size = self.settings.value('window/size', QtCore.QSize(600, 500))
  373. position = self.settings.value('window/position', QtCore.QPoint(0, 0))
  374. self.resize(size)
  375. self.move(position)
  376. # or simply:
  377. # self.restoreGeometry(settings['window/geometry']
  378. self.restoreState(
  379. self.settings.value('window/state', QtCore.QByteArray()))
  380. self.lineColor = QtGui.QColor(
  381. self.settings.value('line/color', Shape.line_color))
  382. self.fillColor = QtGui.QColor(
  383. self.settings.value('fill/color', Shape.fill_color))
  384. Shape.line_color = self.lineColor
  385. Shape.fill_color = self.fillColor
  386. # Populate the File menu dynamically.
  387. self.updateFileMenu()
  388. # Since loading the file may take some time,
  389. # make sure it runs in the background.
  390. if self.filename is not None:
  391. self.queueEvent(functools.partial(self.loadFile, self.filename))
  392. # Callbacks:
  393. self.zoomWidget.valueChanged.connect(self.paintCanvas)
  394. self.populateModeActions()
  395. # self.firstStart = True
  396. # if self.firstStart:
  397. # QWhatsThis.enterWhatsThisMode()
  398. # Support Functions
  399. def getConfig(self):
  400. # shortcuts for actions
  401. home = os.path.expanduser('~')
  402. config_file = os.path.join(home, '.labelmerc')
  403. # default config
  404. config = default_config.copy()
  405. def update_dict(target_dict, new_dict):
  406. for key, value in new_dict.items():
  407. if key not in target_dict:
  408. logger.warn('Skipping unexpected key in config: {}'
  409. .format(key))
  410. continue
  411. if isinstance(target_dict[key], dict) and \
  412. isinstance(value, dict):
  413. update_dict(target_dict[key], value)
  414. else:
  415. target_dict[key] = value
  416. if os.path.exists(config_file):
  417. user_config = yaml.load(open(config_file)) or {}
  418. update_dict(config, user_config)
  419. # save config
  420. try:
  421. yaml.safe_dump(config, open(config_file, 'w'),
  422. default_flow_style=False)
  423. except Exception:
  424. warnings.warn('Failed to save config: {}'.format(config_file))
  425. return config
  426. def noShapes(self):
  427. return not self.labelList.itemsToShapes
  428. def populateModeActions(self):
  429. tool, menu = self.actions.tool, self.actions.menu
  430. self.tools.clear()
  431. addActions(self.tools, tool)
  432. self.canvas.menus[0].clear()
  433. addActions(self.canvas.menus[0], menu)
  434. self.menus.edit.clear()
  435. actions = (self.actions.createMode, self.actions.editMode)
  436. addActions(self.menus.edit, actions + self.actions.editMenu)
  437. def setDirty(self):
  438. if self._auto_save:
  439. label_file = os.path.splitext(self.imagePath)[0] + '.json'
  440. self.saveLabels(label_file)
  441. return
  442. self.dirty = True
  443. self.actions.save.setEnabled(True)
  444. self.actions.undo.setEnabled(self.canvas.isShapeRestorable)
  445. title = __appname__
  446. if self.filename is not None:
  447. title = '{} - {}*'.format(title, self.filename)
  448. self.setWindowTitle(title)
  449. def setClean(self):
  450. self.dirty = False
  451. self.actions.save.setEnabled(False)
  452. self.actions.createMode.setEnabled(True)
  453. title = __appname__
  454. if self.filename is not None:
  455. title = '{} - {}'.format(title, self.filename)
  456. self.setWindowTitle(title)
  457. def toggleActions(self, value=True):
  458. """Enable/Disable widgets which depend on an opened image."""
  459. for z in self.actions.zoomActions:
  460. z.setEnabled(value)
  461. for action in self.actions.onLoadActive:
  462. action.setEnabled(value)
  463. def queueEvent(self, function):
  464. QtCore.QTimer.singleShot(0, function)
  465. def status(self, message, delay=5000):
  466. self.statusBar().showMessage(message, delay)
  467. def resetState(self):
  468. self.labelList.clear()
  469. self.filename = None
  470. self.imagePath = None
  471. self.imageData = None
  472. self.labelFile = None
  473. self.otherData = None
  474. self.canvas.resetState()
  475. def currentItem(self):
  476. items = self.labelList.selectedItems()
  477. if items:
  478. return items[0]
  479. return None
  480. def addRecentFile(self, filename):
  481. if filename in self.recentFiles:
  482. self.recentFiles.remove(filename)
  483. elif len(self.recentFiles) >= self.maxRecent:
  484. self.recentFiles.pop()
  485. self.recentFiles.insert(0, filename)
  486. # Callbacks
  487. def undoShapeEdit(self):
  488. self.canvas.restoreShape()
  489. self.labelList.clear()
  490. self.uniqLabelList.clear()
  491. self.loadShapes(self.canvas.shapes)
  492. self.actions.undo.setEnabled(self.canvas.isShapeRestorable)
  493. def tutorial(self):
  494. url = 'https://github.com/wkentaro/labelme/tree/master/examples/tutorial' # NOQA
  495. webbrowser.open(url)
  496. def toggleDrawingSensitive(self, drawing=True):
  497. """Toggle drawing sensitive.
  498. In the middle of drawing, toggling between modes should be disabled.
  499. """
  500. self.actions.editMode.setEnabled(not drawing)
  501. self.actions.undoLastPoint.setEnabled(drawing)
  502. self.actions.undo.setEnabled(not drawing)
  503. def toggleDrawMode(self, edit=True):
  504. self.canvas.setEditing(edit)
  505. self.actions.createMode.setEnabled(edit)
  506. self.actions.editMode.setEnabled(not edit)
  507. def setCreateMode(self):
  508. self.toggleDrawMode(False)
  509. def setEditMode(self):
  510. self.toggleDrawMode(True)
  511. def updateFileMenu(self):
  512. current = self.filename
  513. def exists(filename):
  514. return os.path.exists(str(filename))
  515. menu = self.menus.recentFiles
  516. menu.clear()
  517. files = [f for f in self.recentFiles if f != current and exists(f)]
  518. for i, f in enumerate(files):
  519. icon = newIcon('labels')
  520. action = QtWidgets.QAction(
  521. icon, '&%d %s' % (i + 1, QtCore.QFileInfo(f).fileName()), self)
  522. action.triggered.connect(functools.partial(self.loadRecent, f))
  523. menu.addAction(action)
  524. def popLabelListMenu(self, point):
  525. self.menus.labelList.exec_(self.labelList.mapToGlobal(point))
  526. def validateLabel(self, label):
  527. # no validation
  528. if self._validate_label is None:
  529. return True
  530. for i in range(self.uniqLabelList.count()):
  531. l = self.uniqLabelList.item(i).text()
  532. if self._validate_label in ['exact', 'instance']:
  533. if l == label:
  534. return True
  535. if self._validate_label == 'instance':
  536. m = re.match(r'^{}-[0-9]*$'.format(l), label)
  537. if m:
  538. return True
  539. return False
  540. def editLabel(self, item=None):
  541. if not self.canvas.editing():
  542. return
  543. item = item if item else self.currentItem()
  544. text = self.labelDialog.popUp(item.text())
  545. if not self.validateLabel(text):
  546. self.errorMessage('Invalid label',
  547. "Invalid label '{}' with validation type '{}'"
  548. .format(text, self._validate_label))
  549. text = None
  550. if text is None:
  551. return
  552. item.setText(text)
  553. self.setDirty()
  554. if not self.uniqLabelList.findItems(text, Qt.MatchExactly):
  555. self.uniqLabelList.addItem(text)
  556. self.uniqLabelList.sortItems()
  557. def fileSelectionChanged(self):
  558. items = self.fileListWidget.selectedItems()
  559. if not items:
  560. return
  561. item = items[0]
  562. if not self.mayContinue():
  563. return
  564. currIndex = self.imageList.index(str(item.text()))
  565. if currIndex < len(self.imageList):
  566. filename = self.imageList[currIndex]
  567. if filename:
  568. self.loadFile(filename)
  569. # React to canvas signals.
  570. def shapeSelectionChanged(self, selected=False):
  571. if self._noSelectionSlot:
  572. self._noSelectionSlot = False
  573. else:
  574. shape = self.canvas.selectedShape
  575. if shape:
  576. item = self.labelList.get_item_from_shape(shape)
  577. item.setSelected(True)
  578. else:
  579. self.labelList.clearSelection()
  580. self.actions.delete.setEnabled(selected)
  581. self.actions.copy.setEnabled(selected)
  582. self.actions.edit.setEnabled(selected)
  583. self.actions.shapeLineColor.setEnabled(selected)
  584. self.actions.shapeFillColor.setEnabled(selected)
  585. def addLabel(self, shape):
  586. item = QtWidgets.QListWidgetItem(shape.label)
  587. item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
  588. item.setCheckState(Qt.Checked)
  589. self.labelList.itemsToShapes.append((item, shape))
  590. self.labelList.addItem(item)
  591. if not self.uniqLabelList.findItems(shape.label, Qt.MatchExactly):
  592. self.uniqLabelList.addItem(shape.label)
  593. self.uniqLabelList.sortItems()
  594. self.labelDialog.addLabelHistory(item.text())
  595. for action in self.actions.onShapesPresent:
  596. action.setEnabled(True)
  597. def remLabel(self, shape):
  598. item = self.labelList.get_item_from_shape(shape)
  599. self.labelList.takeItem(self.labelList.row(item))
  600. def loadShapes(self, shapes):
  601. for shape in shapes:
  602. self.addLabel(shape)
  603. self.canvas.loadShapes(shapes)
  604. def loadLabels(self, shapes):
  605. s = []
  606. for label, points, line_color, fill_color in shapes:
  607. shape = Shape(label=label)
  608. for x, y in points:
  609. shape.addPoint(QtCore.QPointF(x, y))
  610. shape.close()
  611. s.append(shape)
  612. if line_color:
  613. shape.line_color = QtGui.QColor(*line_color)
  614. if fill_color:
  615. shape.fill_color = QtGui.QColor(*fill_color)
  616. self.loadShapes(s)
  617. def saveLabels(self, filename):
  618. lf = LabelFile()
  619. def format_shape(s):
  620. return dict(label=str(s.label),
  621. line_color=s.line_color.getRgb()
  622. if s.line_color != self.lineColor else None,
  623. fill_color=s.fill_color.getRgb()
  624. if s.fill_color != self.fillColor else None,
  625. points=[(p.x(), p.y()) for p in s.points])
  626. shapes = [format_shape(shape) for shape in self.labelList.shapes]
  627. try:
  628. imagePath = os.path.relpath(
  629. self.imagePath, os.path.dirname(filename))
  630. imageData = self.imageData if self._store_data else None
  631. lf.save(filename, shapes, imagePath, imageData,
  632. self.lineColor.getRgb(), self.fillColor.getRgb(),
  633. self.otherData)
  634. self.labelFile = lf
  635. # disable allows next and previous image to proceed
  636. # self.filename = filename
  637. return True
  638. except LabelFileError as e:
  639. self.errorMessage('Error saving label data', '<b>%s</b>' % e)
  640. return False
  641. def copySelectedShape(self):
  642. self.addLabel(self.canvas.copySelectedShape())
  643. # fix copy and delete
  644. self.shapeSelectionChanged(True)
  645. def labelSelectionChanged(self):
  646. item = self.currentItem()
  647. if item and self.canvas.editing():
  648. self._noSelectionSlot = True
  649. shape = self.labelList.get_shape_from_item(item)
  650. self.canvas.selectShape(shape)
  651. def labelItemChanged(self, item):
  652. shape = self.labelList.get_shape_from_item(item)
  653. label = str(item.text())
  654. if label != shape.label:
  655. shape.label = str(item.text())
  656. self.setDirty()
  657. else: # User probably changed item visibility
  658. self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
  659. # Callback functions:
  660. def newShape(self):
  661. """Pop-up and give focus to the label editor.
  662. position MUST be in global coordinates.
  663. """
  664. items = self.uniqLabelList.selectedItems()
  665. text = None
  666. if items:
  667. text = items[0].text()
  668. text = self.labelDialog.popUp(text)
  669. if not self.validateLabel(text):
  670. self.errorMessage('Invalid label',
  671. "Invalid label '{}' with validation type '{}'"
  672. .format(text, self._validate_label))
  673. text = None
  674. if text is None:
  675. self.canvas.undoLastLine()
  676. self.canvas.shapesBackups.pop()
  677. else:
  678. self.addLabel(self.canvas.setLastLabel(text))
  679. self.actions.editMode.setEnabled(True)
  680. self.actions.undoLastPoint.setEnabled(False)
  681. self.actions.undo.setEnabled(True)
  682. self.setDirty()
  683. def scrollRequest(self, delta, orientation):
  684. units = - delta * 0.1 # natural scroll
  685. bar = self.scrollBars[orientation]
  686. bar.setValue(bar.value() + bar.singleStep() * units)
  687. def setZoom(self, value):
  688. self.actions.fitWidth.setChecked(False)
  689. self.actions.fitWindow.setChecked(False)
  690. self.zoomMode = self.MANUAL_ZOOM
  691. self.zoomWidget.setValue(value)
  692. def addZoom(self, increment=10):
  693. self.setZoom(self.zoomWidget.value() + increment)
  694. def zoomRequest(self, delta, pos):
  695. canvas_width_old = self.canvas.width()
  696. units = delta * 0.1
  697. self.addZoom(units)
  698. canvas_width_new = self.canvas.width()
  699. if canvas_width_old != canvas_width_new:
  700. canvas_scale_factor = canvas_width_new / canvas_width_old
  701. x_shift = round(pos.x() * canvas_scale_factor) - pos.x()
  702. y_shift = round(pos.y() * canvas_scale_factor) - pos.y()
  703. self.scrollBars[Qt.Horizontal].setValue(
  704. self.scrollBars[Qt.Horizontal].value() + x_shift)
  705. self.scrollBars[Qt.Vertical].setValue(
  706. self.scrollBars[Qt.Vertical].value() + y_shift)
  707. def setFitWindow(self, value=True):
  708. if value:
  709. self.actions.fitWidth.setChecked(False)
  710. self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM
  711. self.adjustScale()
  712. def setFitWidth(self, value=True):
  713. if value:
  714. self.actions.fitWindow.setChecked(False)
  715. self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM
  716. self.adjustScale()
  717. def togglePolygons(self, value):
  718. for item, shape in self.labelList.itemsToShapes:
  719. item.setCheckState(Qt.Checked if value else Qt.Unchecked)
  720. def loadFile(self, filename=None):
  721. """Load the specified file, or the last opened file if None."""
  722. # changing fileListWidget loads file
  723. if (filename in self.imageList and
  724. self.fileListWidget.currentRow() !=
  725. self.imageList.index(filename)):
  726. self.fileListWidget.setCurrentRow(self.imageList.index(filename))
  727. return
  728. self.resetState()
  729. self.canvas.setEnabled(False)
  730. if filename is None:
  731. filename = self.settings.value('filename', '')
  732. filename = str(filename)
  733. if not QtCore.QFile.exists(filename):
  734. self.errorMessage(
  735. 'Error opening file', 'No such file: <b>%s</b>' % filename)
  736. return False
  737. # assumes same name, but json extension
  738. self.status("Loading %s..." % os.path.basename(str(filename)))
  739. label_file = os.path.splitext(filename)[0] + '.json'
  740. if QtCore.QFile.exists(label_file) and \
  741. LabelFile.isLabelFile(label_file):
  742. try:
  743. self.labelFile = LabelFile(label_file)
  744. # FIXME: PyQt4 installed via Anaconda fails to load JPEG
  745. # and JSON encoded images.
  746. # https://github.com/ContinuumIO/anaconda-issues/issues/131
  747. if QtGui.QImage.fromData(self.labelFile.imageData).isNull():
  748. raise LabelFileError(
  749. 'Failed loading image data from label file.\n'
  750. 'Maybe this is a known issue of PyQt4 built on'
  751. ' Anaconda, and may be fixed by installing PyQt5.')
  752. except LabelFileError as e:
  753. self.errorMessage(
  754. 'Error opening file',
  755. "<p><b>%s</b></p>"
  756. "<p>Make sure <i>%s</i> is a valid label file."
  757. % (e, label_file))
  758. self.status("Error reading %s" % label_file)
  759. return False
  760. self.imageData = self.labelFile.imageData
  761. self.imagePath = os.path.join(os.path.dirname(label_file),
  762. self.labelFile.imagePath)
  763. self.lineColor = QtGui.QColor(*self.labelFile.lineColor)
  764. self.fillColor = QtGui.QColor(*self.labelFile.fillColor)
  765. self.otherData = self.labelFile.otherData
  766. else:
  767. # Load image:
  768. # read data first and store for saving into label file.
  769. self.imageData = read(filename, None)
  770. if self.imageData is not None:
  771. # the filename is image not JSON
  772. self.imagePath = filename
  773. self.labelFile = None
  774. image = QtGui.QImage.fromData(self.imageData)
  775. if image.isNull():
  776. formats = ['*.{}'.format(fmt.data().decode())
  777. for fmt in QtGui.QImageReader.supportedImageFormats()]
  778. self.errorMessage(
  779. 'Error opening file',
  780. '<p>Make sure <i>{0}</i> is a valid image file.<br/>'
  781. 'Supported image formats: {1}</p>'
  782. .format(filename, ','.join(formats)))
  783. self.status("Error reading %s" % filename)
  784. return False
  785. self.image = image
  786. self.filename = filename
  787. self.canvas.loadPixmap(QtGui.QPixmap.fromImage(image))
  788. if self.labelFile:
  789. self.loadLabels(self.labelFile.shapes)
  790. self.setClean()
  791. self.canvas.setEnabled(True)
  792. self.adjustScale(initial=True)
  793. self.paintCanvas()
  794. self.addRecentFile(self.filename)
  795. self.toggleActions(True)
  796. self.status("Loaded %s" % os.path.basename(str(filename)))
  797. return True
  798. def resizeEvent(self, event):
  799. if self.canvas and not self.image.isNull()\
  800. and self.zoomMode != self.MANUAL_ZOOM:
  801. self.adjustScale()
  802. super(MainWindow, self).resizeEvent(event)
  803. def paintCanvas(self):
  804. assert not self.image.isNull(), "cannot paint null image"
  805. self.canvas.scale = 0.01 * self.zoomWidget.value()
  806. self.canvas.adjustSize()
  807. self.canvas.update()
  808. def adjustScale(self, initial=False):
  809. value = self.scalers[self.FIT_WINDOW if initial else self.zoomMode]()
  810. self.zoomWidget.setValue(int(100 * value))
  811. def scaleFitWindow(self):
  812. """Figure out the size of the pixmap to fit the main widget."""
  813. e = 2.0 # So that no scrollbars are generated.
  814. w1 = self.centralWidget().width() - e
  815. h1 = self.centralWidget().height() - e
  816. a1 = w1 / h1
  817. # Calculate a new scale value based on the pixmap's aspect ratio.
  818. w2 = self.canvas.pixmap.width() - 0.0
  819. h2 = self.canvas.pixmap.height() - 0.0
  820. a2 = w2 / h2
  821. return w1 / w2 if a2 >= a1 else h1 / h2
  822. def scaleFitWidth(self):
  823. # The epsilon does not seem to work too well here.
  824. w = self.centralWidget().width() - 2.0
  825. return w / self.canvas.pixmap.width()
  826. def closeEvent(self, event):
  827. if not self.mayContinue():
  828. event.ignore()
  829. self.settings.setValue(
  830. 'filename', self.filename if self.filename else '')
  831. self.settings.setValue('window/size', self.size())
  832. self.settings.setValue('window/position', self.pos())
  833. self.settings.setValue('window/state', self.saveState())
  834. self.settings.setValue('line/color', self.lineColor)
  835. self.settings.setValue('fill/color', self.fillColor)
  836. self.settings.setValue('recentFiles', self.recentFiles)
  837. # ask the use for where to save the labels
  838. # self.settings.setValue('window/geometry', self.saveGeometry())
  839. # User Dialogs #
  840. def loadRecent(self, filename):
  841. if self.mayContinue():
  842. self.loadFile(filename)
  843. def openPrevImg(self, _value=False):
  844. if not self.mayContinue():
  845. return
  846. if len(self.imageList) <= 0:
  847. return
  848. if self.filename is None:
  849. return
  850. currIndex = self.imageList.index(self.filename)
  851. if currIndex - 1 >= 0:
  852. filename = self.imageList[currIndex - 1]
  853. if filename:
  854. self.loadFile(filename)
  855. def openNextImg(self, _value=False, load=True):
  856. if not self.mayContinue():
  857. return
  858. if len(self.imageList) <= 0:
  859. return
  860. filename = None
  861. if self.filename is None:
  862. filename = self.imageList[0]
  863. else:
  864. currIndex = self.imageList.index(self.filename)
  865. if currIndex + 1 < len(self.imageList):
  866. filename = self.imageList[currIndex + 1]
  867. self.filename = filename
  868. if self.filename and load:
  869. self.loadFile(self.filename)
  870. def openFile(self, _value=False):
  871. if not self.mayContinue():
  872. return
  873. path = os.path.dirname(str(self.filename)) if self.filename else '.'
  874. formats = ['*.{}'.format(fmt.data().decode())
  875. for fmt in QtGui.QImageReader.supportedImageFormats()]
  876. filters = "Image & Label files (%s)" % ' '.join(
  877. formats + ['*%s' % LabelFile.suffix])
  878. filename = QtWidgets.QFileDialog.getOpenFileName(
  879. self, '%s - Choose Image or Label file' % __appname__,
  880. path, filters)
  881. if QT5:
  882. filename, _ = filename
  883. filename = str(filename)
  884. if filename:
  885. self.loadFile(filename)
  886. def saveFile(self, _value=False):
  887. assert not self.image.isNull(), "cannot save empty image"
  888. if self.hasLabels():
  889. if self.labelFile:
  890. # DL20180323 - overwrite when in directory
  891. self._saveFile(self.labelFile.filename)
  892. elif self.output:
  893. self._saveFile(self.output)
  894. else:
  895. self._saveFile(self.saveFileDialog())
  896. def saveFileAs(self, _value=False):
  897. assert not self.image.isNull(), "cannot save empty image"
  898. if self.hasLabels():
  899. self._saveFile(self.saveFileDialog())
  900. def saveFileDialog(self):
  901. caption = '%s - Choose File' % __appname__
  902. filters = 'Label files (*%s)' % LabelFile.suffix
  903. dlg = QtWidgets.QFileDialog(self, caption, self.currentPath(), filters)
  904. dlg.setDefaultSuffix(LabelFile.suffix[1:])
  905. dlg.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
  906. dlg.setOption(QtWidgets.QFileDialog.DontConfirmOverwrite, False)
  907. dlg.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, False)
  908. basename = os.path.splitext(self.filename)[0]
  909. default_labelfile_name = os.path.join(
  910. self.currentPath(), basename + LabelFile.suffix)
  911. filename = dlg.getSaveFileName(
  912. self, 'Choose File', default_labelfile_name,
  913. 'Label files (*%s)' % LabelFile.suffix)
  914. if QT5:
  915. filename, _ = filename
  916. filename = str(filename)
  917. return filename
  918. def _saveFile(self, filename):
  919. if filename and self.saveLabels(filename):
  920. self.addRecentFile(filename)
  921. self.setClean()
  922. if self.labeling_once:
  923. self.close()
  924. def closeFile(self, _value=False):
  925. if not self.mayContinue():
  926. return
  927. self.resetState()
  928. self.setClean()
  929. self.toggleActions(False)
  930. self.canvas.setEnabled(False)
  931. self.actions.saveAs.setEnabled(False)
  932. # Message Dialogs. #
  933. def hasLabels(self):
  934. if not self.labelList.itemsToShapes:
  935. self.errorMessage(
  936. 'No objects labeled',
  937. 'You must label at least one object to save the file.')
  938. return False
  939. return True
  940. def mayContinue(self):
  941. if not self.dirty:
  942. return True
  943. mb = QtWidgets.QMessageBox
  944. msg = 'Save annotations to "{}" before closing?'.format(self.filename)
  945. answer = mb.question(self,
  946. 'Save annotations?',
  947. msg,
  948. mb.Save | mb.Discard | mb.Cancel,
  949. mb.Save)
  950. if answer == mb.Discard:
  951. return True
  952. elif answer == mb.Save:
  953. self.saveFile()
  954. return True
  955. else: # answer == mb.Cancel
  956. return False
  957. def errorMessage(self, title, message):
  958. return QtWidgets.QMessageBox.critical(
  959. self, title, '<p><b>%s</b></p>%s' % (title, message))
  960. def currentPath(self):
  961. return os.path.dirname(str(self.filename)) if self.filename else '.'
  962. def chooseColor1(self):
  963. color = self.colorDialog.getColor(
  964. self.lineColor, 'Choose line color', default=DEFAULT_LINE_COLOR)
  965. if color:
  966. self.lineColor = color
  967. # Change the color for all shape lines:
  968. Shape.line_color = self.lineColor
  969. self.canvas.update()
  970. self.setDirty()
  971. def chooseColor2(self):
  972. color = self.colorDialog.getColor(
  973. self.fillColor, 'Choose fill color', default=DEFAULT_FILL_COLOR)
  974. if color:
  975. self.fillColor = color
  976. Shape.fill_color = self.fillColor
  977. self.canvas.update()
  978. self.setDirty()
  979. def deleteSelectedShape(self):
  980. yes, no = QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No
  981. msg = 'You are about to permanently delete this polygon, ' \
  982. 'proceed anyway?'
  983. if yes == QtWidgets.QMessageBox.warning(self, 'Attention', msg,
  984. yes | no):
  985. self.remLabel(self.canvas.deleteSelected())
  986. self.setDirty()
  987. if self.noShapes():
  988. for action in self.actions.onShapesPresent:
  989. action.setEnabled(False)
  990. def chshapeLineColor(self):
  991. color = self.colorDialog.getColor(
  992. self.lineColor, 'Choose line color', default=DEFAULT_LINE_COLOR)
  993. if color:
  994. self.canvas.selectedShape.line_color = color
  995. self.canvas.update()
  996. self.setDirty()
  997. def chshapeFillColor(self):
  998. color = self.colorDialog.getColor(
  999. self.fillColor, 'Choose fill color', default=DEFAULT_FILL_COLOR)
  1000. if color:
  1001. self.canvas.selectedShape.fill_color = color
  1002. self.canvas.update()
  1003. self.setDirty()
  1004. def copyShape(self):
  1005. self.canvas.endMove(copy=True)
  1006. self.addLabel(self.canvas.selectedShape)
  1007. self.setDirty()
  1008. def moveShape(self):
  1009. self.canvas.endMove(copy=False)
  1010. self.setDirty()
  1011. def openDirDialog(self, _value=False, dirpath=None):
  1012. if not self.mayContinue():
  1013. return
  1014. defaultOpenDirPath = dirpath if dirpath else '.'
  1015. if self.lastOpenDir and os.path.exists(self.lastOpenDir):
  1016. defaultOpenDirPath = self.lastOpenDir
  1017. else:
  1018. defaultOpenDirPath = os.path.dirname(self.filename) \
  1019. if self.filename else '.'
  1020. targetDirPath = str(QtWidgets.QFileDialog.getExistingDirectory(
  1021. self, '%s - Open Directory' % __appname__, defaultOpenDirPath,
  1022. QtWidgets.QFileDialog.ShowDirsOnly |
  1023. QtWidgets.QFileDialog.DontResolveSymlinks))
  1024. self.importDirImages(targetDirPath)
  1025. @property
  1026. def imageList(self):
  1027. lst = []
  1028. for i in range(self.fileListWidget.count()):
  1029. item = self.fileListWidget.item(i)
  1030. lst.append(item.text())
  1031. return lst
  1032. def importDirImages(self, dirpath):
  1033. if not self.mayContinue() or not dirpath:
  1034. return
  1035. self.lastOpenDir = dirpath
  1036. self.filename = None
  1037. self.fileListWidget.clear()
  1038. for imgPath in self.scanAllImages(dirpath):
  1039. item = QtWidgets.QListWidgetItem(imgPath)
  1040. self.fileListWidget.addItem(item)
  1041. self.openNextImg(load=False)
  1042. def scanAllImages(self, folderPath):
  1043. extensions = ['.%s' % fmt.data().decode("ascii").lower()
  1044. for fmt in QtGui.QImageReader.supportedImageFormats()]
  1045. images = []
  1046. for root, dirs, files in os.walk(folderPath):
  1047. for file in files:
  1048. if file.lower().endswith(tuple(extensions)):
  1049. relativePath = os.path.join(root, file)
  1050. images.append(relativePath)
  1051. images.sort(key=lambda x: x.lower())
  1052. return images
  1053. def inverted(color):
  1054. return QtGui.QColor(*[255 - v for v in color.getRgb()])
  1055. def read(filename, default=None):
  1056. try:
  1057. with open(filename, 'rb') as f:
  1058. return f.read()
  1059. except Exception:
  1060. return default
  1061. def main():
  1062. """Standard boilerplate Qt application code."""
  1063. parser = argparse.ArgumentParser()
  1064. parser.add_argument('filename', nargs='?', help='image or label filename')
  1065. parser.add_argument('--output', '-O', '-o', help='output label name')
  1066. parser.add_argument('--nodata', dest='store_data', action='store_false',
  1067. help='stop storing image data to JSON file')
  1068. parser.add_argument('--autosave', action='store_true', help='auto save')
  1069. parser.add_argument('--labels',
  1070. help='comma separated list of labels OR file '
  1071. 'containing one label per line')
  1072. parser.add_argument('--nosortlabels', dest='sort_labels',
  1073. action='store_false', help='stop sorting labels')
  1074. parser.add_argument('--validatelabel', choices=['exact', 'instance'],
  1075. help='label validation types')
  1076. args = parser.parse_args()
  1077. if args.labels is None:
  1078. if args.validatelabel is not None:
  1079. logger.error('--labels must be specified with --validatelabel')
  1080. sys.exit(1)
  1081. else:
  1082. if os.path.isfile(args.labels):
  1083. args.labels = [l.strip() for l in open(args.labels, 'r')
  1084. if l.strip()]
  1085. else:
  1086. args.labels = [l for l in args.labels.split(',') if l]
  1087. app = QtWidgets.QApplication(sys.argv)
  1088. app.setApplicationName(__appname__)
  1089. app.setWindowIcon(newIcon("icon"))
  1090. win = MainWindow(
  1091. filename=args.filename,
  1092. output=args.output,
  1093. store_data=args.store_data,
  1094. labels=args.labels,
  1095. sort_labels=args.sort_labels,
  1096. auto_save=args.autosave,
  1097. validate_label=args.validatelabel,
  1098. )
  1099. win.show()
  1100. win.raise_()
  1101. sys.exit(app.exec_())