def exportRelabeling(self): # Ask for the export path exportPath = QFileDialog.getSaveFileName( self, "Save supervoxel relabeling", "", "Hdf5 Files (*.h5 *.hdf5)", options=QFileDialog.Options(QFileDialog.DontUseNativeDialog)) if exportPath.isNull(): return def handleProgress(progress): # TODO: Hook this up to the progress bar logger.info("Export progress: {}%".format(progress)) op = self.topLevelOperatorView req = op.exportFinalSupervoxels(encode_from_qstring(exportPath), "zyx", handleProgress) self._drawer.exportButton.setEnabled(False) def handleFinish(*args): self._drawer.exportButton.setEnabled(True) req.notify_finished(handleFinish) req.notify_failed(handleFinish)
def _chooseDirectory(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = PreferencesManager().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 directory.isNull(): # User cancelled return directory = encode_from_qstring(directory) PreferencesManager().set('DataSelection', 'recent stack directory', directory) self.directoryEdit.setText(decode_to_qstring(directory)) try: globstring = self._getGlobString(directory) except StackFileSelectionWidget.DetermineStackError, e: QMessageBox.warning(self, "Invalid selection", str(e))
def repairFile(self, path, filt=None): """get new path to lost file""" from PyQt4.QtGui import QFileDialog, QMessageBox from volumina.utility import encode_from_qstring text = "The file at {} could not be found any more. Do you want to search for it at another directory?".format( path) logger.info(text) c = QMessageBox.critical(None, "update external data", text, QMessageBox.Ok | QMessageBox.Cancel) if c == QMessageBox.Cancel: raise RuntimeError("Could not find external data: " + path) options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog fileName = QFileDialog.getOpenFileName(None, "repair files", path, filt, options=options) if fileName.isEmpty(): raise RuntimeError("Could not find external data: " + path) else: return encode_from_qstring(fileName)
def _chooseDirectory(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = PreferencesManager().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 directory.isNull(): # User cancelled return directory = encode_from_qstring(directory) PreferencesManager().set('DataSelection', 'recent stack directory', directory) self.directoryEdit.setText(decode_to_qstring(directory)) globstring = self._getGlobString(directory) if globstring: filenames = OpStackLoader.expandGlobStrings(globstring) self._updateFileList(sorted(filenames)) # As a convenience, also show the glob string in the pattern field self.patternEdit.setText(decode_to_qstring(globstring))
def _printToLog(self, *args, **kwargs): parts = [] for s in (self.text(), self.informativeText(), self.detailedText()): if len(s) > 0: parts.append(encode_from_qstring(s)) msg = "\n".join(parts) logger.warn(msg)
def _chooseDirectory(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = PreferencesManager().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 directory.isNull(): # User cancelled return directory = encode_from_qstring( directory ) PreferencesManager().set('DataSelection', 'recent stack directory', directory) self.directoryEdit.setText( decode_to_qstring(directory) ) globstring = self._getGlobString(directory) if globstring is not None: filenames = [k.replace('\\', '/') for k in glob.glob(globstring)] self._updateFileList( sorted(filenames) ) # As a convenience, also show the glob string in the pattern field self.patternEdit.setText( decode_to_qstring(globstring) )
def _updateFromGui(self): export_dir = encode_from_qstring( self.directoryEdit.text() ) filename_pattern = encode_from_qstring( self.filePatternEdit.text() ) export_path = os.path.join( export_dir, filename_pattern ) self._filepathSlot.setValue( export_path ) old_valid_state = self.settings_are_valid if re.search("{slice_index(:.*)?}", export_path): self.settings_are_valid = True self.filePatternEdit.setStyleSheet("QLineEdit {background-color: white}" ) else: self.settings_are_valid = False self.filePatternEdit.setStyleSheet("QLineEdit {background-color: red}" ) if old_valid_state != self.settings_are_valid: self.pathValidityChange.emit( self.settings_are_valid )
def name( self, n ): if isinstance(n, str): n = decode_to_qstring(n, 'utf-8') assert isinstance(n, QString) pystr = encode_from_qstring(n, 'utf-8') if self._name != n: self._name = n self.nameChanged.emit(pystr)
def _updateFromGui(self): export_dir = encode_from_qstring(self.directoryEdit.text()) filename_pattern = encode_from_qstring(self.filePatternEdit.text()) export_path = os.path.join(export_dir, filename_pattern) self._filepathSlot.setValue(export_path) old_valid_state = self.settings_are_valid if re.search("{slice_index(:.*)?}", export_path): self.settings_are_valid = True self.filePatternEdit.setStyleSheet( "QLineEdit {background-color: white}") else: self.settings_are_valid = False self.filePatternEdit.setStyleSheet( "QLineEdit {background-color: red}") if old_valid_state != self.settings_are_valid: self.pathValidityChange.emit(self.settings_are_valid)
def eventFilter(self, watched, event): # Apply the new path if the user presses # 'enter' or clicks outside the filepathe editbox if watched == self.filepathEdit: if event.type() == QEvent.FocusOut or \ ( event.type() == QEvent.KeyPress and \ ( event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return) ): newpath = self.filepathEdit.text() newpath = encode_from_qstring(newpath) self._filepathSlot.setValue( newpath ) return False
def _onExportTifButtonPressed(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog directory = encode_from_qstring(QFileDialog.getExistingDirectory(self, 'Select Directory',os.path.expanduser("~"), options=options)) if directory is None or len(str(directory)) == 0: logger.info( "cancelled." ) return logger.info( 'Saving results as tiffs...' ) label2color = self.mainOperator.label2color lshape = list(self.mainOperator.LabelImage.meta.shape) def _handle_progress(x): self.applet.progressSignal.emit(x) def _export(): num_files = float(len(label2color)) for t, label2color_at in enumerate(label2color): if len(label2color_at) == 0: continue logger.info( 'exporting tiffs for t = ' + str(t) ) roi = SubRegion(self.mainOperator.LabelImage, start=[t,] + 4*[0,], stop=[t+1,] + list(lshape[1:])) labelImage = self.mainOperator.LabelImage.get(roi).wait() relabeled = relabel(labelImage[0,...,0],label2color_at) for i in range(relabeled.shape[2]): out_im = relabeled[:,:,i] out_fn = str(directory) + '/vis_t' + str(t).zfill(4) + '_z' + str(i).zfill(4) + '.tif' vigra.impex.writeImage(np.asarray(out_im,dtype=np.uint32), out_fn) _handle_progress(t/num_files * 100) logger.info( 'Tiffs exported.' ) def _handle_finished(*args): self._drawer.exportTifButton.setEnabled(True) self.applet.progressSignal.emit(100) def _handle_failure( exc, exc_info ): import traceback, sys traceback.print_exception(*exc_info) sys.stderr.write("Exception raised during export. See traceback above.\n") self.applet.progressSignal.emit(100) self._drawer.exportTifButton.setEnabled(True) self._drawer.exportTifButton.setEnabled(False) self.applet.progressSignal.emit(0) req = Request( _export ) req.notify_failed( _handle_failure ) req.notify_finished( _handle_finished ) req.submit()
def eventFilter(self, watched, event): # Apply the new path if the user presses # 'enter' or clicks outside the filepathe editbox if watched == self.filepathEdit: if event.type() == QEvent.FocusOut or \ ( event.type() == QEvent.KeyPress and \ ( event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return) ): newpath = self.filepathEdit.text() newpath = encode_from_qstring(newpath) self._filepathSlot.setValue(newpath) return False
def _onExportTifButtonPressed(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog directory = encode_from_qstring(QFileDialog.getExistingDirectory(self, 'Select Directory',os.path.expanduser("~"), options=options)) if directory is None or len(str(directory)) == 0: logger.info( "cancelled." ) return logger.info( 'Saving results as tiffs...' ) label2color = self.mainOperator.label2color lshape = list(self.mainOperator.LabelImage.meta.shape) def _handle_progress(x): self.applet.progressSignal.emit(x) def _export(): num_files = float(len(label2color)) for t, label2color_at in enumerate(label2color): if len(label2color_at) == 0: continue logger.info( 'exporting tiffs for t = ' + str(t) ) roi = SubRegion(self.mainOperator.LabelImage, start=[t,] + 4*[0,], stop=[t+1,] + list(lshape[1:])) labelImage = self.mainOperator.LabelImage.get(roi).wait() relabeled = relabel(labelImage[0,...,0],label2color_at) for i in range(relabeled.shape[2]): out_im = relabeled[:,:,i] out_fn = str(directory) + '/vis_t' + str(t).zfill(4) + '_z' + str(i).zfill(4) + '.tif' vigra.impex.writeImage(np.asarray(out_im,dtype=np.uint32), out_fn) _handle_progress(t/num_files * 100) logger.info( 'Tiffs exported.' ) def _handle_finished(*args): self._drawer.exportTifButton.setEnabled(True) self.applet.progressSignal.emit(100) def _handle_failure( exc, exc_info ): msg = "Exception raised during export. See traceback above.\n" log_exception( logger, msg, exc_info ) self.applet.progressSignal.emit(100) self._drawer.exportTifButton.setEnabled(True) self._drawer.exportTifButton.setEnabled(False) self.applet.progressSignal.emit(0) req = Request( _export ) req.notify_failed( _handle_failure ) req.notify_finished( _handle_finished ) req.submit()
def setData(self, index, value, role=Qt.EditRole): ''' Reimplement, see labelListModel or boxListModel for concrete example :param index: ''' if role == Qt.EditRole and index.column() == self.ColumnID.Name: row = index.row() # value is a user provided QVariant, possibly with unicode # characters in it. internally, we keep a str self._elements[row].name = encode_from_qstring(value.toString(), 'utf-8') self.dataChanged.emit(index, index) return True return False
def _browseForFilepath(self): starting_dir = os.path.expanduser("~") if self._filepathSlot.ready(): starting_dir = os.path.split(self._filepathSlot.value)[-1] dlg = QFileDialog( self, "Export Location", starting_dir, self._file_filter ) dlg.setDefaultSuffix(self._extension) dlg.setAcceptMode(QFileDialog.AcceptSave) if not dlg.exec_(): return exportPath = encode_from_qstring( dlg.selectedFiles()[0] ) self._filepathSlot.setValue( exportPath ) self.filepathEdit.setText( decode_to_qstring(exportPath) )
def _browseForFilepath(self): starting_dir = os.path.expanduser("~") if self._filepathSlot.ready(): starting_dir = os.path.split(self._filepathSlot.value)[-1] dlg = QFileDialog(self, "Export Location", starting_dir, self._file_filter) dlg.setAcceptMode(QFileDialog.AcceptSave) if not dlg.exec_(): return exportPath = encode_from_qstring(dlg.selectedFiles()[0]) self._filepathSlot.setValue(exportPath) self.filepathEdit.setText(decode_to_qstring(exportPath))
def setData(self, index, value, role=Qt.EditRole): ''' Reimplement, see labelListModel or boxListModel for concrete example :param index: ''' if role == Qt.EditRole and index.column() == self.ColumnID.Name: row = index.row() # value is a user provided QVariant, possibly with unicode # characters in it. internally, we keep a str self._elements[row].name = encode_from_qstring(value.toString()) self.dataChanged.emit(index, index) return True return False
def onUsePrecomputedFeaturesButtonClicked(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog filename = QFileDialog.getOpenFileName(self, 'Open Feature List', '.', options=options) filename = encode_from_qstring(filename) #sanity checks on the given file if not filename: return if not os.path.exists(filename): QMessageBox.critical(self, "Open Feature List", "File '%s' does not exist" % filename) return f = open(filename, 'r') with f: for line in f: line = line.strip() if len(line) == 0: continue if not os.path.exists(line): QMessageBox.critical( self, "Open Feature List", "File '%s', referenced in '%s', does not exist" % (line, filename)) return try: h = h5py.File(line, 'r') with h: assert len(h["data"].shape) == 3 except: QMessageBox.critical( self, "Open Feature List", "File '%s', referenced in '%s', could not be opened as an HDF5 file or does not contain a 3D dataset called 'data'" % (line, filename)) return self.topLevelOperatorView.FeatureListFilename.setValue(filename) self.topLevelOperatorView._setupOutputs() self.onFeaturesSelectionsChanged() # Notify the workflow that some applets may have changed state now. # (For example, the downstream pixel classification applet can # be used now that there are features selected) self.parentApplet.appletStateUpdateRequested.emit()
def _browseForFilepath(self): starting_dir = os.path.expanduser("~") if self._filepathSlot.ready(): starting_dir = os.path.split(self._filepathSlot.value)[0] dlg = QFileDialog( self, "Export Location", starting_dir, "HDF5 Files (*.h5 *.hdf5)" ) dlg.setDefaultSuffix("h5") dlg.setAcceptMode(QFileDialog.AcceptSave) if not dlg.exec_(): return exportPath = dlg.selectedFiles()[0] self.filepathEdit.setText( exportPath ) self._filepathSlot.setValue( encode_from_qstring(exportPath) )
def _browseForFilepath(self): starting_dir = os.path.expanduser("~") if self._filepathSlot.ready(): starting_dir = os.path.split(self._filepathSlot.value)[-1] dlg = QFileDialog( self, "Export Location", starting_dir, "HDF5 Files (*.h5 *.hdf5)" ) dlg.setDefaultSuffix("h5") dlg.setAcceptMode(QFileDialog.AcceptSave) if not dlg.exec_(): return exportPath = dlg.selectedFiles()[0] self.filepathEdit.setText( exportPath ) self._filepathSlot.setValue( encode_from_qstring(exportPath) )
def _applyPattern(self): globStrings = encode_from_qstring(self.patternEdit.text()) H5EXTS = OpStreamingHdf5SequenceReaderM.H5EXTS filenames = [] # see if some glob strings include HDF5 files globStrings = globStrings.split(os.path.pathsep) pcs = [PathComponents(x) for x in globStrings] ish5 = [x.extension in H5EXTS for x in pcs] h5GlobStrings = os.path.pathsep.join( [x for x, y in zip(globStrings, ish5) if y is True]) globStrings = os.path.pathsep.join( [x for x, y in zip(globStrings, ish5) if y is False]) filenames.extend(OpStackLoader.expandGlobStrings(globStrings)) try: OpStreamingHdf5SequenceReaderS.checkGlobString(h5GlobStrings) # OK, if nothing raised there is a single h5 file in h5GlobStrings: pathComponents = PathComponents( h5GlobStrings.split(os.path.pathsep)[0]) h5file = h5py.File(pathComponents.externalPath, mode='r') filenames.extend( "{}/{}".format(pathComponents.externalPath, internal) for internal in OpStreamingHdf5SequenceReaderS. expandGlobStrings(h5file, h5GlobStrings)) except (OpStreamingHdf5SequenceReaderS.WrongFileTypeError, OpStreamingHdf5SequenceReaderS.NotTheSameFileError, OpStreamingHdf5SequenceReaderS.NoInternalPlaceholderError, OpStreamingHdf5SequenceReaderS.ExternalPlaceholderError): pass try: OpStreamingHdf5SequenceReaderM.checkGlobString(h5GlobStrings) filenames.extend( "{}/{}".format(external, internal) for external, internal in zip( *OpStreamingHdf5SequenceReaderM.expandGlobStrings( h5GlobStrings))) except (OpStreamingHdf5SequenceReaderM.WrongFileTypeError, OpStreamingHdf5SequenceReaderM.SameFileError, OpStreamingHdf5SequenceReaderM.NoExternalPlaceholderError, OpStreamingHdf5SequenceReaderM.InternalPlaceholderError): pass self._updateFileList(filenames)
def onUsePrecomputedFeaturesButtonClicked(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog filename = QFileDialog.getOpenFileName(self, "Open Feature List", ".", options=options) filename = encode_from_qstring(filename) # sanity checks on the given file if not filename: return if not os.path.exists(filename): QMessageBox.critical(self, "Open Feature List", "File '%s' does not exist" % filename) return f = open(filename, "r") with f: for line in f: line = line.strip() if len(line) == 0: continue if not os.path.exists(line): QMessageBox.critical( self, "Open Feature List", "File '%s', referenced in '%s', does not exist" % (line, filename) ) return try: h = h5py.File(line, "r") with h: assert len(h["data"].shape) == 3 except: QMessageBox.critical( self, "Open Feature List", "File '%s', referenced in '%s', could not be opened as an HDF5 file or does not contain a 3D dataset called 'data'" % (line, filename), ) return self.topLevelOperatorView.FeatureListFilename.setValue(filename) self.topLevelOperatorView._setupOutputs() self.onFeaturesSelectionsChanged() # Notify the workflow that some applets may have changed state now. # (For example, the downstream pixel classification applet can # be used now that there are features selected) self.parentApplet.appletStateUpdateRequested.emit()
def _loadNewAnnotationFile(self): """ Ask the user for a new annotation filepath, and then load it. """ navDir = "" if self._annotationFilepath is not None: navDir = os.path.split(self._annotationFilepath)[0] selected_file = QFileDialog.getOpenFileName( self, "Load Split Annotation File", navDir, "JSON files (*.json)", options=QFileDialog.DontUseNativeDialog ) self.refreshButton.setEnabled(not selected_file.isNull()) if selected_file.isNull(): return self._loadAnnotationFile(encode_from_qstring(selected_file))
def _exportFeaturesButtonPressed(self): mainOperator = self.topLevelOperatorView if not mainOperator.RegionFeatures.ready(): mexBox=QMessageBox() mexBox.setText("No features have been computed yet. Nothing to save.") mexBox.exec_() return fname = QFileDialog.getSaveFileName(self, caption='Export Computed Features', filter="Pickled Objects (*.pkl);;All Files (*)") fname = encode_from_qstring( fname ) if len(fname)>0: #not cancelled with open(fname, 'w') as f: pickle.dump(mainOperator.RegionFeatures(list()).wait(), f) logger.debug("Exported object features to file '{}'".format(fname))
def repairFile(self,path,filt = None): """get new path to lost file""" from PyQt4.QtGui import QFileDialog,QMessageBox text = "The file at {} could not be found any more. Do you want to search for it at another directory?".format(path) c = QMessageBox.critical(None, "update external data",text, QMessageBox.Ok | QMessageBox.Cancel) if c == QMessageBox.Cancel: raise RuntimeError("Could not find external data: " + path) options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog fileName = QFileDialog.getOpenFileName( None, "repair files", path, filt, options=options) if fileName.isEmpty(): raise RuntimeError("Could not find external data: " + path) else: return encode_from_qstring(fileName)
def _browseForFilepath(self): from lazyflow.utility import PathComponents if self._fullPathOutputSlot.ready(): starting_dir = PathComponents( self._fullPathOutputSlot.value).externalDirectory else: starting_dir = os.path.expanduser("~") dlg = QFileDialog(self, "Export Location", starting_dir, "HDF5 Files (*.h5 *.hdf5)") dlg.setDefaultSuffix("h5") dlg.setAcceptMode(QFileDialog.AcceptSave) if not dlg.exec_(): return exportPath = dlg.selectedFiles()[0] self.filepathEdit.setText(exportPath) self._filepathSlot.setValue(encode_from_qstring(exportPath))
def _loadNewAnnotationFile(self): """ Ask the user for a new annotation filepath, and then load it. """ navDir = "" if self._annotation_filepath is not None: navDir = os.path.split(self._annotation_filepath)[0] selected_file = QFileDialog.getOpenFileName( self, "Load Split Annotation File", navDir, "JSON files (*.json)", options=QFileDialog.DontUseNativeDialog) self.refreshButton.setEnabled(not selected_file.isNull()) if selected_file.isNull(): return self._loadAnnotationFile(encode_from_qstring(selected_file))
def exportFinalSegmentation(self): # Ask for the export path exportPath = QFileDialog.getSaveFileName( self, "Save final segmentation", "", "Hdf5 Files (*.h5 *.hdf5)", options=QFileDialog.Options(QFileDialog.DontUseNativeDialog) ) if exportPath.isNull(): return def handleProgress(progress): # TODO: Hook this up to the progress bar logger.info( "Export progress: {}%".format( progress ) ) op = self.topLevelOperatorView req = op.exportFinalSegmentation( encode_from_qstring( exportPath ), "zyx", handleProgress ) self._drawer.exportButton.setEnabled(False) def handleFinish(*args): self._drawer.exportButton.setEnabled(True) req.notify_finished( handleFinish ) req.notify_failed( handleFinish )
def _applyNicknameToTempOps(self): newNickname = encode_from_qstring(self.nicknameEdit.text(), 'utf-8') if "<multiple>" in newNickname: return try: # Remove the event filter while this function executes because we don't # want to trigger additional calls to this very function. self.nicknameEdit.removeEventFilter(self) # Save a copy of our settings oldInfos = {} for laneIndex, op in self.tempOps.items(): oldInfos[laneIndex] = copy.copy( op.Dataset.value ) try: for laneIndex, op in self.tempOps.items(): info = copy.copy( op.Dataset.value ) info.nickname = newNickname op.Dataset.setValue( info ) self._error_fields.discard('Nickname') return True except Exception as e: # Revert everything back to the previous state for laneIndex, op in self.tempOps.items(): op.Dataset.setValue( oldInfos[laneIndex] ) msg = "Could not set new nickname due to an exception:\n" msg += "{}".format( e ) QMessageBox.warning(self, "Error", msg) log_exception( logger, msg ) self._error_fields += 'Nickname' return False finally: self.nicknameEdit.installEventFilter(self) self._updateNickname()
def _onExportButtonPressed(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog directory = encode_from_qstring(QFileDialog.getExistingDirectory(self, 'Select Directory',os.path.expanduser("~"), options=options)) if directory is None or len(str(directory)) == 0: logger.info( "cancelled." ) return def _handle_progress(x): self.applet.progressSignal.emit(x) def _export(): self.applet.busy = True self.applet.appletStateUpdateRequested.emit() if hasattr(self.mainOperator,"RelabeledImage"): labelImageSlot = self.mainOperator.RelabeledImage else: labelImageSlot = self.mainOperator.LabelImage logger.info( "Saving first label image..." ) key = [] for idx, flag in enumerate(axisTagsToString(labelImageSlot.meta.axistags)): if flag is 't': key.append(slice(0,labelImageSlot.meta.shape[idx]))#slice(t_from,t_from+1)) elif flag is 'c': key.append(slice(0,1)) else: key.append(slice(0,labelImageSlot.meta.shape[idx])) try: events = self.mainOperator.EventsVector.value logger.info( "Saving events..." ) logger.info( "Length of events " + str(len(events)) ) num_files = float(len(events)) for i in sorted(events.keys()): events_at = events[i] i = int(i) t = i key[0] = slice(t,t+1) roi = SubRegion(labelImageSlot, key) labelImage = labelImageSlot.get(roi).wait() labelImage = labelImage[0,...,0] write_events(events_at, str(directory), t, labelImage) _handle_progress(i/num_files * 100) except IOError as e: self._criticalMessage("Cannot export the tracking results. Maybe these files already exist. "\ "Please delete them or choose a different directory.") return def _handle_finished(*args): self.applet.busy = False self.applet.appletStateUpdateRequested.emit() self._drawer.exportButton.setEnabled(True) self.applet.progressSignal.emit(100) def _handle_failure( exc, exc_info ): self.applet.busy = False self.applet.appletStateUpdateRequested.emit() msg = "Exception raised during export. See traceback above.\n" log_exception( logger, msg, exc_info=exc_info ) self.applet.progressSignal.emit(100) self._drawer.exportButton.setEnabled(True) self._drawer.exportButton.setEnabled(False) self.applet.progressSignal.emit(0) req = Request( _export ) req.notify_failed( _handle_failure ) req.notify_finished( _handle_finished ) req.submit()
def handleProjectNameWidgetChanged(newText): self._projectMetadata.projectName = encode_from_qstring(newText)
def handleLabelerWidgetChanged(newText): self._projectMetadata.labeler = encode_from_qstring(newText)
def handleDescriptionWidgetChanged(): self._projectMetadata.description = encode_from_qstring(self.descriptionEdit.toPlainText())
def handleProjectNameWidgetChanged(newText): self._projectMetadata.projectName = encode_from_qstring( newText, 'utf-8')
def _applyPattern(self): globStrings = encode_from_qstring(self.patternEdit.text()) filenames = OpStackLoader.expandGlobStrings(globStrings) self._updateFileList(filenames)
def _applyFilepath(self): filepath = self.filepathEdit.text() self._filepathSlot.setValue( encode_from_qstring(filepath) )
def handleDescriptionWidgetChanged(): self._projectMetadata.description = encode_from_qstring( self.descriptionEdit.toPlainText(), 'utf-8')
def _applyFilepath(self): filepath = self.filepathEdit.text() self._filepathSlot.setValue(encode_from_qstring(filepath))
def _onExportButtonPressed(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog directory = encode_from_qstring( QFileDialog.getExistingDirectory(self, 'Select Directory', os.path.expanduser("~"), options=options)) if directory is None or len(str(directory)) == 0: logger.info("cancelled.") return def _handle_progress(x): self.applet.progressSignal.emit(x) def _export(): self.applet.busy = True self.applet.appletStateUpdateRequested.emit() t_from = None # determine from_time (it could has been changed in the GUI meanwhile) for t_from, label2color_at in enumerate( self.mainOperator.label2color): if len(label2color_at) == 0: continue else: break if t_from is None: self._criticalMessage("There is nothing to export.") return t_from = int(t_from) logger.info("Saving first label image...") key = [] for idx, flag in enumerate( axisTagsToString( self.mainOperator.LabelImage.meta.axistags)): if flag is 't': key.append(slice(t_from, t_from + 1)) elif flag is 'c': key.append(slice(0, 1)) else: key.append( slice(0, self.mainOperator.LabelImage.meta.shape[idx])) roi = SubRegion(self.mainOperator.LabelImage, key) labelImage = self.mainOperator.LabelImage.get(roi).wait() labelImage = labelImage[0, ..., 0] try: # write_events([], str(directory), t_from, labelImage) events = self.mainOperator.EventsVector.value logger.info("Saving events...") logger.info("Length of events " + str(len(events))) num_files = float(len(events)) for i in sorted(events.keys()): events_at = events[i] i = int(i) t = t_from + i key[0] = slice(t, t + 1) roi = SubRegion(self.mainOperator.LabelImage, key) labelImage = self.mainOperator.LabelImage.get(roi).wait() labelImage = labelImage[0, ..., 0] if self.withMergers: write_events(events_at, str(directory), t, labelImage, self.mainOperator.mergers) else: write_events(events_at, str(directory), t, labelImage) _handle_progress(i / num_files * 100) except IOError as e: self._criticalMessage("Cannot export the tracking results. Maybe these files already exist. "\ "Please delete them or choose a different directory.") return def _handle_finished(*args): self.applet.busy = False self.applet.appletStateUpdateRequested.emit() self._drawer.exportButton.setEnabled(True) self.applet.progressSignal.emit(100) def _handle_failure(exc, exc_info): self.applet.busy = False self.applet.appletStateUpdateRequested.emit() msg = "Exception raised during export. See traceback above.\n" log_exception(logger, msg, exc_info=exc_info) self.applet.progressSignal.emit(100) self._drawer.exportButton.setEnabled(True) self._drawer.exportButton.setEnabled(False) self.applet.progressSignal.emit(0) req = Request(_export) req.notify_failed(_handle_failure) req.notify_finished(_handle_finished) req.submit()
def _onExportButtonPressed(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog directory = encode_from_qstring(QFileDialog.getExistingDirectory(self, 'Select Directory',os.path.expanduser("~"), options=options)) if directory is None or len(str(directory)) == 0: logger.info( "cancelled." ) return def _handle_progress(x): self.applet.progressSignal.emit(x) def _export(): t_from = None # determine from_time (it could has been changed in the GUI meanwhile) for t_from, label2color_at in enumerate(self.mainOperator.label2color): if len(label2color_at) == 0: continue else: break if t_from == None: return logger.info( "Saving first label image..." ) key = [] for idx, flag in enumerate(axisTagsToString(self.mainOperator.LabelImage.meta.axistags)): if flag is 't': key.append(slice(t_from,t_from+1)) elif flag is 'c': key.append(slice(0,1)) else: key.append(slice(0,self.mainOperator.LabelImage.meta.shape[idx])) roi = SubRegion(self.mainOperator.LabelImage, key) labelImage = self.mainOperator.LabelImage.get(roi).wait() labelImage = labelImage[0,...,0] try: write_events([], str(directory), t_from, labelImage) events = self.mainOperator.EventsVector.value logger.info( "Saving events..." ) logger.info( "Length of events " + str(len(events)) ) num_files = float(len(events)) for i in events.keys(): events_at = events[i] t = t_from + i key[0] = slice(t+1,t+2) roi = SubRegion(self.mainOperator.LabelImage, key) labelImage = self.mainOperator.LabelImage.get(roi).wait() labelImage = labelImage[0,...,0] if self.withMergers: write_events(events_at, str(directory), t+1, labelImage, self.mainOperator.mergers) else: write_events(events_at, str(directory), t+1, labelImage) _handle_progress(i/num_files * 100) except IOError as e: self._criticalMessage("Cannot export the tracking results. Maybe these files already exist. "\ "Please delete them or choose a different directory.") return def _handle_finished(*args): self._drawer.exportButton.setEnabled(True) self.applet.progressSignal.emit(100) def _handle_failure( exc, exc_info ): msg = "Exception raised during export. See traceback above.\n" log_exception( logger, msg, exc_info=exc_info ) self.applet.progressSignal.emit(100) self._drawer.exportButton.setEnabled(True) self._drawer.exportButton.setEnabled(False) self.applet.progressSignal.emit(0) req = Request( _export ) req.notify_failed( _handle_failure ) req.notify_finished( _handle_finished ) req.submit()
def handleLabelerWidgetChanged(newText): self._projectMetadata.labeler = encode_from_qstring( newText, 'utf-8')