def serialize(self, h5g, destbegin = (0,0,0), destend = (0,0,0), srcbegin = (0,0,0), srcend = (0,0,0), destshape = (0,0,0) ):
        #for now save the labels and prediction in the old format
        #TODO: change that when we are certain about the new project file format
        vl = VolumeLabels(self.dataItemImage.overlayMgr["Classification/Labels"]._data)
        vl.descriptions = self.classificationModuleMgr.dataMgr.module["Classification"]["labelDescriptions"]
        vl.serialize(h5g, "labels", destbegin, destend, srcbegin, srcend, destshape)

        if len(vl.descriptions) > 0:
            prediction = numpy.zeros(self.dataItemImage.shape[0:-1] + (len(vl.descriptions),), 'float32')
            for d in vl.descriptions:
                if self.dataItemImage.overlayMgr["Classification/Prediction/" + d.name] is not None:
                    prediction[:,:,:,:,d.number-1] = self.dataItemImage.overlayMgr["Classification/Prediction/" + d.name][:,:,:,:,0]
            prediction = DataAccessor(prediction)
            prediction.serialize(h5g, 'prediction', destbegin, destend, srcbegin, srcend, destshape )
Example #2
0
 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
Example #3
0
    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
Example #5
0
    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()
Example #7
0
    def deserialize(self, h5G, offsets = (0,0,0), shape = (0,0,0)):
        self._dataVol = DataAccessor.deserialize(h5G, "data", offsets, shape)
        
        #load obsolete file format parts (pre version 0.5)
        #and store them in the properties
        #the responsible modules will take care of them
            
        for k in self.module.keys():
            if hasattr(self.module[k], "deserialize"):
                print "Deserializing", k
                self.module[k].deserialize(h5G, offsets, shape)

        self.updateOverlays()
Example #8
0
    def deserialize(self, h5G, offsets=(0, 0, 0), shape=(0, 0, 0)):
        self._dataVol = DataAccessor.deserialize(h5G, "data", offsets, shape)

        #load obsolete file format parts (pre version 0.5)
        #and store them in the properties
        #the responsible modules will take care of them

        for k in self.module.keys():
            if hasattr(self.module[k], "deserialize"):
                print "Deserializing", k
                self.module[k].deserialize(h5G, offsets, shape)

        self.updateOverlays()
Example #9
0
    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 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()
Example #11
0
 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)
Example #14
0
    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
Example #15
0
class OverlayItem(object):
    """
    A Item that holds some scalar or multichannel _data and their drawing related settings.
    OverlayItems are held by the OverlayMgr
    """
    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 __getitem__(self, args):
        return self._data[args]
            
    def __setitem__(self, args, data):
        self._data[args] = data

    def __getattr__(self, name):
        if name == "color":
            return self.getColor()
        elif name == "dtype":
            return self._data.dtype
        elif name == "shape":
            return self._data.shape
        elif name == "dataItemImage":
            return self.overlayMgr.dataItem
        else:
            raise AttributeError, name

    def getColorTab(self):
        return self.colorTable
    
    def getSubSlice(self, offsets, sizes, num, axis, time = 0, channel = 0):
        return self._data.getSubSlice(offsets, sizes, num, axis, time, channel)

        
    def setSubSlice(self, offsets, data, num, axis, time = 0, channel = 0):
        self._data.setSubSlice(offsets, data, num, axis, time, channel)
                          
    
    def getColor(self):
        if self.linkColor is False:
            return self.defaultColor
        else:
            return self.colorGetter()
                          
    
    def setColorGetter(self,colorGetter, colorGetterArguments):
        self.colorGetter = colorGetter
        self.colorGetterArguments = colorGetterArguments
        self.linkColor = True
    
    
    def getRef(self):
        ref = OverlayItemReference(self)
        ref.visible = self.autoVisible
        self.references.append(ref)
        return ref
        
    def remove(self):
        for r in self.references:
            r.remove()
        self.references = []
        self._data = None


    def changeKey(self, newKey):
        if self.overlayMgr is not None:
            self.overlayMgr.changeKey(self.key, newKey)
        
    def setData(self,  data):
        self.overlayItem._data = data

    @classmethod
    def normalizeForDisplay(cls, data):
        import numpy
        dmin = numpy.min(data)
        data = data - dmin
        dmax = numpy.max(data)
        data = 255*data/dmax
        return data

    @classmethod
    def qrgb(cls, r, g, b):
        return long(0xff << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)
    
    @classmethod
    def qgray(cls, r, g, b):
        return (r*11+g*16+b*5)/32
    
    @classmethod
    def createDefaultColorTable(cls, type, levels = 256, transparentValues = set()):
        typeCap = type.capitalize()
        colorTab = []
        if(typeCap == "GRAY"):
            for i in range(levels):
                if i in transparentValues:
                    colorTab.append(0L)
                else:
                    colorTab.append(OverlayItem.qgray(i, i, i)) # see qGray function in QtGui
        else:
            #RGB
            import numpy
            from ilastik.core.randomSeed import RandomSeed
            seed = RandomSeed.getRandomSeed()
            if seed is not None:
                numpy.random.seed(seed)
            for i in range(levels):
                if i in transparentValues:
                    colorTab.append(0L)
                else:
                    colorTab.append(OverlayItem.qrgb(numpy.random.randint(255),numpy.random.randint(255),numpy.random.randint(255))) # see gRGB function in QtGui
        return colorTab        
    
    @classmethod
    # IMPORTANT: BE AWARE THAT CHANGING THE COLOR TABLE MAY AFFECT TESTS THAT WORK WITH GROUND TRUTH 
    # DATA FROM EXPORTED OVERLAYS. TYPICALLY, ONLY THE DATA AND NOT THE COLOR TABLE OF AN OVERLAY IS
    # COMPARED BUT BETTER MAKE SURE THAT THIS IS INDEED THE CASE.
    def createDefault16ColorColorTable(cls):
        sublist = []
        sublist.append(OverlayItem.qrgb(69, 69, 69)) # dark grey
        sublist.append(OverlayItem.qrgb(255, 0, 0))
        sublist.append(OverlayItem.qrgb(0, 255, 0))
        sublist.append(OverlayItem.qrgb(0, 0, 255))
        
        sublist.append(OverlayItem.qrgb(255, 255, 0))
        sublist.append(OverlayItem.qrgb(0, 255, 255))
        sublist.append(OverlayItem.qrgb(255, 0, 255))
        sublist.append(OverlayItem.qrgb(255, 105, 180)) #hot pink!
        
        sublist.append(OverlayItem.qrgb(102, 205, 170)) #dark aquamarine
        sublist.append(OverlayItem.qrgb(165,  42,  42)) #brown        
        sublist.append(OverlayItem.qrgb(0, 0, 128)) #navy
        sublist.append(OverlayItem.qrgb(255, 165, 0)) #orange
        
        sublist.append(OverlayItem.qrgb(173, 255,  47)) #green-yellow
        sublist.append(OverlayItem.qrgb(128,0, 128)) #purple
        sublist.append(OverlayItem.qrgb(192, 192, 192)) #silver
        sublist.append(OverlayItem.qrgb(240, 230, 140)) #khaki
        colorlist = []
        colorlist.append(long(0))
        colorlist.extend(sublist)
        
        import numpy
        from ilastik.core.randomSeed import RandomSeed
        seed = RandomSeed.getRandomSeed()
        if seed is not None:
            numpy.random.seed(seed)        
        for i in range(17, 256):
            color = OverlayItem.qrgb(numpy.random.randint(255),numpy.random.randint(255),numpy.random.randint(255))
            colorlist.append(color)
            
        return colorlist    
Example #16
0
    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
Example #17
0
class OverlayItem(object):
    """
    A Item that holds some scalar or multichannel _data and their drawing related settings.
    OverlayItems are held by the OverlayMgr
    """
    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 __getitem__(self, args):
        return self._data[args]

    def __setitem__(self, args, data):
        self._data[args] = data

    def __getattr__(self, name):
        if name == "color":
            return self.getColor()
        elif name == "dtype":
            return self._data.dtype
        elif name == "shape":
            return self._data.shape
        elif name == "dataItemImage":
            return self.overlayMgr.dataItem
        else:
            raise AttributeError, name

    def getColorTab(self):
        return self.colorTable

    def getSubSlice(self, offsets, sizes, num, axis, time=0, channel=0):
        return self._data.getSubSlice(offsets, sizes, num, axis, time, channel)

    def setSubSlice(self, offsets, data, num, axis, time=0, channel=0):
        self._data.setSubSlice(offsets, data, num, axis, time, channel)

    def getColor(self):
        if self.linkColor is False:
            return self.defaultColor
        else:
            return self.colorGetter()

    def setColorGetter(self, colorGetter, colorGetterArguments):
        self.colorGetter = colorGetter
        self.colorGetterArguments = colorGetterArguments
        self.linkColor = True

    def getRef(self):
        ref = OverlayItemReference(self)
        ref.visible = self.autoVisible
        self.references.append(ref)
        return ref

    def remove(self):
        for r in self.references:
            r.remove()
        self.references = []
        self._data = None

    def changeKey(self, newKey):
        if self.overlayMgr is not None:
            self.overlayMgr.changeKey(self.key, newKey)

    def setData(self, data):
        self.overlayItem._data = data

    @classmethod
    def normalizeForDisplay(cls, data):
        import numpy
        dmin = numpy.min(data)
        data = data - dmin
        dmax = numpy.max(data)
        data = 255 * data / dmax
        return data

    @classmethod
    def qrgb(cls, r, g, b):
        return long(0xff << 24) | ((r & 0xff) << 16) | (
            (g & 0xff) << 8) | (b & 0xff)

    @classmethod
    def qgray(cls, r, g, b):
        return (r * 11 + g * 16 + b * 5) / 32

    @classmethod
    def createDefaultColorTable(cls,
                                type,
                                levels=256,
                                transparentValues=set()):
        typeCap = type.capitalize()
        colorTab = []
        if (typeCap == "GRAY"):
            for i in range(levels):
                if i in transparentValues:
                    colorTab.append(0L)
                else:
                    colorTab.append(OverlayItem.qgray(
                        i, i, i))  # see qGray function in QtGui
        else:
            #RGB
            import numpy
            from ilastik.core.randomSeed import RandomSeed
            seed = RandomSeed.getRandomSeed()
            if seed is not None:
                numpy.random.seed(seed)
            for i in range(levels):
                if i in transparentValues:
                    colorTab.append(0L)
                else:
                    colorTab.append(
                        OverlayItem.qrgb(
                            numpy.random.randint(255),
                            numpy.random.randint(255), numpy.random.randint(
                                255)))  # see gRGB function in QtGui
        return colorTab

    @classmethod
    # IMPORTANT: BE AWARE THAT CHANGING THE COLOR TABLE MAY AFFECT TESTS THAT WORK WITH GROUND TRUTH
    # DATA FROM EXPORTED OVERLAYS. TYPICALLY, ONLY THE DATA AND NOT THE COLOR TABLE OF AN OVERLAY IS
    # COMPARED BUT BETTER MAKE SURE THAT THIS IS INDEED THE CASE.
    def createDefault16ColorColorTable(cls):
        sublist = []
        sublist.append(OverlayItem.qrgb(69, 69, 69))  # dark grey
        sublist.append(OverlayItem.qrgb(255, 0, 0))
        sublist.append(OverlayItem.qrgb(0, 255, 0))
        sublist.append(OverlayItem.qrgb(0, 0, 255))

        sublist.append(OverlayItem.qrgb(255, 255, 0))
        sublist.append(OverlayItem.qrgb(0, 255, 255))
        sublist.append(OverlayItem.qrgb(255, 0, 255))
        sublist.append(OverlayItem.qrgb(255, 105, 180))  #hot pink!

        sublist.append(OverlayItem.qrgb(102, 205, 170))  #dark aquamarine
        sublist.append(OverlayItem.qrgb(165, 42, 42))  #brown
        sublist.append(OverlayItem.qrgb(0, 0, 128))  #navy
        sublist.append(OverlayItem.qrgb(255, 165, 0))  #orange

        sublist.append(OverlayItem.qrgb(173, 255, 47))  #green-yellow
        sublist.append(OverlayItem.qrgb(128, 0, 128))  #purple
        sublist.append(OverlayItem.qrgb(192, 192, 192))  #silver
        sublist.append(OverlayItem.qrgb(240, 230, 140))  #khaki
        colorlist = []
        colorlist.append(long(0))
        colorlist.extend(sublist)

        import numpy
        from ilastik.core.randomSeed import RandomSeed
        seed = RandomSeed.getRandomSeed()
        if seed is not None:
            numpy.random.seed(seed)
        for i in range(17, 256):
            color = OverlayItem.qrgb(numpy.random.randint(255),
                                     numpy.random.randint(255),
                                     numpy.random.randint(255))
            colorlist.append(color)

        return colorlist
    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 deserialize(self, h5G, offsets = (0,0,0), shape = (0,0,0)):
     labels = VolumeLabels.deserialize(h5G, "labels",offsets, shape)
     self["labels"] = labels
     if 'prediction' in h5G.keys():
         self["prediction"] = DataAccessor.deserialize(h5G, 'prediction', offsets, shape)
Example #20
0
 def initDataItemFromArray(image, name):
     dataItem = dataMgr.DataItemImage(name)
     dataItem._dataVol = DataAccessor(image, True)
     dataItem.updateOverlays()
     return dataItem