Пример #1
0
    def plot_points(self, Channel='DeepBlue', periring=False,colormap='plasma' ,func=lambda x : x,**kwargs):
        """
        Parameters
        ----------
        Channel : [DeepBlue] str or list of strings
        periring : {[False], True} will error on Trueif periring wasnt calculated
        colormap : colormap to use for points
        func : transformation to color, i.e. np.log, logicle, or whatever

        Draws overlaying points colorcoded by intensity in current napari viewer
        """
        #assert self._tracked, str(pos) +' not tracked yet'

        from oyLabImaging.Processing.imvisutils import get_or_create_viewer
        viewer = get_or_create_viewer()
        try:
            pointsmat = self._pointmatrix
        except:
            self._calculate_pointmat()
            pointsmat = self._pointmatrix


        point_props = {'mean' : func(np.concatenate(self.mean(Channel,periring=periring))), 'ind' : np.concatenate(self.index)}
        pointlayer = viewer.add_points(pointsmat,properties=point_props, text='ind', face_color='mean',edge_width=0, face_colormap=colormap,  size=20,blending='translucent', scale=[1, self.PixelSize, self.PixelSize])
        return pointlayer
Пример #2
0
        def show_movie(self, Channel=['DeepBlue'], boxsize=75, cmaps = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow'] ,**kwargs):
            """
            Function to display a close up movie of a cell being tracked.
            Parameters
            ----------
            Channel : ['DeepBlue'] str or list of strs
            boxsize : [50] num size of box around the cell
            cmaps : order of colormaps for each channel
            """
            if type(Channel)==str:
                cmaps = ['gray']

            from oyLabImaging.Processing.imvisutils import get_or_create_viewer
            from oyLabImaging.Processing.improcutils import sample_stack

            viewer = get_or_create_viewer()
            viewer.scale_bar.unit = "um"
            cents = np.fliplr(self.centroid)
            #cents = self.centroid

            crp = list(map(tuple,np.ceil(np.concatenate((cents-boxsize, cents+boxsize),axis=1 )).astype(int)))

            for ind, ch in enumerate(Channel):
                #imgs = self._outer.img(ch, frame=list(self.T),verbose=False)
                #stk = np.array([np.pad(im1, boxsize)[crp1[0]+boxsize:crp1[2]+boxsize, crp1[1]+boxsize:crp1[3]+boxsize] for im1, crp1 in zip(imgs, crp)])

                stk = self._outer.img(ch, frame=list(self.frame()),crop=crp,verbose=False)

                stksmp = stk.flatten()#sample_stack(stk,int(stk.size/100))
                stksmp = stksmp[stksmp!=0]
                viewer.add_image(stk,blending='additive', contrast_limits=[np.percentile(stksmp,1),np.percentile(stksmp,99.9)],name=ch, colormap=cmaps[ind%len(cmaps)],scale=[self._outer.PixelSize, self._outer.PixelSize])
Пример #3
0
    def plot_tracks(self, J=None, **kwargs):
        """
        Parameters
        ----------
        J : track indices - plots all tracks if not provided


        Draws overlaying tracks in current napari viewer
        """
        assert self._tracked, str(pos) +' not tracked yet'

        from oyLabImaging.Processing.imvisutils import get_or_create_viewer
        viewer = get_or_create_viewer()
        trackmat, J = self._tracksmat(J=J)
        inds_to_include = self.trackinds[J]!=None
        track_props = {'cell_id' :list( self.trackinds[J][np.where(inds_to_include)]), 'cell_T' : np.where(inds_to_include)[1],}

        tracklayer = viewer.add_tracks(trackmat,blending='additive', scale=[self.PixelSize, self.PixelSize],properties=track_props)
        #tracklayer.display_id=True
        return tracklayer
Пример #4
0
    def plot_images(self, Channel='DeepBlue',Zindex=[0], frames=None, cmaps = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow'], **kwargs):
        """
        Parameters
        ----------
        Channel : [DeepBlue] str or list of strings
        Zindex : [0]

        Draws image stks in current napari viewer
        """
        if len(Channel)==1:
                cmaps = ['gray']
        if frames==None:
            frames = self.frames

        from oyLabImaging.Processing.imvisutils import get_or_create_viewer
        from oyLabImaging.Processing.improcutils import sample_stack
        viewer = get_or_create_viewer()
        viewer.scale_bar.unit = "um"
        viewer.scale_bar.font_size=16

        for ind, ch in enumerate(Channel):
            stk = self.img(Channel=ch,verbose=True,Zindex=Zindex , frames=frames, **kwargs)
            stksmp = sample_stack(stk,int(stk.size/1000))
            viewer.add_image(stk,blending='additive', contrast_limits=[np.percentile(stksmp,1),np.percentile(stksmp,99.9)], scale=[self.PixelSize, self.PixelSize], colormap=cmaps[ind%len(cmaps)] ,**kwargs)
Пример #5
0
    def track_explorer(R, keep_only=False):
        """
        Track explorer app. Written using magicgui (Thanks @tlambert03!)

        Allows one to easily browse through tracks, plot the data and see the corresponding movies. Can also be used for curation and quality control.

        Parameters:
        keep_only : [False] Bool - If true, only tracks that are in PosLbl.track_to_use will be loaded in a given position. This can be used to filter unwanted tracks before examining for quality with the explorer.
        """
        from typing import List
        import matplotlib
        import matplotlib.pyplot as plt
        import numpy as np
        from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
        from magicgui import magicgui
        from magicgui.widgets import Checkbox, PushButton, Container
        from oyLabImaging.Processing.imvisutils import get_or_create_viewer
        from scipy import stats
        from napari import run
        from natsort import natsorted

        cmaps = ['cyan', 'magenta', 'yellow', 'red', 'green', 'blue']
        viewer = get_or_create_viewer()

        matplotlib.use('Agg')
        mpl_fig = plt.figure()
        ax = mpl_fig.add_subplot(111)

        fc = FigureCanvasQTAgg(mpl_fig)

        #attr_list = ['area', 'convex_area','centroid','perimeter','eccentricity','solidity','inertia_tensor_eigvals', 'orientation'] #todo: derive list from F regioprops

        position = list(natsorted(R.PosLbls.keys()))[0]
        PosLbl0 = R.PosLbls[position]

        attr_list = [
            f for f in list(PosLbl0.framelabels[0].regionprops)
            if not f.startswith(('mean', 'median', 'max', 'min', '90th',
                                 'slice'))
        ]
        attr_cmap = plt.cm.get_cmap('tab20b', len(attr_list)).colors

        @magicgui(
            auto_call=True,
            position={
                "choices": natsorted([str(a) for a in R.PosLbls.keys()])
            },
            track_id={
                "choices":
                range(R.PosLbls[sorted([str(a) for a in R.PosLbls.keys()
                                        ])[0]].get_track(0).numtracks)
            },
            channels={
                "widget_type": "Select",
                "choices": list(R.channels)
            },
            features={
                "widget_type": "Select",
                "choices": attr_list
            },
        )
        def widget(position: List[str], track_id: int, channels: List[str],
                   features: List[str]):
            # preserving these parameters for things that the graphing function
            # needs... so that anytime this is called we have to graph.
            ...
            # do your graphing here
            PosLbl = R.PosLbls[position]
            t0 = PosLbl.get_track(track_id)
            ax.cla()
            ax.set_xlabel('Timepoint')
            ax.set_ylabel('kAU')
            ch_choices = widget.channels.choices
            for ch in channels:
                ax.plot(t0.T,
                        stats.zscore(t0.mean(ch)),
                        color=cmaps[ch_choices.index(ch)])

            f_choices = widget.features.choices
            for ch in features:
                feat_to_plot = eval("t0.prop('" + ch + "')")
                if np.ndim(feat_to_plot) == 1:
                    ax.plot(t0.T,
                            stats.zscore(feat_to_plot, nan_policy='omit'),
                            '--',
                            color=attr_cmap[f_choices.index(ch)],
                            alpha=0.33)
                else:
                    mini_cmap = plt.cm.get_cmap('jet',
                                                np.shape(feat_to_plot)[1])
                    for dim in np.arange(np.shape(feat_to_plot)[1]):
                        ax.plot(t0.T,
                                stats.zscore(feat_to_plot[:, dim],
                                             nan_policy='omit'),
                                '--',
                                color=mini_cmap(dim),
                                alpha=0.33)
                        #ax.plot(t0.T, feat_to_plot[:,dim],'--', color=mini_cmap(dim), alpha=0.25)

            ax.legend(channels + features)
            fc.draw()

        @widget.position.changed.connect
        def _on_position_changed():
            PosLbl = R.PosLbls[widget.position.value]
            try:
                PosLbl.track_to_use
            except:
                PosLbl.track_to_use = []
            viewer.layers.clear()
            #update track_id choices - bug in choices:
            if keep_only:
                J = PosLbl.track_to_use
            else:
                J = range(PosLbl.get_track(0).numtracks)
            widget.track_id.choices = []
            widget.track_id.choices = J
            #update keep_btn value
            #keep_btn.value= widget.track_id.value in PosLbl.track_to_use

        @widget.track_id.changed.connect
        def _on_track_changed(new_track: int):
            PosLbl = R.PosLbls[widget.position.value]
            viewer.layers.clear()
            keep_btn.value = widget.track_id.value in PosLbl.track_to_use
            #print("you cahnged to ", new_track)

        movie_btn = PushButton(text="Movie")
        widget.insert(1, movie_btn)

        @movie_btn.clicked.connect
        def _on_movie_clicked():
            PosLbl = R.PosLbls[widget.position.value]
            channels = widget.channels.get_value()
            track_id = widget.track_id.get_value()
            t0 = PosLbl.get_track(track_id)
            viewer.layers.clear()
            ch_choices = widget.channels.choices
            t0.show_movie(
                Channel=channels,
                cmaps=[cmaps[ch_choices.index(ch)] for ch in channels])

        btn = PushButton(text="NEXT")
        widget.insert(-1, btn)

        @btn.clicked.connect
        def _on_next_clicked():
            choices = widget.track_id.choices
            current_index = choices.index(widget.track_id.value)
            widget.track_id.value = choices[(current_index + 1) %
                                            (len(choices))]

        PosLbl = R.PosLbls[widget.position.value]
        try:
            PosLbl.track_to_use
        except:
            PosLbl.track_to_use = []

        keep_btn = Checkbox(text="Keep")
        keep_btn.value = widget.track_id.value in PosLbl.track_to_use
        widget.append(keep_btn)

        @keep_btn.clicked.connect
        def _on_keep_btn_clicked(value: bool):
            #print("keep is now", value)
            PosLbl = R.PosLbls[widget.position.value]
            if value == True:
                if widget.track_id.value not in PosLbl.track_to_use:
                    PosLbl.track_to_use.append(widget.track_id.value)
            if value == False:
                if widget.track_id.value in PosLbl.track_to_use:
                    PosLbl.track_to_use.remove(widget.track_id.value)
            R.PosLbls[widget.position.value] = PosLbl

        # widget.native
        # ... points to the underlying backend widget

        container = Container(layout='horizontal')

        # magicgui container expect magicgui objects
        # but we can access and modify the underlying QLayout
        # https://doc.qt.io/qt-5/qlayout.html#addWidget

        layout = container.native.layout()

        layout.addWidget(fc)
        layout.addWidget(widget.native)  # adding native, because we're in Qt

        #container.show(run=True)
        # OR

        viewer.window.add_dock_widget(container)
        #run()
        matplotlib.use('Qt5Agg')