Example #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
Example #2
0
def multi_mask(img, *names, **kwargs):
    """ Return a list/tuple/generator of masks of an image, one for each unique
    label found in a colored img. EVERYTHING DOWN-CONVERTED TO UINT: NECESSARY
    FOR MORPHOLOGY.LABELS ANYWAY, ALTHOUGH POSSIBLY SHOULD DO RGB2GRAY OR 255
    LABELS IS MAX"""
    
    astype = kwargs.pop('astype', tuple)
    ignore = kwargs.pop('ignore', 'black')
    names = list(names)    
    
    # THIS WILL DRASTICALLY REDUCE NUMBER OF UNIQUE LABELS ALLOWED RIGHT? 
    # SINCE IT ONLY HAS 255 POSSIBLE VALUES?!
    if img.ndim == 3:
        img = putil.rgb2uint(img, warnmsg=True)
    
    # Labels requires on grayscale; npunique also doesn't play nice w/ rgb
    
    if ignore == 'black' or ignore == (0,0,0):
        ignore = 0

    elif ignore == 'white' or ignore == (1,1,1):
        ignore = 255
    
    unique = ptools.unique(img)
    
    if ignore not in unique:
        logger.warn("Ignore set to %s but was not found on image." % ignore)
    else:
        unique = [v for v in unique if v != ignore]
        
    names = _parse_names(names, unique)
            
    # Make the mask dict as generator
    out = ((str(names[idx]), (img==v)) for idx, v in enumerate(unique))
    return putil._parse_generator(out, astype)
Example #3
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 
Example #4
0
 def graybackground(self):
     return rgb2uint(self.background)
Example #5
0
 def grayimage(self):
     """ Collapse multi-channel, scale to 255 (via ubyte) """
     return rgb2uint(self.image)
Example #6
0
    def show(self, *args, **kwargs):
        """ Wrapper to imshow.  Converts to gray to allow color maps.
        
        Notes
        -----
        Differs from patchshow in that the collective image (bg, grid, particles)
        is a series of masks, so they have to be drawn onto a single ndarray and 
        then plotted.  Sicne patchshow is writing patchs, it can plot the background
        separate from the grid and particles, which is slightly easier"""

        # This will pull out "ax", leaving remaing args/kwargs
        axes, kwargs = _parse_ax(*args, **kwargs)
        title = kwargs.pop('title', None)
        save = kwargs.pop('save', None)
        bgonly = kwargs.pop('bgonly', False)
        annotate = kwargs.pop('annotate', False)
        
        grid = kwargs.pop('grid', False)
        gcolor = kwargs.pop('gcolor', None)
        gunder = kwargs.pop('gunder', False)
        gstyle = kwargs.pop('gstyle', None) #NOT USED
        nolabel = kwargs.pop('nolabel', False)
        zoom = kwargs.pop('zoom', None)
        
        if gstyle:
            raise CanvasPlotError('"gstyle" only valid for patchshow()')
        
        if 'pmap' in kwargs:
            raise CanvasPlotError('"pmap" is only valid for patchshow() method')
        
        PBINARY = False
        if 'cmap' in kwargs:
            if kwargs['cmap'] == 'pbinary' or kwargs['cmap'] == 'pbinary_r':
                PBINARY = kwargs['cmap']
                del kwargs['cmap']
        
        # Get the background
        if bgonly: 
            if 'cmap' not in kwargs:
                raise CanvasPlotError('"bgonly" is only valid when a colormap is' 
                ' passed.')
            bg = kwargs['cmap'](self.graybackground)[... , :3]
            del kwargs['cmap']

        else:
            bg = self.background
            if PBINARY:
                if PBINARY == 'pbinary_r':
                    bg = np.ones(bg.shape).astype(bool)
                else:
                    bg = np.zeros(bg.shape).astype(bool)
                              
        # grid overlay
        if gcolor or gunder and not grid:
            grid = True
            
        # If user enters gcolor, assume default grid
        if grid and not gcolor:
            gcolor = GCOLOR
        
        # Map attributes from grid (centers, corners, grid)
        gattr = np.zeros(bg.shape).astype(bool)  #IE pass
        if grid:
            if not gcolor:
                gcolor = GCOLOR
            if grid == True:
                grid = 'grid'

            # Validate grid keyword
            try:
                gattr=getattr( self.grid, grid.lower() )
            except Exception:
                raise CanvasPlotError('Invalid grid argument, "%s".  Choose from:  '
                    'True, "grid", "centers", "corners", "hlines", "vlines"' 
                    % grid)            
            gcolor = to_normrgb(gcolor)
                                  
        #Draw grid over or under?            
        if gunder:
            bg[gattr] = gcolor
            image = self._draw_particles(bg, force_binary=PBINARY)
        else:
            image = self._draw_particles(bg, force_binary=PBINARY)
            image[gattr] = gcolor
            
                        
        # GRAY CONVERT
        if 'cmap' in kwargs:
            image = rgb2uint(image)           
            
            
        # Matplotlib
        if axes:
            axes.imshow(image, **kwargs)
        else:     
            axes = plt.imshow(image, **kwargs).axes         
            
        axes = self._annotate_plot(axes, annotate, title)            
        
        # SHOW DOESNT ACTUALLY CROP ANYTHING WHEN ZOOMING
        if zoom:
            xi, yi, xf, yf = 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)
            skimage.io.imsave(path, image)   
        return axes