Exemple #1
0
    def blend_bg(self, bg, weight=0.5):
        if weight > 1 or weight < 0:
            raise GridError("weight must be between 0 and 1")

        if bg.ndim == 3:
            bg = rgb2uint(bg)
            logger.warn('3-channel image convert to 8-bit uint')

        if bg.shape != self.shape:
            xf, yf = self.shape
            try:
                bg = crop(bg, 0, 0, xf, yf)
            except Exception as E:
                raise GridError('bg shape %s did not match grid shape %s and '
                                'cropping failed with: %s' %
                                (bg.shape, self.shape, E.message))
            else:
                logger.warn("bg image cropped to grid dimensions %s" %
                            self.shape)

        # Normalize the values to balance weight sum
        scale = bg.max() / self.zz.max()
        zzout = self.zz * scale
        alpha = 1 - weight

        return (weight * zzout + (alpha * bg))  #/ scale
Exemple #2
0
    def zoom_bg(self, *coords, **kwds):
        """ Zoom in on current image and set the zoomed background as the 
        background of a new canvas.  Note that because indicies will always 
        resume at 0, particle positions will not maintain their relative 
        positions.
        """
        # avoid set_bg() because uses size of coords, not coords itself
        inplace = kwds.pop('inplace', False)
        autogrid = kwds.pop('autogrid', True)
        
        if inplace:
            cout = self
        else:
            cout = Canvas.copy(self)          

        cout._background = crop(cout._background, coords)
        cout.rez = cout._background.shape[0:2]        
        if autogrid:
            xmag = self.rx / float(cout.rx) 
            ymag = self.ry / float(cout.ry) 
            
            cout.grid.xdiv = rint(self.grid.xdiv / xmag)
            cout.grid.ydiv = rint(self.grid.ydiv / ymag)

        if not inplace:
            return cout        
Exemple #3
0
def load(f, rez=None):
    """Load an image file located in the data directory.

    Parameters
    ----------
    f : string
        File name.
    
    rez : (int, int) or None
        Crop image to desired length by width.

    Returns
    -------
    img : ndarray
        Image loaded from skimage.data_dir.
    """
    img = imread(op.join(data_dir, f))
    if rez:
        rx, ry = rez
        img = crop(img, (0, 0, rx, ry))
    return img
Exemple #4
0
def load(f, rez=None):
    """Load an image file located in the data directory.

    Parameters
    ----------
    f : string
        File name.
    
    rez : (int, int) or None
        Crop image to desired length by width.

    Returns
    -------
    img : ndarray
        Image loaded from skimage.data_dir.
    """
    img = imread(op.join(data_dir, f))
    if rez:
        rx, ry = rez
        img = crop(img, (0,0,rx,ry))
    return img
Exemple #5
0
    def blend_bg(self, bg, weight=0.5):
        if weight > 1 or weight < 0:
            raise GridError("weight must be between 0 and 1")

        if bg.ndim == 3:
            bg = rgb2uint(bg)
            logger.warn('3-channel image convert to 8-bit uint')

        if bg.shape != self.shape:
            xf, yf = self.shape
            try:
                bg = crop(bg, 0, 0, xf, yf)
            except Exception as E:
                raise GridError('bg shape %s did not match grid shape %s and '
                                'cropping failed with: %s' % (bg.shape, self.shape, E.message))
            else:
                logger.warn("bg image cropped to grid dimensions %s" % self.shape)

        # Normalize the values to balance weight sum
        scale = bg.max() / self.zz.max()
        zzout = self.zz * scale 
        alpha = 1-weight

        return (weight * zzout + ( alpha  * bg) ) #/ scale 
Exemple #6
0
    def patchshow(self, *args, **kwargs):
        """ ...
        args/kwargs include alpha, edgecolors, linestyles 

        Notes:
        Matplotlib API is setup that args or kwargs can be entered.  Order is
        important for args, but the correspond to same kwargs.
        """

        axes, kwargs = _parse_ax(*args, **kwargs)	
        
        title = kwargs.pop('title', None)        
        bgonly = kwargs.pop('bgonly', False)
        annotate = kwargs.pop('annotate', False)
        zoom = kwargs.pop('zoom', None)

        grid = kwargs.pop('grid', False)
        gcolor = kwargs.pop('gcolor', None)
        gstyle = kwargs.pop('gstyle', None)
        gunder = kwargs.pop('gunder',False)
        pmap = kwargs.pop('pmap', None)
        nolabel = kwargs.pop('nolabel', None)
        
        alpha = kwargs.get('alpha', None)
        edgecolor = kwargs.get('edgecolor', None)
        linewidth = kwargs.get('linewidth', None)
        linestyle = kwargs.get('linestyle', None)

        # Some keywords to savefig; not all supported
        save = kwargs.pop('save', None)
        dpi = kwargs.pop('dpi', None)
        bbox_inches = kwargs.pop('bbox_inches', None)
        
        # GET NOT POP
        cmap = kwargs.get('cmap', None)       
        
        # Implement later
        if cmap in ['pbinary', 'pbinary_r']:
            raise CanvasPlotError('"pbinary(_r)" color map only valid for .show()')
        
        # grid defaults
        if gcolor or gunder or gstyle and not grid:
            grid = True
            
        # If user enters gcolor/gstyle, assume default grid
        if grid and not gcolor:
            gcolor = GCOLOR       
            
        if grid and not gstyle:
            gstyle = 'solid'        
        
        # Corner case, don't touch
        if pmap and cmap and bgonly:
            bgonly = False
        
        if bgonly and not cmap: 
            raise CanvasPlotError('"bgonly" is only valid when a colormap is' 
            ' passed.')

        if cmap:
            bg = self.graybackground
        else:
            bg = self.background
            
        if zoom:
            xi, yi, xf, yf = zoom
            bg = crop(bg, zoom) 
                        
        #Overwrite axes image
        if not axes:
            fig, axes = plt.subplots()
        else:
            axes.images=[]
        # DONT PASS ALL KWARGS
        axes.imshow(bg, cmap=cmap)

        # FOR PATICLES IN IMAGE ONLY.
        in_and_edges = self.pin + self.pedge
        
        # PARTICLE FACECOLOR, ALPHA and other PATCH ARGS
        # http://matplotlib.org/api/artist_api.html#matplotlib.patches.Patch
        patches = [p.particle.as_patch(facecolor=p.color, alpha=alpha, 
                    edgecolor=edgecolor, linestyle=linestyle, linewidth=linewidth)
                   for p in in_and_edges]

        # If no particles or grid, just pass to avoid deep mpl exceptiosn
        if patches or grid:
            if patches:
                if pmap:
                    kwargs['cmap'] = pmap               
                if 'cmap' in kwargs and not bgonly:
                    ppatch = PatchCollection(patches, **kwargs) #cmap and Patch Args
                    ppatch.set_array(np.arange(len(patches)))        
        
                # Use settings passed to "patches"
                else:                                                  
                    ppatch = PatchCollection(patches, match_original=True, **kwargs) #
        
            # Grid under particles
            if gunder:
                axes.add_collection(self.grid.as_patch(
                    edgecolors=gcolor, linestyles=gstyle))
                if patches:
                    axes.add_collection(ppatch)
            # Grid over particles
            else:
                if patches:
                    axes.add_collection(ppatch)          
                if grid:
                    axes.add_collection(self.grid.as_patch(
                        edgecolors=gcolor, linestyles=gstyle))    
        
        axes = self._annotate_plot(axes, annotate, title)    
        
        if zoom:
            axes.set_xlim(xi, xf)
            axes.set_ylim(yf, yi)
        
        if nolabel:
            axes.xaxis.set_visible(False)
            axes.yaxis.set_visible(False)
            if nolabel == 'x':
                axes.yaxis.set_visible(True)
            elif nolabel == 'y':
                axes.xaxis.set_visible(True)        
        
        if save:
            path = _parse_path(save)
            plt.savefig(path, dpi=dpi, bbox_inches=bbox_inches)
        return axes
Exemple #7
0
    
if __name__ == '__main__':
    import matplotlib.pyplot as plt

    from skimage.io import imread
    from pyparty.utils import crop
#    img = imread('/home/glue/Desktop/imgproc_supplemental/images/Test_Data/Ilastik_Analysis_Final/class_10_labels/Noise_class_10labels_modified.png')
    from pyparty.data import nanolabels
    img = nanolabels()
#    print ptools.unique(img)

  #  plt.imshow(img, cmap='spectral')
 #   plt.show()

    img = crop(img, (0,0,512,512))
    mc = MultiCanvas.from_labeled(img, 'gay', 'f*g',
                                  storecolors=False, 
                                  ignore=0,
                                  #mapper=[ 
                                      #('singles', 1),
                                      #('dimers', 2),
                                      #('trimer', 3),
                                      #('bigs',  4)
                                      #],
                                  )
    
                                  
    mc.show(annotate=False, names=True, nolabel=True)
#   plt.imshow(nanolabels())
    plt.show()