app.py 49 KB

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