Example #1
0
    def __setattr__(self, attr, value):
        """ Defer attribute calls to to self.particle unless overwriting
        name, color etc... 
        """

        if attr == 'color':
            MetaParticle.__dict__['color'].__set__(self, to_normrgb(value))

        elif attr == 'name':
            MetaParticle.__dict__['name'].__set__(self, str(value))

        elif attr == 'particle':
            if not isinstance(value, Particle):
                raise ParticleError(
                    'MetaParticle requires instance of Particle'
                    ' recieved %s' % type(value))

            MetaParticle.__dict__['particle'].__set__(self, value)

        elif attr in CUSTOM_DESCRIPTORS or attr in SKIMAGE_DESCRIPTORS:
            raise ParticleError("%s already reserved name for particle:"
                                " descriptor setting is not allowed." % attr)

        else:
            setattr(self.particle, attr, value)
Example #2
0
    def __init__(self, name="", color="", particle=""):

        self.name = str(name)
        self.color = to_normrgb(color)
        if not isinstance(particle, Particle):
            raise ParticleError("MetaParticle requires instance of Particle" " recieved %s" % type(particle))
        self.particle = particle
Example #3
0
    def __init__(self, name='', color='', particle=''):

        self.name = str(name)
        self.color = to_normrgb(color)
        if not isinstance(particle, Particle):
            raise ParticleError('MetaParticle requires instance of Particle'
                                ' recieved %s' % type(particle))
        self.particle = particle
Example #4
0
def from_color_res(color, resx, resy=None):
    """ Constant image of resolution (resx, resy) """
    if not resy:
        resy = resx
    background = np.empty((int(resx), int(resy), 3))

    color = to_normrgb(color)
    background[:, :, :] = color
    return background
Example #5
0
def from_color_res(color, resx, resy=None):
    """ Constant image of resolution (resx, resy) """
    if not resy:
        resy = resx
    background = np.empty( (int(resx), int(resy), 3) )

    color = to_normrgb(color)
    background[:,:,:] = color
    return background        
Example #6
0
def _parse_intensity(img, intensity):
    """ Validate intensity to any pyparty color/intensity, then grayconvert
    if image is gray.  Allows for 'red' to be valid noise for example"""

    if isinstance(intensity, np.ndarray):
        raise NoiseError('Intensity/color cannot be an array.')
    intensity = to_normrgb(intensity)
    if img.ndim == 2:
        r,g,b = intensity
        intensity = 0.2125 * r + 0.7154 * g + 0.0721 * b
    return intensity        
Example #7
0
 def random_circles(cls, n=50, rmin=5, rmax=50, background=BGCOLOR, pcolor=None):
     """ Return a canvas populated with n randomly positioned circles.  
     Radius ranges vary randomly between 5 and 50."""
     from random import randint as RIT
                    
     particles = ParticleManager()            
     # Randomize particle centers within the image default dimensions
     for i in range(n):
         cx, cy = RIT(0, BGRES[0]), RIT(0, BGRES[1])
         radius = RIT(rmin,rmax)
         particles.add('circle', center=(cx,cy), radius=radius, 
                       color=to_normrgb(pcolor))
     
     # Use default resolution and grid
     return cls(background=background, particles=particles)
Example #8
0
 def random_triangles(cls, n=50, lmin=5, lmax=50, background=BGCOLOR, pcolor=None):
     """ Return a canvas populated with n randomly positioned circles.  
     Radius ranges vary randomly between 5 and 50."""
     from random import randint as RIT
                    
     particles = ParticleManager()            
     # Randomize particle centers within the image default dimensions
     for i in range(n):
         # ADD PADDING ADHOC AT THE MOMENT!!
         PAD = 2*lmax
         cx, cy = RIT(0+PAD, BGRES[0]-PAD), RIT(0+PAD, BGRES[1]-PAD)
         length = RIT(lmin,lmax)
         particles.add('triangle', center=(cx,cy), length=length, 
                       color=to_normrgb(pcolor))
     
     # Use default resolution and grid
     return cls(background=background, particles=particles)
Example #9
0
    def __setattr__(self, attr, value):
        """ Defer attribute calls to to self.particle unless overwriting
        name, color etc... 
        """

        if attr == "color":
            MetaParticle.__dict__["color"].__set__(self, to_normrgb(value))

        elif attr == "name":
            MetaParticle.__dict__["name"].__set__(self, str(value))

        elif attr == "particle":
            if not isinstance(value, Particle):
                raise ParticleError("MetaParticle requires instance of Particle" " recieved %s" % type(value))

            MetaParticle.__dict__["particle"].__set__(self, value)

        elif attr in CUSTOM_DESCRIPTORS or attr in SKIMAGE_DESCRIPTORS:
            raise ParticleError("%s already reserved name for particle:" " descriptor setting is not allowed." % attr)

        else:
            setattr(self.particle, attr, value)
Example #10
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
Example #11
0
import skimage.io
import skimage.measure as measure
import skimage.morphology as morphology

import pyparty.background.bg_utils as bgu
from pyparty.shape_models.abstract_shape import ParticleError
from pyparty.tools.thresholding import choose_thresh
from pyparty.tools.manager import ParticleManager, concat_particles
from pyparty.tools.grids import Grid, CartesianGrid
from pyparty.utils import coords_in_image, where_is_particle, to_normrgb, \
     any2rgb, crop, _parse_ax, _parse_path, mem_address, rgb2uint
from pyparty.config import BGCOLOR, BGRES, GRIDXSPACE, GRIDYSPACE, _PAD, \
     GCOLOR, THRESHDEF
# Ensure colors are correctly mapped
BGCOLOR, GCOLOR = to_normrgb(BGCOLOR), to_normrgb(GCOLOR)

logger = logging.getLogger(__name__) 

def rint(x): return int(round(x,0))

#def inplace(method):
    #""" Thought I could decorate methods that have inplace keyword, but turned
    #out to be more than I bargained for.  Decorator syntax is fine, but not correct.
    #"""
    #methodname = method.__name__
    ##variables = method.func_code.co_varnames
    #@wraps(method)
    #def wrapper(obj, *args, **kwargs):
        #print 'method is', method, type(obj), type(method)
        #inplace = kwargs.pop('inplace', False)
Example #12
0
 def _color_changed(self, old, new):
     if new:
         self.color = to_normrgb(new)
Example #13
0
 def _color_changed(self, old, new):
     if new:
         self.color=to_normrgb(new)