app.py 45 KB

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