def run(self, imagename=None): if imagename is not None: self.load_image(imagename) if self.image is None: raise ImportError('Image cannot be loaded') # Create ilastik dataMgr dataMgr = DataMgr() di = DataItemImage('') di.setDataVol(DataAccessor(self.image)) dataMgr.append(di, alreadyLoaded=True) dataMgr.module["Classification"][ "classificationMgr"].classifiers = self.classifiers # Create FeatureMgr fm = FeatureMgr(dataMgr, self.features) fm.prepareCompute(dataMgr) fm.triggerCompute() fm.joinCompute(dataMgr) # Predict with loaded classifier classificationPredict = ClassifierPredictThread(dataMgr) classificationPredict.start() classificationPredict.wait() #del dataMgr return classificationPredict._prediction[0]
def calculateDsets(self, dsets, new_fg=True): """ eventually smooth the dataSets before doing the threshold. sad sad world. no point in re-smoothing the foreground, if only the background has changed """ if self.smoothing is True: dsets_new = [] #smooth only the foreground! for index, d in enumerate(dsets): if index < len(self.foregrounds) and new_fg is True: data = numpy.ndarray(d.shape, 'float32') for t in range(d.shape[0]): for c in range(d.shape[-1]): if d.shape[1] > 1: start_time = datetime.datetime.now() dRaw = numpy.asarray(d[t, :, :, :, c]) dRaw = dRaw.swapaxes(0, 2).view() res = vigra.filters.gaussianSmoothing( dRaw, self.sigma) res = res.swapaxes(0, 2).view() data[t, :, :, :, c] = res else: dRaw = d[t, 0, :, :, c].astype('float32').view( vigra.ScalarImage) data[t, 0, :, :, c] = vigra.filters.gaussianSmoothing( dRaw, self.sigma) dataAcc = DataAccessor(data) dsets_new.append(dataAcc) else: dsets_new.append(d) self.dsets = dsets_new else: self.dsets = dsets
def run(self, workspace): # get input image image = workspace.image_set.get_image(self.image_name.value, must_be_color=False) # recover raw image domain image_ = image.pixel_data * image.get_scale() # # Apply a rescaling that's done similarly in ilastik's dataImpex # image_max = np.max(image_) if (image_max > 255) and (image_max < 4096): image_ = image_ / 4095. * 255.0 # Create ilastik dataMgr dataMgr = DataMgr() # Transform input image to ilastik convention s # 3D = (time,x,y,z,channel) # 2D = (time,1,x,y,channel) # Note, this work for 2D images right now. Is there a need for 3D image_.shape = (1, 1) + image_.shape # Check if image_ has channels, if not add singelton dimension if len(image_.shape) == 4: image_.shape = image_.shape + (1, ) # Add data item di to dataMgr di = DataItemImage('') di.setDataVol(DataAccessor(image_)) dataMgr.append(di, alreadyLoaded=True) dataMgr.module["Classification"]["classificationMgr"].classifiers =\ self.get_classifiers(workspace) # Create FeatureMgr fm = FeatureMgr(dataMgr, self.get_feature_items(workspace)) # Compute features fm.prepareCompute(dataMgr) fm.triggerCompute() fm.joinCompute(dataMgr) # Predict with loaded classifier classificationPredict = ClassifierPredictThread(dataMgr) classificationPredict.start() classificationPredict.wait() workspace.display_data.source_image = image.pixel_data workspace.display_data.dest_images = [] for group in self.probability_maps: # Produce output image and select the probability map probMap = classificationPredict._prediction[0][ 0, 0, :, :, int(group.class_sel.value)] temp_image = cpi.Image(probMap, parent_image=image) workspace.image_set.add(group.output_image.value, temp_image) workspace.display_data.dest_images.append(probMap)
def on_btnDimensions(self): self.only2D = not self.only2D if self.only2D: ov = self.parent.project.dataMgr[self.parent._activeImageNumber].overlayMgr["Segmentation/Segmentation"] if ov is not None: zerod = numpy.zeros(ov._data.shape, numpy.uint8) ov._data = DataAccessor(zerod) self.btnChooseDimensions.setText('Using 2D') else: self.btnChooseDimensions.setText('Using 3D') self.setupWeights()
def on_overlaysChanged(self): if type(self.parent.labelWidget.labelWidget) is DummyLabelWidget: return s = self.ilastik._activeImage.Interactive_Segmentation if s.segmentation is None: #the segmentation has been cleared, remove overlay self.activeImage.overlayMgr.remove("Segmentation/Segmentation") self.segmentationOverlay = None elif self.activeImage.overlayMgr["Segmentation/Segmentation"] is None: #ensure that we have a 'Segmentation' overlay which will display the result of the segmentation algorithm origColorTable = copy.deepcopy(self.parent.labelWidget.labelWidget.colorTab) origColorTable[1] = 255 self.segmentationOverlay = OverlayItem(self.localMgr.segmentation, color = 0, alpha = 1.0, colorTable = origColorTable, autoAdd = True, autoVisible = True, linkColorTable = True) #this overlay can be shown in 3D #the label 0 never occurs, label 1 is assigned to the background class self.segmentationOverlay.displayable3D = True self.segmentationOverlay.backgroundClasses = set([1]) self.activeImage.overlayMgr["Segmentation/Segmentation"] = self.segmentationOverlay if s.segmentation is not None: #create Overlay for segmentation: res = self.localMgr.segmentation self.segmentationOverlay._data = DataAccessor(res) origColorTable = copy.deepcopy(self.parent.labelWidget.labelWidget.colorTab) origColorTable[1] = 255 self.segmentationOverlay.colorTable = origColorTable if self.localMgr.potentials is not None: origColorTable = copy.deepcopy(self.parent.labelWidget.labelWidget.colorTab) ov = OverlayItem(self.localMgr.potentials,color = origColorTable[1], alpha = 1.0, autoAdd = True, autoVisible = True, min = 0.0, max = 1.0) self.activeImage.overlayMgr["Segmentation/Potentials"] = ov else: self.activeImage.overlayMgr.remove("Segmentation/Potentials") if self.localMgr.borders is not None: #colorTab = [] #for i in range(256): # color = QtGui.QColor(random.randint(0,255),random.randint(0,255),random.randint(0,255)).rgba() # colorTab.append(color) ov = OverlayItem(self.localMgr.borders, color = QtGui.QColor(), alpha = 1.0, autoAdd = True, autoVisible = False, min = 0, max = 1.0) self.activeImage.overlayMgr["Segmentation/Supervoxels"] = ov else: self.activeImage.overlayMgr.remove("Segmentation/Supervoxels") self.parent.labelWidget.repaint()
def getDataItem(self, blockNr): di = DataItemImage("block " + str(blockNr)) boundsa = self._blockAccessor.getBlockBounds(blockNr, self.overlap) tempdata = DataAccessor(self._data[:, boundsa[0]:boundsa[1], boundsa[2]:boundsa[3], boundsa[4]:boundsa[5], :]) di.setDataVol(tempdata) boundsb = self._blockAccessor.getBlockBounds(blockNr, 0) di.setWriteBounds((boundsb[0], boundsb[2], boundsb[4]), (boundsb[1], boundsb[3], boundsb[5]), self._data.shape[1:-1]) di.setReadBounds((boundsb[0] - boundsa[0], boundsb[2] - boundsa[2], boundsb[4] - boundsa[4]), (boundsb[0] - boundsa[0] + boundsb[1] - boundsb[0], boundsb[2] - boundsa[2] + boundsb[3] - boundsb[2], boundsb[4] - boundsa[4] + boundsb[5] - boundsb[4])) return di
def finalizeResults(self): colortable = OverlayItem.createDefaultColorTable('RGB', 256) #create Overlay for segmentation: if self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Auto Segmentation/Segmentation"] is None: ov = OverlayItem(self.res, color=0, alpha=1.0, colorTable=colortable, autoAdd=True, autoVisible=True) self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Auto Segmentation/Segmentation"] = ov else: self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Auto Segmentation/Segmentation"]._data = DataAccessor( self.res)
def finalizeResults(self): #create Overlay for connected components: if self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Connected Components/CC Results"] is None: colortab = OverlayItem.createDefault16ColorColorTable() myColor = OverlayItem.qrgb(255, 0, 0) ov = OverlayItem(self.ccThread.result, color=myColor, alpha=1.0, colorTable=colortab, autoAdd=True, autoVisible=True) self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Connected Components/CC Results"] = ov else: self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Connected Components/CC Results"]._data = DataAccessor( self.ccThread.result)
def loadFromFile(fileName): # Load an image or a stack from a single file theDataItem = dataMgr.DataItemImage(fileName) print fileName fBase, fExt = os.path.splitext(fileName) if fExt == '.h5': f = h5py.File(fileName, 'r') g = f['volume'] theDataItem.deserialize(g) else: # I have to do a cast to at.Image which is useless in here, BUT, when i py2exe it, # the result of vigra.impex.readImage is numpy.ndarray? I don't know why... (see featureMgr compute) data = DataImpex.vigraReadImageWrapper(fileName) dataAcc = DataAccessor(data) theDataItem._dataVol = dataAcc theDataItem.updateOverlays() return theDataItem
def __init__(self, data, color=0, alpha=0.4, colorTable=None, autoAdd=False, autoVisible=False, linkColorTable=False, autoAlphaChannel=True, min=None, max=None): #whether this overlay can be displayed in 3D using #extraction of meshes self.displayable3D = False #if this overlay can be shown in 3D, the list of labels #that should be suppressed (not shown) self.backgroundClasses = set() self.smooth3D = True self._data = DataAccessor(data) self.linkColorTable = linkColorTable self.colorTable = colorTable self.defaultColor = color self.linkColor = False self.colorGetter = None self.colorGetterArguments = None self.alpha = alpha self.autoAlphaChannel = autoAlphaChannel self.channel = 0 self.name = "Unnamed Overlay" self.key = "Unknown Key" self.autoAdd = autoAdd self.autoVisible = autoVisible self.references = [] self.min = min self.max = max self.overlayMgr = None
def _predict_image_with_ilastik(self, image_): import ilastik from ilastik.core.dataMgr import DataMgr, DataItemImage from ilastik.modules.classification.core.featureMgr import FeatureMgr from ilastik.modules.classification.core.classificationMgr import ClassificationMgr from ilastik.modules.classification.core.features.featureBase import FeatureBase from ilastik.modules.classification.core.classifiers.classifierRandomForest import ClassifierRandomForest from ilastik.modules.classification.core.classificationMgr import ClassifierPredictThread from ilastik.core.volume import DataAccessor import numpy, h5py dataMgr = DataMgr() # Transform input image to ilastik convention s # 3D = (time,x,y,z,channel) # 2D = (time,1,x,y,channel) # Note, this work for 2D images right now. Is there a need for 3D image_.shape = (1,1) + image_.shape # Check if image_ has channels, if not add singelton dimension if len(image_.shape) == 4: image_.shape = image_.shape + (1,) # Add data item di to dataMgr di = DataItemImage('') di.setDataVol(DataAccessor(image_)) dataMgr.append(di, alreadyLoaded=True) fileName = self.params["ilastik_classifier"] ilastik_class = self.params["ilastik_class_selector"] hf = h5py.File(fileName,'r') temp = hf['classifiers'].keys() # If hf is not closed this leads to an error in win64 and mac os x hf.close() del hf classifiers = [] for cid in temp: cidpath = 'classifiers/' + cid classifiers.append(ClassifierRandomForest.loadRFfromFile(fileName, str(cidpath))) dataMgr.module["Classification"]["classificationMgr"].classifiers = classifiers # Restore user selection of feature items from hdf5 featureItems = [] f = h5py.File(fileName,'r') for fgrp in f['features'].values(): featureItems.append(FeatureBase.deserialize(fgrp)) f.close() del f fm = FeatureMgr(dataMgr, featureItems) # Create FeatureMgr # Compute features fm.prepareCompute(dataMgr) fm.triggerCompute() fm.joinCompute(dataMgr) # Predict with loaded classifier classificationPredict = ClassifierPredictThread(dataMgr) classificationPredict.start() classificationPredict.wait() if ilastik_class >= classificationPredict._prediction[0].shape[-1]: raise RuntimeError('ilastik output class not valid...') # Produce output image and select the probability map probMap = (classificationPredict._prediction[0][0,0,:,:, ilastik_class] * 255).astype(numpy.uint8) img_out = ccore.numpy_to_image(probMap, True) return img_out
def filterSynapses(self, inputOverlay, label, minsize, maxsize): #This is a special function to filter synapses. It assumes that the input overlay #is a threhsold overlay and computes it for equal probabilities, and then dilates the #the current connected components to the size of their counterparts in the equal #probability connected components. The resulting objects are filtered to be between minsize #and maxsize pixels in volume. #FIXME: This function is very specific and is only put here until ilastik 0.6 allows #to make it into a special workflow. Remove as soon as possible! parts = label.split(" ") labelnum = int(parts[0]) #labelname = parts[1] thres = self.dataMgr[ self.dataMgr._activeImageNumber].Connected_Components.inputData cc = self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Connected Components/CC Results"] if thres is None: print "no threshold overlay" return if not isinstance(thres._data, MultivariateThresholdAccessor): print "no threshold overlay used for connected components" return if cc is None: print "No connected components overlay" return sfad = SynapseFilterAndSegmentor(self.dataMgr, labelnum, minsize, maxsize, cc, inputOverlay) objs_user = sfad.computeUserThreshObjects() objs_ref = sfad.computeReferenceObjects() #goodsizes = [s for s in goodsizes if s>100] #mingoodsize = min(goodsizes) #maxgoodsize = max(goodsizes) objs_final = sfad.filterObjects(objs_user, objs_ref) #create a new, filtered overlay: result = numpy.zeros(cc.shape, dtype='int32') objcounter = 1 for iobj in objs_final: for i in range(len(iobj[0])): result[0, iobj[0][i], iobj[1][i], iobj[2][i], 0] = int(objcounter) objcounter = objcounter + 1 if self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Connected Components/CC Filtered"] is None: #colortab = [QtGui.qRgb(i, i, i) for i in range(256)] colortab = OverlayItem.createDefault16ColorColorTable() myColor = OverlayItem.qrgb(255, 0, 0) #QtGui.QColor(255, 0, 0) ov = OverlayItem(result, color=myColor, alpha=1.0, colorTable=colortab, autoAdd=True, autoVisible=True) self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Connected Components/CC Filtered"] = ov else: self.dataMgr[self.dataMgr._activeImageNumber].overlayMgr[ "Connected Components/CC Filtered"]._data = DataAccessor( result)
def initDataItemFromArray(image, name): dataItem = dataMgr.DataItemImage(name) dataItem._dataVol = DataAccessor(image, True) dataItem.updateOverlays() return dataItem