def _chooseDirectory(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = preferences.get("DataSelection", "recent stack directory") if mostRecentStackDirectory is not None: defaultDirectory = os.path.split(mostRecentStackDirectory)[0] else: defaultDirectory = os.path.expanduser("~") options = QFileDialog.Options(QFileDialog.ShowDirsOnly) if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog # Launch the "Open File" dialog directory = QFileDialog.getExistingDirectory(self, "Image Stack Directory", defaultDirectory, options=options) if not directory: # User cancelled return preferences.set("DataSelection", "recent stack directory", directory) self.directoryEdit.setText(directory) try: globstring = self._getGlobString(directory) self.patternEdit.setText(globstring) self._applyPattern() except StackFileSelectionWidget.DetermineStackError as e: QMessageBox.warning(self, "Invalid selection", str(e))
def addModelClicked(self): """ When AddModel button is clicked. """ # open dialog in recent model folder if possible folder = preferences.get("DataSelection", "recent model") if folder is None: folder = os.path.expanduser("~") # get folder from user filename = self.getModelToOpen(self, folder) if filename: projectManager = self.parentApplet._StandardApplet__workflow._shell.projectManager # save whole project (specifically important here: the labels) if not projectManager.currentProjectIsReadOnly: projectManager.saveProject() with open(filename, "rb") as modelFile: modelBytes = modelFile.read() self._uploadModel(modelBytes) preferences.set("DataSelection", "recent model", filename) self.parentApplet.appletStateUpdateRequested()
def _exportAllObjectMeshes(self): """ Export all objects in the project as separate .obj files, stored to a user-specified directory. """ mst = self.topLevelOperatorView.MST.value if not list(mst.object_lut.keys()): QMessageBox.critical( self, "Can't Export", "You have no saved objets, so there are no meshes to export.") return recent_dir = preferences.get("carving", "recent export mesh directory") if recent_dir is None: defaultPath = os.path.join(os.path.expanduser("~")) else: defaultPath = os.path.join(recent_dir) export_dir = QFileDialog.getExistingDirectory( self, "Select export directory for mesh files", defaultPath) if not export_dir: return export_dir = str(export_dir) preferences.set("carving", "recent export mesh directory", export_dir) # Get the list of all object names object_names = [] obj_filepaths = [] for object_name in list(mst.object_lut.keys()): object_names.append(object_name) obj_filepaths.append( os.path.join(export_dir, "{}.obj".format(object_name))) if object_names: self._exportMeshes(object_names, obj_filepaths)
def store_to_preferences(self): """ Immediately serialize the current set of shortcuts to the preferences file. """ # Auto-save after we're done setting prefs # Just save the entire shortcut dict as a single pickle value reversemap = self.get_keyseq_reversemap(self._keyseq_target_actions) preferences.set(self.PreferencesGroup, "all_shortcuts", reversemap)
def store_to_preferences(self) -> None: shortcuts = [{ "group": group, "name": name, "keyseq": keyseq } for keyseq, targets in self._keyseq_target_actions.items() for group, name in targets] preferences.set(self.PreferencesGroup, self.PreferencesSetting, shortcuts)
def addDvidVolume(self, roleIndex, laneIndex): group = "DataSelection" recent_hosts_key = "Recent DVID Hosts" recent_hosts = preferences.get(group, recent_hosts_key) if not recent_hosts: recent_hosts = ["localhost:8000"] recent_hosts = [ h for h in recent_hosts if h ] # There used to be a bug where empty strings could be saved. Filter those out. recent_nodes_key = "Recent DVID Nodes" recent_nodes = preferences.get(group, recent_nodes_key) or {} from .dvidDataSelectionBrowser import DvidDataSelectionBrowser browser = DvidDataSelectionBrowser(recent_hosts, recent_nodes, parent=self) if browser.exec_() == DvidDataSelectionBrowser.Rejected: return if None in browser.get_selection(): QMessageBox.critical("Couldn't use your selection.") return rois = None hostname, repo_uuid, volume_name, node_uuid, typename = browser.get_selection( ) dvid_url = f"http://{hostname}/api/node/{node_uuid}/{volume_name}" subvolume_roi = browser.get_subvolume_roi() # Relocate host to top of 'recent' list, and limit list to 10 items. try: i = recent_hosts.index(hostname) del recent_hosts[i] except ValueError: pass finally: recent_hosts.insert(0, hostname) recent_hosts = recent_hosts[:10] # Save pref preferences.set(group, recent_hosts_key, recent_hosts) recent_nodes[hostname] = node_uuid preferences.set(group, recent_nodes_key, recent_nodes) self.addLanes( [UrlDatasetInfo(url=dvid_url, subvolume_roi=subvolume_roi)], roleIndex)
def getSelectedPaths(self) -> List[Path]: if not super().exec_(): return [] preferences.set(self.preferences_group, self.preferences_setting, Path(self.selectedFiles()[0]).as_posix()) filePaths = [] for selected_file in self.selectedFiles(): path = Path(selected_file) if path.name.lower() == "attributes.json" and any( p.suffix.lower() == ".n5" for p in path.parents): # For the n5 extension the attributes.json file has to be selected in the file dialog. # However we need just the *.n5 directory-file. filePaths.append(path.parent) else: filePaths.append(path) return filePaths
def _loadModelButtonClicked(self): """ When Load Model button is clicked. """ mostRecentModelFile = preferences.get("DataSelection", "recent neural net") if mostRecentModelFile is not None: defaultDirectory = os.path.split(mostRecentModelFile)[0] else: defaultDirectory = os.path.expanduser("~") fileName = self.getModelFileNameToOpen(self, defaultDirectory) if fileName is not None: self._setClassifierModel(fileName) preferences.set("DataSelection", "recent neural net", fileName) self._setModelGuiVisible(True)
def _onContextMenuExportMesh(self, _name): """ Export a single object mesh to a user-specified filename. """ recent_dir = preferences.get("carving", "recent export mesh directory") if recent_dir is None: defaultPath = os.path.join(os.path.expanduser("~"), "{}obj".format(_name)) else: defaultPath = os.path.join(recent_dir, "{}.obj".format(_name)) filepath, _filter = QFileDialog.getSaveFileName( self, "Save meshes for object '{}'".format(_name), defaultPath, "OBJ Files (*.obj)") if not filepath: return obj_filepath = str(filepath) preferences.set("carving", "recent export mesh directory", os.path.split(obj_filepath)[0]) self._exportMeshes([_name], [obj_filepath])
def prompt_export_settings_and_export_layer(layer: Layer, parent_widget=None) -> None: """ Prompt the user for layer export settings, and perform the layer export. """ opExport = get_export_operator(layer) export_dir = preferences.get("layer", "export-dir", default=os.path.expanduser("~")) opExport.OutputFilenameFormat.setValue(os.path.join(export_dir, layer.name)) # Use this dialog to populate the operator's slot settings settingsDlg = DataExportOptionsDlg(parent_widget, opExport) # If user didn't cancel, run the export now. if settingsDlg.exec_() == DataExportOptionsDlg.Accepted: export_dir = PathComponents(opExport.ExportPath.value).externalDirectory preferences.set("layer", "export-dir", export_dir) helper = ExportHelper(parent_widget) helper.run(opExport) # Clean up our temporary operators opExport.cleanUp()
def _setTileWidth(self, value): key, _ = self._getTileWidthConfigKeyDefault() preferences.set("ImageScene2D", key, value) self._updateTileWidth()
def accept(self): preferences.set("WYSIWYG", "export directory", str(self.directoryEdit.text())) super(WysiwygExportOptionsDlg, self).accept()
def saveSize(): size = self.featureDlg.size() s = (size.width(), size.height()) preferences.set("featureSelection", "dialog size", s)
def _selectFiles(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = preferences.get("DataSelection", "recent stack directory") if mostRecentStackDirectory is not None: defaultDirectory = os.path.split(mostRecentStackDirectory)[0] else: defaultDirectory = os.path.expanduser("~") options = QFileDialog.Options(QFileDialog.ShowDirsOnly) if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog h5exts = [x.lstrip(".") for x in OpStreamingH5N5SequenceReaderM.H5EXTS] # Launch the "Open File" dialog extensions = vigra.impex.listExtensions().split() extensions.extend(h5exts) extensions.extend(OpInputDataReader.n5Selection) filt = "Image files (" + " ".join("*." + x for x in extensions) + ")" options = QFileDialog.Options() if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog fileNames, _filter = QFileDialog.getOpenFileNames( self, "Select Images for Stack", defaultDirectory, filt, options=options) # For the n5 extension, the attributes.json file has to be selected in the file dialog. # However we need just the n5 directory-file. for i in range(len(fileNames)): if os.path.join("n5", "attributes.json") in fileNames[i]: fileNames[i] = fileNames[i].replace( os.path.sep + "attributes.json", "") msg = "" if len(fileNames) == 0: return pathComponents = PathComponents(fileNames[0]) if ((len(fileNames) == 1) and pathComponents.extension not in OpStreamingH5N5SequenceReaderM.H5EXTS + OpStreamingH5N5SequenceReaderM.N5EXTS): msg += "Cannot create stack: You only chose a single file. " msg += "If your stack is contained in a single file (e.g. a multi-page tiff) " msg += 'please use the "Add File" button.' QMessageBox.warning(self, "Invalid selection", msg) return None directory = pathComponents.externalPath preferences.set("DataSelection", "recent stack directory", directory) if (pathComponents.extension in OpStreamingH5N5SequenceReaderM.H5EXTS or pathComponents.extension in OpStreamingH5N5SequenceReaderM.N5EXTS): if len(fileNames) == 1: # open the dialog for globbing: file_name = fileNames[0] dlg = H5N5StackingDlg( parent=self, list_of_paths=self._findInternalStacks(file_name)) if dlg.exec_() == QDialog.Accepted: globstring = "{}/{}".format(file_name, dlg.get_globstring()) self.patternEdit.setText(globstring) self._applyPattern() return None else: return None else: # check for internal paths internal_paths = self._h5N5FindCommonInternal(fileNames) if len(internal_paths) == 0: msg += "Could not find a unique common internal path in" msg += directory + "\n" QMessageBox.warning(self, "Invalid selection", msg) return None elif len(internal_paths) == 1: fileNames = [ "{}/{}".format(fn, internal_paths[0]) for fn in fileNames ] else: # Ask the user which dataset to choose dlg = SubvolumeSelectionDlg(internal_paths, self) if dlg.exec_() == QDialog.Accepted: selected_index = dlg.combo.currentIndex() selected_dataset = str(internal_paths[selected_index]) fileNames = [ "{}/{}".format(fn, selected_dataset) for fn in fileNames ] else: msg = "No valid internal path selected." QMessageBox.warning(self, "Invalid selection", msg) return None self._updateFileList(fileNames)
def setTileWidth(self, tileWidth): self._tileWidth = tileWidth preferences.set("ImageScene2D", "tileWidth", tileWidth)