Пример #1
0
class PlanarSliceSourceTest(ut.TestCase):
    def setUp(self):
        self.raw = np.random.randint(0, 100, (10, 3, 3, 128, 3))
        self.a = ArraySource(self.raw)
        self.ss = PlanarSliceSource(self.a, projectionAlongTZC)

    def testRequest(self):
        self.ss.setThrough(0, 1)
        self.ss.setThrough(2, 2)
        self.ss.setThrough(1, 127)

        sl = self.ss.request((slice(None), slice(None))).wait()
        self.assertTrue(np.all(sl == self.raw[1, :, :, 127, 2]))

        sl_bounded = self.ss.request((slice(0, 3), slice(1, None))).wait()
        numpy.testing.assert_array_equal(sl_bounded, self.raw[1, 0:3, 1:, 127,
                                                              2])

    def testDirtynessPropagation(self):
        self.ss.setThrough(0, 1)
        self.ss.setThrough(2, 2)
        self.ss.setThrough(1, 127)

        check_mock = mock.Mock()
        self.ss.isDirty.connect(check_mock)
        self.a.setDirty(np.s_[1:2, :, 1:2, 127:128, 2:3])
        self.ss.isDirty.disconnect(check_mock)
        check_mock.assert_called_once_with(np.s_[:, 1:2])
Пример #2
0
 def setUp( self ):
     GenericArraySourceTest.setUp(self)
     self.lena = np.load(os.path.join(volumina._testing.__path__[0], 'lena.npy'))
     self.raw = np.zeros((1,512,512,1,1))
     self.raw[0,:,:,0,0] = self.lena
     self.source = ArraySource( self.raw )
     
     self.samesource = ArraySource( self.raw )
     self.othersource = ArraySource( np.array(self.raw) )
Пример #3
0
    def setUp(self):
        GenericArraySourceTest.setUp(self)
        self.cells2d = np.load(os.path.join(volumina._testing.__path__[0], "2d_cells_apoptotic_1channel.npy"))
        y, x = self.cells2d.shape
        self.raw = np.zeros((1, y, x, 1, 1))
        self.raw[0, :, :, 0, 0] = self.cells2d
        self.source = ArraySource(self.raw)

        self.samesource = ArraySource(self.raw)
        self.othersource = ArraySource(np.array(self.raw))
Пример #4
0
    def setUp( self ):
        dataShape = (1, 900, 400, 10, 1) # t,x,y,z,c
        data = np.indices(dataShape)[3].astype(np.uint8) # Data is labeled according to z-index
        self.ds1 = ArraySource( data )
        self.CONSTANT = 13
        self.ds2 = ConstantSource( self.CONSTANT )

        self.layer1 = GrayscaleLayer( self.ds1, normalize=False )
        self.layer1.visible = True
        self.layer1.opacity = 1.0

        self.layer2 = GrayscaleLayer( self.ds2, normalize=False )

        self.lsm = LayerStackModel()
        self.pump = ImagePump( self.lsm, SliceProjection(), sync_along=(0,1,2) )
Пример #5
0
    def setupLayers(self):
        layers = []
        op = self.topLevelOperatorView

        # Superpixels
        if op.Superpixels.ready():
            layer = ColortableLayer( LazyflowSource(op.Superpixels), self._sp_colortable )
            layer.colortableIsRandom = True
            layer.name = "Superpixels"
            layer.visible = True
            layer.opacity = 0.5
            layers.append(layer)
            del layer

        # Debug layers
        if op.debug_results:
            for name, compressed_array in op.debug_results.items():
                axiskeys = op.Superpixels.meta.getAxisKeys()[:-1] # debug images don't have a channel axis
                permutation = map(lambda key: axiskeys.index(key) if key in axiskeys else None, 'txyzc')
                arraysource = ArraySource( TransposedView(compressed_array, permutation) )
                if compressed_array.dtype == np.uint32:
                    layer = ColortableLayer(arraysource, self._sp_colortable)
                else:
                    layer = GrayscaleLayer(arraysource)
                    # TODO: Normalize? Maybe the drange should be included with the debug image.
                layer.name = name
                layer.visible = False
                layer.opacity = 1.0
                layers.append(layer)
                del layer

        # Threshold
        if op.ThresholdedInput.ready():
            layer = ColortableLayer( LazyflowSource(op.ThresholdedInput), self._threshold_colortable )
            layer.name = "Thresholded Input"
            layer.visible = True
            layer.opacity = 1.0
            layers.append(layer)
            del layer

        # Raw Data (grayscale)
        if op.Input.ready():
            layer = self._create_grayscale_layer_from_slot( op.Input, op.Input.meta.getTaggedShape()['c'] )
            layer.name = "Input"
            layer.visible = False
            layer.opacity = 1.0
            layers.append(layer)
            del layer

        # Raw Data (grayscale)
        if op.RawData.ready():
            layer = self.createStandardLayerFromSlot( op.RawData )
            layer.name = "Raw Data"
            layer.visible = True
            layer.opacity = 1.0
            layers.append(layer)
            del layer

        return layers
Пример #6
0
    def createWidget(self, parent):
        a = (numpy.random.random((1, 100, 200, 300, 1)) * 255).astype(numpy.uint8)
        source = ArraySource(a)
        layerstack = LayerStackModel()
        layerstack.append(GrayscaleLayer(source))

        editor = VolumeEditor(layerstack, labelsink=None, parent=self)
        widget = VolumeEditorWidget(parent=parent)
        if not _has_lazyflow:
            widget.setEnabled(False)
        widget.init(editor)
        editor.dataShape = a.shape
        return widget
Пример #7
0
    def setUp( self ):
        dataShape = (1, 900, 400, 10, 1) # t,x,y,z,c
        data = np.indices(dataShape)[3] # Data is labeled according to z-index
        self.ds1 = ArraySource( data )
        self.CONSTANT = 13
        self.ds2 = ConstantSource( self.CONSTANT )

        self.layer1 = GrayscaleLayer( self.ds1 )
        self.layer1.visible = True
        self.layer1.opacity = 1.0

        self.layer2 = GrayscaleLayer( self.ds2 )

        self.lsm = LayerStackModel()
        self.pump = ImagePump( self.lsm, SliceProjection() )
Пример #8
0
def showStuff(raw_name,
              pred_viewer1,
              pred_viewer2,
              cutout_name,
              one_extra=None):
    # display the raw and annotations for cremi challenge data
    raw = vigra.impex.readHDF5(indir + datasets[raw_name], "data", order='C')
    # raw_old = vigra.readHDF5(indir+datasets["raw_bad"], "data", order = 'C')
    defect_prediction_128 = vigra.impex.readHDF5(indir +
                                                 datasets[pred_viewer2],
                                                 "data",
                                                 order='C')
    defect_prediction_150 = vigra.impex.readHDF5(indir +
                                                 datasets[pred_viewer1],
                                                 "data",
                                                 order='C')
    cutout_from_150_pred = vigra.impex.readHDF5(indir + datasets[cutout_name],
                                                "data",
                                                order='C')

    ####################################################################################################################
    # only used for fast testing stuff
    #change_one = vigra.readHDF5(indir+datasets["segmentation_on_equalized_image"], "data", order = 'C')
    #pdb.set_trace()
    #defect_prediction_150[1,:,:] = change_one[0,:,:,0]
    ####################################################################################################################
    # defect_prediction_150 = gt[..., 0]
    cutout = numpy.asarray(cutout_from_150_pred)
    rawdata = numpy.asarray(raw)
    # rawdata_old = numpy.asarray(raw_old)
    # op5ify
    # shape5d = rawdata.shape
    shape5d = (1, ) + rawdata.shape + (1, )
    print shape5d, rawdata.shape, rawdata.dtype

    app = QApplication([])
    v = Viewer()
    direct = False

    # layer for raw data
    rawdata = numpy.reshape(rawdata, shape5d)
    rawsource = ArraySource(rawdata)
    v.dataShape = shape5d
    lraw = GrayscaleLayer(rawsource, direct=direct)
    lraw.visible = True
    lraw.name = "raw"
    v.layerstack.append(lraw)

    # layer for cutout regions from raw data
    cutout = numpy.reshape(cutout, shape5d)
    cutoutsource = ArraySource(cutout)
    lcutout = GrayscaleLayer(cutoutsource, direct=direct)
    lcutout.visible = False
    lcutout.name = "cut_out"
    v.layerstack.append(lcutout)

    # layer for first prediction result
    defect_prediction_128 = numpy.reshape(defect_prediction_128, shape5d)
    synsource = ArraySource(defect_prediction_128)
    ct = create_random_16bit()
    ct[0] = 0
    lsyn = ColortableLayer(synsource, ct)
    lsyn.name = pred_viewer2
    lsyn.visible = False
    v.layerstack.append(lsyn)

    # layer for second prediction result
    segm = numpy.reshape(defect_prediction_150, shape5d)
    segsource = ArraySource(segm)
    ct = create_random_16bit()
    ct[0] = 0
    lseg = ColortableLayer(segsource, ct)
    lseg.name = pred_viewer1
    lseg.visible = False
    v.layerstack.append(lseg)
    if one_extra is None:
        v.showMaximized()
        app.exec_()

    if one_extra is not None:
        # layer for third prediction result
        extra_prediction = vigra.readHDF5(indir + datasets[one_extra],
                                          "data",
                                          order='C')
        extra_pred_reshaped = numpy.reshape(extra_prediction, shape5d)
        segsource = ArraySource(extra_pred_reshaped)
        ct = create_random_16bit()
        ct[0] = 0
        # ct = create_default_16bit()
        lseg = ColortableLayer(segsource, ct)
        lseg.name = one_extra
        lseg.visible = False
        v.layerstack.append(lseg)
        v.showMaximized()
        app.exec_()
Пример #9
0
class DirtyPropagationTest( ut.TestCase ):

    def setUp( self ):
        dataShape = (1, 900, 400, 10, 1) # t,x,y,z,c
        data = np.indices(dataShape)[3].astype(np.uint8) # Data is labeled according to z-index
        self.ds1 = ArraySource( data )
        self.CONSTANT = 13
        self.ds2 = ConstantSource( self.CONSTANT )

        self.layer1 = GrayscaleLayer( self.ds1, normalize=False )
        self.layer1.visible = True
        self.layer1.opacity = 1.0

        self.layer2 = GrayscaleLayer( self.ds2, normalize=False )

        self.lsm = LayerStackModel()
        self.pump = ImagePump( self.lsm, SliceProjection(), sync_along=(0,1,2) )

    def testEverythingDirtyPropagation( self ):
        self.lsm.append(self.layer2)
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.pump.stackedImageSources)

        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == self.CONSTANT))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

        NEW_CONSTANT = self.CONSTANT+1
        self.ds2.constant = NEW_CONSTANT
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == NEW_CONSTANT))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

    def testOutOfViewDirtyPropagation( self ):
        self.lsm.append(self.layer1)
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.pump.stackedImageSources)

        # Navigate down to the second z-slice
        self.pump.syncedSliceSources.through = [0,1,0]
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()

        # Sanity check: Do we see the right data on the second
        # slice? (should be all 1s)
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == 1))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

        # Navigate down to the third z-slice
        self.pump.syncedSliceSources.through = [0,2,0]
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()

        # Sanity check: Do we see the right data on the third
        # slice?(should be all 2s)
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == 2))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

        # Navigate back up to the second z-slice
        self.pump.syncedSliceSources.through = [0,1,0]
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == 1))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

        # Change some of the data in the (out-of-view) third z-slice
        slicing = (slice(None), slice(100,300), slice(100,300),
                   slice(2,3), slice(None))
        slicing = tuple(slicing)
        self.ds1._array[slicing] = 99
        self.ds1.setDirty( slicing )

        # Navigate back down to the third z-slice
        self.pump.syncedSliceSources.through = [0,2,0]
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()

        # Even though the data was out-of-view when it was
        # changed, it should still have new values. If dirtiness
        # wasn't propagated correctly, the cache's old values will
        # be used. (For example, this fails if you comment out the
        # call to setDirty, above.)

        # Shrink accessed rect by 1 pixel on each side (Otherwise,
        # tiling overlap_draw causes getTiles() to return
        # surrounding tiles that we haven't actually touched in
        # this test)
        tiles = tp.getTiles(QRectF(101,101,198,198))

        for tile in tiles:
            aimg = byte_view(tile.qimg)
            # Use any() because the tile borders may not be
            # perfectly aligned with the data we changed.
            self.assertTrue(np.any(aimg[:,:,0:3] == 99))
Пример #10
0
class DirtyPropagationTest( ut.TestCase ):
    
    def setUp( self ):
        dataShape = (1, 900, 400, 10, 1) # t,x,y,z,c
        data = np.indices(dataShape)[3] # Data is labeled according to z-index
        self.ds1 = ArraySource( data )
        self.CONSTANT = 13
        self.ds2 = ConstantSource( self.CONSTANT )

        self.layer1 = GrayscaleLayer( self.ds1 )
        self.layer1.visible = True
        self.layer1.opacity = 1.0

        self.layer2 = GrayscaleLayer( self.ds2 )

        self.lsm = LayerStackModel()
        self.pump = ImagePump( self.lsm, SliceProjection() )

    def testEverythingDirtyPropagation( self ):
        self.lsm.append(self.layer2)        
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.pump.stackedImageSources)
        try:
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == self.CONSTANT))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            NEW_CONSTANT = self.CONSTANT+1
            self.ds2.constant = NEW_CONSTANT
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == NEW_CONSTANT))
                self.assertTrue(np.all(aimg[:,:,3] == 255))
            
        finally:
            tp.notifyThreadsToStop()
            tp.joinThreads()

    def testOutOfViewDirtyPropagation( self ):
        self.lsm.append(self.layer1)
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.pump.stackedImageSources)
        try:
            # Navigate down to the second z-slice
            self.pump.syncedSliceSources.through = [0,1,0]
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()

            # Sanity check: Do we see the right data on the second slice? (should be all 1s)
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == 1))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            # Navigate down to the third z-slice
            self.pump.syncedSliceSources.through = [0,2,0]
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()

            # Sanity check: Do we see the right data on the third slice?(should be all 2s)
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == 2))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            # Navigate back up to the second z-slice
            self.pump.syncedSliceSources.through = [0,1,0]
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == 1))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            # Change some of the data in the (out-of-view) third z-slice
            slicing = (slice(None), slice(100,300), slice(100,300), slice(2,3), slice(None))
            slicing = tuple(slicing)
            self.ds1._array[slicing] = 99
            self.ds1.setDirty( slicing )
            
            # Navigate back down to the third z-slice
            self.pump.syncedSliceSources.through = [0,2,0]
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()

            # Even though the data was out-of-view when it was changed, it should still have new values.
            # If dirtiness wasn't propagated correctly, the cache's old values will be used.
            # (For example, this fails if you comment out the call to setDirty, above.)
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                # Use any() because the tile borders may not be perfectly aligned with the data we changed.
                self.assertTrue(np.any(aimg[:,:,0:3] == 99))

        finally:
            tp.notifyThreadsToStop()
            tp.joinThreads()
Пример #11
0
    def setupLayers(self):
        logger.debug("setupLayers")

        layers = []

        def onButtonsEnabled(slot, roi):
            currObj = self.topLevelOperatorView.CurrentObjectName.value
            hasSeg = self.topLevelOperatorView.HasSegmentation.value

            self.labelingDrawerUi.currentObjectLabel.setText(currObj)
            self.labelingDrawerUi.save.setEnabled(hasSeg)

        self.topLevelOperatorView.CurrentObjectName.notifyDirty(
            onButtonsEnabled)
        self.topLevelOperatorView.HasSegmentation.notifyDirty(onButtonsEnabled)
        self.topLevelOperatorView.opLabelArray.NonzeroBlocks.notifyDirty(
            onButtonsEnabled)

        # Labels
        labellayer, labelsrc = self.createLabelLayer(direct=True)
        if labellayer is not None:
            labellayer._allowToggleVisible = False
            layers.append(labellayer)
            # Tell the editor where to draw label data
            self.editor.setLabelSink(labelsrc)

        #uncertainty
        #if self._showUncertaintyLayer:
        #    uncert = self.topLevelOperatorView.Uncertainty
        #    if uncert.ready():
        #        colortable = []
        #        for i in range(256-len(colortable)):
        #            r,g,b,a = i,0,0,i
        #            colortable.append(QColor(r,g,b,a).rgba())
        #        layer = ColortableLayer(LazyflowSource(uncert), colortable, direct=True)
        #        layer.name = "Uncertainty"
        #        layer.visible = True
        #        layer.opacity = 0.3
        #        layers.append(layer)

        #segmentation
        seg = self.topLevelOperatorView.Segmentation

        #seg = self.topLevelOperatorView.MST.value.segmentation
        #temp = self._done_lut[self.MST.value.supervoxelUint32[sl[1:4]]]
        if seg.ready():
            #source = RelabelingArraySource(seg)
            #source.setRelabeling(numpy.arange(256, dtype=numpy.uint8))

            # assign to the object label color, 0 is transparent, 1 is background
            colortable = [
                QColor(0, 0, 0, 0).rgba(),
                QColor(0, 0, 0, 0).rgba(), labellayer._colorTable[2]
            ]
            for i in range(256 - len(colortable)):
                r, g, b = numpy.random.randint(0, 255), numpy.random.randint(
                    0, 255), numpy.random.randint(0, 255)
                colortable.append(QColor(r, g, b).rgba())

            layer = ColortableLayer(LazyflowSource(seg),
                                    colortable,
                                    direct=True)
            layer.name = "Segmentation"
            layer.setToolTip("This layer displays the <i>current</i> segmentation. Simply add foreground and background " \
                             "labels, then press <i>Segment</i>.")
            layer.visible = True
            layer.opacity = 0.3
            layers.append(layer)

        #done
        doneSeg = self.topLevelOperatorView.DoneSegmentation
        if doneSeg.ready():
            #FIXME: if the user segments more than 255 objects, those with indices that divide by 255 will be shown as transparent
            #both here and in the _doneSegmentationColortable
            colortable = 254 * [QColor(230, 25, 75).rgba()]
            colortable.insert(0, QColor(0, 0, 0, 0).rgba())

            #have to use lazyflow because it provides dirty signals
            layer = ColortableLayer(LazyflowSource(doneSeg),
                                    colortable,
                                    direct=True)
            layer.name = "Completed segments (unicolor)"
            layer.setToolTip("In order to keep track of which objects you have already completed, this layer " \
                             "shows <b>all completed object</b> in one color (<b>blue</b>). " \
                             "The reason for only one color is that for finding out which " \
                              "objects to label next, the identity of already completed objects is unimportant " \
                              "and destracting.")
            layer.visible = False
            layer.opacity = 0.5
            layers.append(layer)

            layer = ColortableLayer(LazyflowSource(doneSeg),
                                    self._doneSegmentationColortable,
                                    direct=True)
            layer.name = "Completed segments (one color per object)"
            layer.setToolTip("<html>In order to keep track of which objects you have already completed, this layer " \
                             "shows <b>all completed object</b>, each with a random color.</html>")
            layer.visible = False
            layer.opacity = 0.5
            layer.colortableIsRandom = True
            self._doneSegmentationLayer = layer
            layers.append(layer)

        #supervoxel
        sv = self.topLevelOperatorView.Supervoxels
        if sv.ready():
            colortable = []
            for i in range(256):
                r, g, b = numpy.random.randint(0, 255), numpy.random.randint(
                    0, 255), numpy.random.randint(0, 255)
                colortable.append(QColor(r, g, b).rgba())
            layer = ColortableLayer(LazyflowSource(sv),
                                    colortable,
                                    direct=True)
            layer.name = "Supervoxels"
            layer.setToolTip("<html>This layer shows the partitioning of the input image into <b>supervoxels</b>. The carving " \
                             "algorithm uses these tiny puzzle-piceces to piece together the segmentation of an " \
                             "object. Sometimes, supervoxels are too large and straddle two distinct objects " \
                             "(undersegmentation). In this case, it will be impossible to achieve the desired " \
                             "segmentation. This layer helps you to understand these cases.</html>")
            layer.visible = False
            layer.colortableIsRandom = True
            layer.opacity = 0.5
            layers.append(layer)

        # Visual overlay (just for easier labeling)
        overlaySlot = self.topLevelOperatorView.OverlayData
        if overlaySlot.ready():
            overlay5D = self.topLevelOperatorView.OverlayData.value
            layer = GrayscaleLayer(ArraySource(overlay5D), direct=True)
            layer.visible = True
            layer.name = 'Overlay'
            layer.opacity = 1.0
            # if the flag window_leveling is set the contrast
            # of the layer is adjustable
            layer.window_leveling = True
            self.labelingDrawerUi.thresToolButton.show()
            layers.append(layer)
            del layer

        inputSlot = self.topLevelOperatorView.InputData
        if inputSlot.ready():
            layer = GrayscaleLayer(LazyflowSource(inputSlot), direct=True)
            layer.name = "Input Data"
            layer.setToolTip(
                "<html>The data originally loaded into ilastik (unprocessed).</html>"
            )
            #layer.visible = not rawSlot.ready()
            layer.visible = True
            layer.opacity = 1.0

            # Window leveling is already active on the Overlay,
            # but if no overlay was provided, then activate window_leveling on the raw data instead.
            if not overlaySlot.ready():
                # if the flag window_leveling is set the contrast
                # of the layer is adjustable
                layer.window_leveling = True
                self.labelingDrawerUi.thresToolButton.show()

            layers.append(layer)
            del layer

        filteredSlot = self.topLevelOperatorView.FilteredInputData
        if filteredSlot.ready():
            layer = GrayscaleLayer(LazyflowSource(filteredSlot))
            layer.name = "Filtered Input"
            layer.visible = False
            layer.opacity = 1.0
            layers.append(layer)

        return layers
    def setupLayers(self):
        layers = []
        
        op = self.topLevelOperatorView
        
        ravelerLabelsSlot = op.RavelerLabels
        if ravelerLabelsSlot.ready():
            colortable = []
            for _ in range(256):
                r,g,b = numpy.random.randint(0,255), numpy.random.randint(0,255), numpy.random.randint(0,255)
                colortable.append(QColor(r,g,b).rgba())
            ravelerLabelLayer = ColortableLayer(LazyflowSource(ravelerLabelsSlot), colortable, direct=True)
            ravelerLabelLayer.name = "Raveler Labels"
            ravelerLabelLayer.visible = False
            ravelerLabelLayer.opacity = 0.4
            layers.append(ravelerLabelLayer)

        def addFragmentSegmentationLayers(mslot, name):
            if mslot.ready():
                for index, slot in enumerate(mslot):
                    if slot.ready():
                        raveler_label = slot.meta.selected_label
                        colortable = map(QColor.rgba, self._fragmentColors)
                        fragSegLayer = ColortableLayer(LazyflowSource(slot), colortable, direct=True)
                        fragSegLayer.name = "{} #{} ({})".format( name, index, raveler_label )
                        fragSegLayer.visible = False
                        fragSegLayer.opacity = 1.0
                        layers.append(fragSegLayer)

        addFragmentSegmentationLayers( op.FragmentedBodies, "Saved Fragments" )
        addFragmentSegmentationLayers( op.RelabeledFragments, "Relabeled Fragments" )
        addFragmentSegmentationLayers( op.FilteredFragmentedBodies, "CC-Filtered Fragments" )
        addFragmentSegmentationLayers( op.WatershedFilledBodies, "Watershed-filled Fragments" )

        mslot = op.EditedRavelerBodies
        for index, slot in enumerate(mslot):
            if slot.ready():
                raveler_label = slot.meta.selected_label
                # 0=Black, 1=Transparent
                colortable = [QColor(0, 0, 0).rgba(), QColor(0, 0, 0, 0).rgba()]
                bodyMaskLayer = ColortableLayer(LazyflowSource(slot), colortable, direct=True)
                bodyMaskLayer.name = "Raveler Body Mask #{} ({})".format( index, raveler_label )
                bodyMaskLayer.visible = False
                bodyMaskLayer.opacity = 1.0
                layers.append(bodyMaskLayer)

        finalSegSlot = op.FinalSegmentation
        if finalSegSlot.ready():
            colortable = []
            for _ in range(256):
                r,g,b = numpy.random.randint(0,255), numpy.random.randint(0,255), numpy.random.randint(0,255)
                colortable.append(QColor(r,g,b).rgba())
            finalLayer = ColortableLayer(LazyflowSource(finalSegSlot), colortable, direct=True)
            finalLayer.name = "Final Segmentation"
            finalLayer.visible = False
            finalLayer.opacity = 0.4
            layers.append(finalLayer)

        inputSlot = op.InputData
        if inputSlot.ready():
            layer = GrayscaleLayer( LazyflowSource(inputSlot) )
            layer.name = "WS Input"
            layer.visible = False
            layer.opacity = 1.0
            layers.append(layer)

        #raw data
        rawSlot = self.topLevelOperatorView.RawData
        rawLayer = None
        if rawSlot.ready():
            raw5D = self.topLevelOperatorView.RawData.value
            rawLayer = GrayscaleLayer(ArraySource(raw5D), direct=True)
            #rawLayer = GrayscaleLayer( LazyflowSource(rawSlot) )
            rawLayer.name = "raw"
            rawLayer.visible = True
            rawLayer.opacity = 1.0
            rawLayer.shortcutRegistration = ( "g", ShortcutManager.ActionInfo(
                                                       "Postprocessing",
                                                       "Raw Data to Top",
                                                       "Raw Data to Top",
                                                       partial(self._toggleRawDataPosition, rawLayer),
                                                       self.viewerControlWidget(),
                                                       rawLayer ) )
            layers.append(rawLayer)

        return layers
Пример #13
0
    o4 = Layer([ConstantSource()])
    o4.name = "Fancy Layer II"
    o4.opacity = 0.95
    model.append(o4)

    o5 = Layer([ConstantSource()])
    o5.name = "Fancy Layer III"
    o5.opacity = 0.65
    model.append(o5)

    o6 = Layer([ConstantSource()])
    o6.name = "Lazyflow Layer"
    o6.opacity = 1

    testVolume = numpy.random.rand(100, 100, 100, 3).astype("uint8")
    source = [ArraySource(testVolume)]
    o6._datasources = source
    model.append(o6)

    view = LayerWidget(None, model)
    view.show()
    view.updateGeometry()

    w = QWidget()
    lh = QHBoxLayout(w)
    lh.addWidget(view)

    up = QPushButton("Up")
    down = QPushButton("Down")
    delete = QPushButton("Delete")
    add = QPushButton("Add")
Пример #14
0
    def setupLayers(self):
        layers = []

        op = self.topLevelOperatorView

        ravelerLabelsSlot = op.RavelerLabels
        if ravelerLabelsSlot.ready():
            colortable = []
            for _ in range(256):
                r, g, b = numpy.random.randint(0, 255), numpy.random.randint(
                    0, 255), numpy.random.randint(0, 255)
                colortable.append(QColor(r, g, b).rgba())
            ravelerLabelLayer = ColortableLayer(
                LazyflowSource(ravelerLabelsSlot), colortable, direct=True)
            ravelerLabelLayer.name = "Raveler Labels"
            ravelerLabelLayer.visible = False
            ravelerLabelLayer.opacity = 0.4
            layers.append(ravelerLabelLayer)

        supervoxelsSlot = op.Supervoxels
        if supervoxelsSlot.ready():
            colortable = []
            for i in range(256):
                r, g, b = numpy.random.randint(0, 255), numpy.random.randint(
                    0, 255), numpy.random.randint(0, 255)
                colortable.append(QColor(r, g, b).rgba())
            supervoxelsLayer = ColortableLayer(LazyflowSource(supervoxelsSlot),
                                               colortable)
            supervoxelsLayer.name = "Input Supervoxels"
            supervoxelsLayer.visible = False
            supervoxelsLayer.opacity = 1.0
            layers.append(supervoxelsLayer)

        def addFragmentSegmentationLayers(mslot, name):
            if mslot.ready():
                for index, slot in enumerate(mslot):
                    if slot.ready():
                        raveler_label = slot.meta.selected_label
                        colortable = []
                        for i in range(256):
                            r, g, b = numpy.random.randint(
                                0, 255), numpy.random.randint(
                                    0, 255), numpy.random.randint(0, 255)
                            colortable.append(QColor(r, g, b).rgba())
                        colortable[0] = QColor(0, 0, 0, 0).rgba()
                        fragSegLayer = ColortableLayer(LazyflowSource(slot),
                                                       colortable,
                                                       direct=True)
                        fragSegLayer.name = "{} #{} ({})".format(
                            name, index, raveler_label)
                        fragSegLayer.visible = False
                        fragSegLayer.opacity = 1.0
                        layers.append(fragSegLayer)

        addFragmentSegmentationLayers(op.MaskedSupervoxels,
                                      "Masked Supervoxels")
        addFragmentSegmentationLayers(op.FilteredMaskedSupervoxels,
                                      "Filtered Masked Supervoxels")
        addFragmentSegmentationLayers(op.HoleFilledSupervoxels,
                                      "Hole Filled Supervoxels")
        addFragmentSegmentationLayers(op.RelabeledSupervoxels,
                                      "Relabeled Supervoxels")

        mslot = op.EditedRavelerBodies
        for index, slot in enumerate(mslot):
            if slot.ready():
                raveler_label = slot.meta.selected_label
                # 0=Black, 1=Transparent
                colortable = [
                    QColor(0, 0, 0).rgba(),
                    QColor(0, 0, 0, 0).rgba()
                ]
                bodyMaskLayer = ColortableLayer(LazyflowSource(slot),
                                                colortable,
                                                direct=True)
                bodyMaskLayer.name = "Raveler Body Mask #{} ({})".format(
                    index, raveler_label)
                bodyMaskLayer.visible = False
                bodyMaskLayer.opacity = 1.0
                layers.append(bodyMaskLayer)

        finalSegSlot = op.FinalSupervoxels
        if finalSegSlot.ready():
            colortable = []
            for _ in range(256):
                r, g, b = numpy.random.randint(0, 255), numpy.random.randint(
                    0, 255), numpy.random.randint(0, 255)
                colortable.append(QColor(r, g, b).rgba())
            finalLayer = ColortableLayer(LazyflowSource(finalSegSlot),
                                         colortable)
            finalLayer.name = "Final Supervoxels"
            finalLayer.visible = False
            finalLayer.opacity = 0.4
            layers.append(finalLayer)

        inputSlot = op.InputData
        if inputSlot.ready():
            layer = GrayscaleLayer(LazyflowSource(inputSlot))
            layer.name = "WS Input"
            layer.visible = False
            layer.opacity = 1.0
            layers.append(layer)

        #raw data
        rawSlot = self.topLevelOperatorView.RawData
        if rawSlot.ready():
            raw5D = self.topLevelOperatorView.RawData.value
            layer = GrayscaleLayer(ArraySource(raw5D), direct=True)
            #layer = GrayscaleLayer( LazyflowSource(rawSlot) )
            layer.name = "raw"
            layer.visible = True
            layer.opacity = 1.0
            layers.append(layer)

        return layers
Пример #15
0
 def setUp(self):
     self.raw = np.random.randint(0, 100, (10, 3, 3, 128, 3))
     self.a = ArraySource(self.raw)
     self.ss = PlanarSliceSource(self.a, projectionAlongTZC)
Пример #16
0
from volumina.colortables import default16_new
from volumina.pixelpipeline.datasources import ArraySinkSource, ArraySource
from volumina.layer import ColortableLayer, GrayscaleLayer

from PyQt5.QtWidgets import QApplication

SHAPE = (1, 600, 800, 1, 1)  # volumina expects 5d txyzc

data_arr = (255 * numpy.random.random(SHAPE)).astype(numpy.uint8)
label_arr = numpy.zeros(SHAPE, dtype=numpy.uint8)

##-----
app = QApplication(sys.argv)
v = Viewer()

data_src = ArraySource(data_arr)
data_layer = GrayscaleLayer(data_src)
data_layer.name = "Raw"
data_layer.numberOfChannels = 1

label_src = ArraySinkSource(label_arr)
label_layer = ColortableLayer(label_src,
                              colorTable=default16_new,
                              direct=False)
label_layer.name = "Labels"
label_layer.ref_object = None

assert SHAPE == label_arr.shape == data_arr.shape
v.dataShape = SHAPE

v.layerstack.append(data_layer)
Пример #17
0
 def setupLayers( self, currentImageIndex ):
     layers = []
    
     def onButtonsEnabled(slot, roi):
         currObj = self._carvingApplet.topLevelOperator.opCarving[currentImageIndex].CurrentObjectName.value
         hasSeg  = self._carvingApplet.topLevelOperator.opCarving[currentImageIndex].HasSegmentation.value
         nzLB    = self._carvingApplet.topLevelOperator.opLabeling.NonzeroLabelBlocks[currentImageIndex][:].wait()[0]
         
         self.labelingDrawerUi.currentObjectLabel.setText("current object: %s" % currObj)
         self.labelingDrawerUi.save.setEnabled(currObj != "" and hasSeg)
         self.labelingDrawerUi.saveAs.setEnabled(currObj == "" and hasSeg)
         #rethink this
         #self.labelingDrawerUi.segment.setEnabled(len(nzLB) > 0)
         #self.labelingDrawerUi.clear.setEnabled(len(nzLB) > 0)
     self._carvingApplet.topLevelOperator.opCarving[currentImageIndex].CurrentObjectName.notifyDirty(onButtonsEnabled)
     self._carvingApplet.topLevelOperator.opCarving[currentImageIndex].HasSegmentation.notifyDirty(onButtonsEnabled)
     self._carvingApplet.topLevelOperator.opLabeling.NonzeroLabelBlocks[currentImageIndex].notifyDirty(onButtonsEnabled)
     
     # Labels
     labellayer, labelsrc = self.createLabelLayer(currentImageIndex, direct=True)
     if labellayer is not None:
         layers.append(labellayer)
         # Tell the editor where to draw label data
         self.editor.setLabelSink(labelsrc)
    
     #segmentation 
     seg = self._carvingApplet.topLevelOperator.opCarving.Segmentation[currentImageIndex]
     
     #seg = self._carvingApplet.topLevelOperator.opCarving[0]._mst.segmentation
     #temp = self._done_lut[self._mst.regionVol[sl[1:4]]]
     if seg.ready(): 
         #source = RelabelingArraySource(seg)
         #source.setRelabeling(numpy.arange(256, dtype=numpy.uint8))
         colortable = [QColor(0,0,0,0).rgba(), QColor(0,0,0,0).rgba(), QColor(0,255,0).rgba()]
         for i in range(256-len(colortable)):
             r,g,b = numpy.random.randint(0,255), numpy.random.randint(0,255), numpy.random.randint(0,255)
             colortable.append(QColor(r,g,b).rgba())
             
         #layer = DirectColorTableLayer(seg, colortable, lazyflow=True)
         layer = ColortableLayer(LazyflowSource(seg), colortable, direct=True)
         layer.name = "segmentation"
         layer.visible = True
         layer.opacity = 0.3
         layers.append(layer)
     
     #done 
     done = self._carvingApplet.topLevelOperator.opCarving.DoneObjects[currentImageIndex]
     if done.ready(): 
         colortable = [QColor(0,0,0,0).rgba(), QColor(0,0,255).rgba()]
         for i in range(254-len(colortable)):
             r,g,b = numpy.random.randint(0,255), numpy.random.randint(0,255), numpy.random.randint(0,255)
             colortable.append(QColor(r,g,b).rgba())
         #have to use lazyflow because it provides dirty signals
         #layer = DirectColorTableLayer(done, colortable, lazyflow=True)
         layer = ColortableLayer(LazyflowSource(done), colortable, direct=True)
         layer.name = "done"
         layer.visible = False
         layer.opacity = 0.5
         layers.append(layer)
         
     doneSeg = self._carvingApplet.topLevelOperator.opCarving.DoneSegmentation[currentImageIndex]
     if doneSeg.ready(): 
         layer = ColortableLayer(LazyflowSource(doneSeg), self._doneSegmentationColortable, direct=True)
         layer.name = "done seg"
         layer.visible = False
         layer.opacity = 0.5
         self._doneSegmentationLayer = layer
         layers.append(layer)
         
     #supervoxel
     sv = self._carvingApplet.topLevelOperator.opCarving.Supervoxels[currentImageIndex]
     if sv.ready():
         for i in range(256):
             r,g,b = numpy.random.randint(0,255), numpy.random.randint(0,255), numpy.random.randint(0,255)
             colortable.append(QColor(r,g,b).rgba())
         #layer = DirectColorTableLayer(sv, colortable, lazyflow=True)
         layer = ColortableLayer(LazyflowSource(sv), colortable, direct=True)
         layer.name = "supervoxels"
         layer.visible = False
         layer.opacity = 1.0
         layers.append(layer)
     
     #
     # load additional layer: features / probability map
     #
     import h5py
     f = h5py.File("pmap.h5")
     pmap = f["data"].value
     
     #
     # here we load the actual raw data from an ArraySource rather than from a LazyflowSource for speed reasons
     #
     raw = self._carvingApplet.topLevelOperator.opCarving[0]._mst.raw
     raw5D = numpy.zeros((1,)+raw.shape+(1,), dtype=raw.dtype)
     raw5D[0,:,:,:,0] = raw[:,:,:]
     #layer = DirectGrayscaleLayer(raw5D)
     layer = GrayscaleLayer(ArraySource(raw5D), direct=True)
     layer.name = "raw"
     layer.visible = True
     layer.opacity = 1.0
     #layers.insert(1, layer)
     layers.append(layer)
         
     return layers