示例#1
0
文件: __init__.py 项目: hmhme/Luc
def getFeatures(outDir, sizeThreshold=25, showImages=True):
    fList = os.listdir(outDir)
    fList = np.array(fList).take(
        np.argsort(map(lambda s: int(s.split('.')[0]), fList)))
    s = np.array([
        io.imread(outDir + f, as_grey=False, plugin=None, flatten=None)
        for f in fList
    ])
    stackSum = np.sum(s, axis=0)
    stackVar = np.var(s, axis=0)
    stackVar = filter.tv_denoise(stackVar, weight=300, eps=1e-5)
    stackSum = filter.tv_denoise(stackSum, weight=300, eps=1e-5)

    labeled_plants, center = findPlantsCanny(stackVar, stackSum)
    circles = center.map(getCircle)
    maxTrace = pandas.DataFrame([
        np.max(s[:, circles[i][:, 0], circles[i][:, 1]], axis=1)
        for i in set(labeled_plants.flat)
    ]).T
    wholeRegion = pandas.DataFrame([
        np.max(s[:,
                 np.where(labeled_plants == i)[0],
                 np.where(labeled_plants == i)[1]],
               axis=1) for i in set(labeled_plants.flat)
    ]).T
    traces = pandas.DataFrame([
        np.mean(s[:, circles[i][:, 0], circles[i][:, 1]], axis=1)
        for i in set(labeled_plants.flat)
    ]).T

    return labeled_plants, center, traces, maxTrace, wholeRegion
示例#2
0
 def test_tv_denoise_2d(self):
     """
     Apply the TV denoising algorithm on the lena image provided
     by scipy
     """
     # lena image
     lena = color.rgb2gray(data.lena())[:256, :256]
     # add noise to lena
     lena += 0.5 * lena.std() * np.random.randn(*lena.shape)
     # clip noise so that it does not exceed allowed range for float images.
     lena = np.clip(lena, 0, 1)
     # denoise
     denoised_lena = filter.tv_denoise(lena, weight=60.0)
     # which dtype?
     assert denoised_lena.dtype in [np.float, np.float32, np.float64]
     from scipy import ndimage
     grad = ndimage.morphological_gradient(lena, size=((3, 3)))
     grad_denoised = ndimage.morphological_gradient(
         denoised_lena, size=((3, 3)))
     # test if the total variation has decreased
     assert np.sqrt(
         (grad_denoised ** 2).sum()) < np.sqrt((grad ** 2).sum()) / 2
     denoised_lena_int = filter.tv_denoise(img_as_uint(lena),
                                           weight=60.0, keep_type=True)
     assert denoised_lena_int.dtype is np.dtype('uint16')
示例#3
0
 def test_tv_denoise_3d(self):
     """
     Apply the TV denoising algorithm on a 3D image representing
     a sphere.
     """
     x, y, z = np.ogrid[0:40, 0:40, 0:40]
     mask = (x - 22) ** 2 + (y - 20) ** 2 + (z - 17) ** 2 < 8 ** 2
     mask = 100 * mask.astype(np.float)
     mask += 60
     mask += 20 * np.random.randn(*mask.shape)
     mask[mask < 0] = 0
     mask[mask > 255] = 255
     res = filter.tv_denoise(mask.astype(np.uint8),
                             weight=100, keep_type=True)
     assert res.std() < mask.std()
     assert res.dtype is np.dtype('uint8')
     res = filter.tv_denoise(mask.astype(np.uint8), weight=100)
     assert res.std() < mask.std()
     assert res.dtype is not np.dtype('uint8')
     # test wrong number of dimensions
     a = np.random.random((8, 8, 8, 8))
     try:
         res = filter.tv_denoise(a)
     except ValueError:
         pass
 def test_tv_denoise_3d(self):
     """
     Apply the TV denoising algorithm on a 3D image representing
     a sphere.
     """
     x, y, z = np.ogrid[0:40, 0:40, 0:40]
     mask = (x -22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2
     mask = 100 * mask.astype(np.float)
     mask += 60
     mask += 20*np.random.randn(*mask.shape)
     mask[mask < 0] = 0
     mask[mask > 255] = 255
     res = filter.tv_denoise(mask.astype(np.uint8),
                             weight=100, keep_type=True)
     assert res.std() < mask.std()
     assert res.dtype is np.dtype('uint8')
     res = filter.tv_denoise(mask.astype(np.uint8), weight=100)
     assert res.std() < mask.std()
     assert res.dtype is not np.dtype('uint8')
     # test wrong number of dimensions
     a = np.random.random((8, 8, 8, 8))
     try:
         res = filter.tv_denoise(a)
     except ValueError:
         pass
示例#5
0
 def _canny_edge_fired(self):
     self.im = self.orig
     r,g,b = np.rollaxis(self.im,axis=-1)
     edge_r = canny(tv_denoise(r, weight=1))
     edge_g = canny(tv_denoise(g, weight=1))
     edge_b = canny(tv_denoise(b, weight=1))
     edges = edge_r + edge_g + edge_b
     self.im = np.dstack((edges,edges,edges))
     self.im[self.im > 0.] = 1.
     try:
         self.axes.imshow(self.im)
         self.figure.canvas.draw()
     except:
         pass        
示例#6
0
def estimate_shape(vol, cur_apix, apix=20, threshold=None, ret_all=False, **extra):
    ''' Get the basic shape of the object based on ellipsoid fitting
    
    :Parameters:
        
        vol : array
              Volume data
        cur_apix : float
                   Current pixel size of volume 
        apix : float
               Pixel size for downsampling
        threshold : float
                    Density threshold, default find automaticaly
        ret_all : bool
                  Return all the ellipse parameters, unscaled by pixel size
        extra : dict
                Unused keyword arguments
    :Returns:
        
        radii : tuple
                Radii of minimum volumn ellipse scaled by pixel size
    '''
    
    vol_sm = ndimage_interpolate.resample_fft_fast(vol, apix/cur_apix)
    apix=float(vol.shape[0])/vol_sm.shape[0]*cur_apix
    vol_sm = tv_denoise(vol_sm, weight=10, eps=2.e-4, n_iter_max=200)
    mask = ndimage_utility.tight_mask(vol_sm, threshold, 0, 0)[0]
    coords = numpy.vstack(numpy.unravel_index(numpy.nonzero(mask.ravel()), vol_sm.shape)).T.copy().astype(numpy.float32)
    if ret_all:
        return minimum_volume_ellipse(coords)
    return minimum_volume_ellipse(coords)[1]*apix*2.0
示例#7
0
def estimate_shape(vol, cur_apix, apix=20, threshold=None, ret_all=False, **extra):
    ''' Get the basic shape of the object based on ellipsoid fitting
    
    :Parameters:
        
        vol : array
              Volume data
        cur_apix : float
                   Current pixel size of volume 
        apix : float
               Pixel size for downsampling
        threshold : float
                    Density threshold, default find automaticaly
        ret_all : bool
                  Return all the ellipse parameters, unscaled by pixel size
        extra : dict
                Unused keyword arguments
    :Returns:
        
        radii : tuple
                Radii of minimum volumn ellipse scaled by pixel size
    '''
    
    vol_sm = ndimage_interpolate.resample_fft_fast(vol, apix/cur_apix)
    apix=float(vol.shape[0])/vol_sm.shape[0]*cur_apix
    vol_sm = tv_denoise(vol_sm, weight=10, eps=2.e-4, n_iter_max=200)
    mask = ndimage_utility.tight_mask(vol_sm, threshold, 0, 0)[0]
    coords = numpy.vstack(numpy.unravel_index(numpy.nonzero(mask.ravel()), vol_sm.shape)).T.copy().astype(numpy.float32)
    if ret_all:
        return minimum_volume_ellipse(coords)
    return minimum_volume_ellipse(coords)[1]*apix*2.0
示例#8
0
 def _denoise(self, img, weight):
     '''
         use TV-denoise to remove noise
         
         http://scipy-lectures.github.com/advanced/image_processing/
         http://en.wikipedia.org/wiki/Total_variation_denoising
     '''
     from skimage.filter import tv_denoise
     return tv_denoise(img, weight=weight).astype('uint8')
示例#9
0
    def classify(self,sample,fingerName,jointName):
        max=sample.max()
        sample=sample/max*255
        sample=sample.astype('uint8')
                 
        cropSamp=sample[self.windowSize[0]:self.windowSize[1],self.windowSize[2]:self.windowSize[3]]
        cropSamp=tv_denoise(cropSamp,weight=0.2)
        
        if self.verbose:
            plt.imshow(cropSamp,cmap=plt.cm.gray)
            plt.show()
        
        cropSamp=filter.hprewitt(cropSamp)

        if self.verbose:
            plt.imshow(cropSamp,cmap=plt.cm.gray)
            plt.show()
        
        #idx=cropSamp<0.08
        #cropSamp[idx]=0    
        
        if self.verbose:
            plt.imshow(cropSamp,cmap=plt.cm.gray)
            plt.show()
        
        scores = []
        for classImage in self.classImages:      
            classImage=tv_denoise(classImage,weight=0.2)
            classImage=filter.hprewitt(classImage)
            
            #idx=classImage<0.08
            #classImage[idx]=0 
            
            if False and self.verbose:
                plt.imshow(classImage,cmap=plt.cm.gray)
                plt.show()
            #do template matching
            score = match_template(classImage, cropSamp,1)
            scores.append(np.max(score))
        
        classification = self.classLabels[np.argmax(scores)]
        
        return classification
示例#10
0
 def test_tv_denoise_float_result_range(self):
     # lena image
     lena = color.rgb2gray(data.lena())[:256, :256]
     int_lena = np.multiply(lena, 255).astype(np.uint8)
     assert np.max(int_lena) > 1
     denoised_int_lena = filter.tv_denoise(int_lena, weight=60.0)
     # test if the value range of output float data is within [0.0:1.0]
     assert denoised_int_lena.dtype == np.float
     assert np.max(denoised_int_lena) <= 1.0
     assert np.min(denoised_int_lena) >= 0.0
 def test_tv_denoise_float_result_range(self):
     # lena image
     lena = color.rgb2gray(data.lena())[:256, :256]
     int_lena = np.multiply(lena, 255).astype(np.uint8)
     assert np.max(int_lena) > 1       
     denoised_int_lena = filter.tv_denoise(int_lena, weight=60.0)
     # test if the value range of output float data is within [0.0:1.0]
     assert denoised_int_lena.dtype == np.float
     assert np.max(denoised_int_lena) <= 1.0
     assert np.min(denoised_int_lena) >= 0.0        
示例#12
0
def getFeatures(outDir, sizeThreshold=25, showImages=True):
    fList = os.listdir(outDir)
    fList = np.array(fList).take(np.argsort(map(lambda s: int(s.split('.')[0]), 
                                                fList)))
    s = np.array([io.imread(outDir+f, as_grey=False, plugin=None, flatten=None) 
                 for f in fList])
    stackSum = np.sum(s, axis=0)
    stackVar = np.var(s, axis=0)
    stackVar = filter.tv_denoise(stackVar, weight=300, eps=1e-5)
    stackSum = filter.tv_denoise(stackSum, weight=300, eps=1e-5)

    labeled_plants, center = findPlantsCanny(stackVar, stackSum)
    circles = center.map(getCircle)
    maxTrace = pandas.DataFrame([np.max(s[:,circles[i][:,0],circles[i][:,1]],axis=1) 
                               for i in set(labeled_plants.flat)]).T
    wholeRegion = pandas.DataFrame([np.max(s[:,np.where(labeled_plants==i)[0],
                                             np.where(labeled_plants==i)[1]],axis=1) 
                               for i in set(labeled_plants.flat)]).T
    traces = pandas.DataFrame([np.mean(s[:,circles[i][:,0],circles[i][:,1]],axis=1) 
                               for i in set(labeled_plants.flat)]).T
                               
    return labeled_plants, center, traces, maxTrace, wholeRegion
示例#13
0
 def test_tv_denoise_2d(self):
     """
     Apply the TV denoising algorithm on the lena image provided
     by scipy
     """
     # lena image
     lena = color.rgb2gray(data.lena())[:256, :256]
     # add noise to lena
     lena += 0.5 * lena.std()*np.random.randn(*lena.shape)
     # clip noise so that it does not exceed allowed range for float images.
     lena = np.clip(lena, 0, 1)
     # denoise
     denoised_lena = filter.tv_denoise(lena, weight=60.0)
     # which dtype?
     assert denoised_lena.dtype in [np.float, np.float32, np.float64]
     from scipy import ndimage
     grad = ndimage.morphological_gradient(lena, size=((3,3)))
     grad_denoised = ndimage.morphological_gradient(denoised_lena, size=((3,3)))
     # test if the total variation has decreased
     assert np.sqrt((grad_denoised**2).sum()) < np.sqrt((grad**2).sum()) / 2
     denoised_lena_int = filter.tv_denoise(img_as_uint(lena),
                                           weight=60.0, keep_type=True)
     assert denoised_lena_int.dtype is np.dtype('uint16')
示例#14
0
 def Psi(x, threshold):
     """
     Deblurring operator.
     
     Arguments:
     ----------
     x : array-like, shape = [m, n]
         Estimated signal
        
     threshold : float
         Threshold for the deblurring algorithm
     """
 
     img_estimated = tv_denoise(x, weight=threshold/2, n_iter_max=4)
 
     return img_estimated
示例#15
0
def tight_mask(vol,
               threshold=None,
               ndilate=0,
               sm_size=3,
               sm_sigma=3.0,
               disable_filter=False,
               **extra):
    ''' Generate a tight mask for the given volume
        
    :Parameters:
    
        vol : array
              Input volume
        threshold : float, optional
                    Threshold for density or None for auto threshold
        ndilate : int
                  Number of times to dilate the mask
        sm_size : int
                  Size of the real space Gaussian kernel (must be odd!)
        sm_sigma : float
                   Width of the real space Gaussian kernel
        disable_prefilter : bool
                            Disable pre filtering
        extra : dict
                Unused key word arguments
    :Returns:
    
        mask : array
               Tight mask
    '''

    if sm_size > 0 and (sm_size % 2) == 0: sm_size += 1
    try:
        threshold = float(threshold)
    except:
        threshold = None
    if not disable_filter:
        fvol = tv_denoise(vol, weight=10, eps=2.e-4, n_iter_max=200)
    else:
        fvol = vol
    mask, th = ndimage_utility.tight_mask(fvol, threshold, ndilate, sm_size,
                                          sm_sigma)
    _logger.info("Determined threshold=%f" % th)
    return mask
示例#16
0
def estimate_diameter(vol, cur_apix, apix=10, threshold=None, **extra):
    ''' Estimate the diameter of the object
    
    :Parameters:
        
        vol : array
              Volume data
        cur_apix : float
                   Current pixel size of volume 
        apix : float
               Pixel size for downsampling
        threshold : float
                    Density threshold, default find automaticaly
        extra : dict
                Unused keyword arguments
    :Returns:
        
        radii : float
                Maximum diameter of the object
    '''

    vol_sm = ndimage_interpolate.resample_fft_fast(vol, apix / cur_apix)
    vol_sm = tv_denoise(vol_sm, weight=10, eps=2.e-4, n_iter_max=200)
    apix = float(vol.shape[0]) / vol_sm.shape[0] * cur_apix
    mask = ndimage_utility.tight_mask(vol_sm, threshold, 0, 0)[0]
    mask2 = scipy.ndimage.binary_dilation(
        mask, scipy.ndimage.generate_binary_structure(mask.ndim, 2), 1)
    coords = numpy.vstack(
        numpy.unravel_index(numpy.nonzero(mask.ravel()),
                            mask.shape)).T.copy().astype(numpy.float32)
    try:
        diameter = distance.max_euclidiean_dist(coords)
    except:
        _logger.error("%s -- %s" % (str(coords.shape), str(coords.dtype)))
        raise

    if 1 == 0:
        radii = getMinVolEllipse(coords)[1]
        print radii.max() / radii.min()

    return diameter * apix
示例#17
0
def estimate_diameter(vol, cur_apix, apix=10, threshold=None, **extra):
    ''' Estimate the diameter of the object
    
    :Parameters:
        
        vol : array
              Volume data
        cur_apix : float
                   Current pixel size of volume 
        apix : float
               Pixel size for downsampling
        threshold : float
                    Density threshold, default find automaticaly
        extra : dict
                Unused keyword arguments
    :Returns:
        
        radii : float
                Maximum diameter of the object
    '''
    
    vol_sm = ndimage_interpolate.resample_fft_fast(vol, apix/cur_apix)
    vol_sm = tv_denoise(vol_sm, weight=10, eps=2.e-4, n_iter_max=200)
    apix=float(vol.shape[0])/vol_sm.shape[0]*cur_apix
    mask = ndimage_utility.tight_mask(vol_sm, threshold, 0, 0)[0]
    mask2 = scipy.ndimage.binary_dilation(mask, scipy.ndimage.generate_binary_structure(mask.ndim, 2), 1)
    coords = numpy.vstack(numpy.unravel_index(numpy.nonzero(mask.ravel()), mask.shape)).T.copy().astype(numpy.float32)
    try:
        diameter=distance.max_euclidiean_dist(coords)
    except:
        _logger.error("%s -- %s"%(str(coords.shape), str(coords.dtype)))
        raise
    
    if 1 == 0:
        radii = getMinVolEllipse(coords)[1]
        print radii.max()/radii.min()
        
    return diameter*apix
import numpy as np
import scipy
import matplotlib.pyplot as plt
from skimage.filter import tv_denoise

l = scipy.misc.lena()
l = l[230:290, 220:320]

noisy = l + 0.4*l.std()*np.random.random(l.shape)

tv_denoised = tv_denoise(noisy, weight=10)


plt.figure(figsize=(12, 2.8))

plt.subplot(131)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('noisy', fontsize=20)
plt.subplot(132)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('TV denoising', fontsize=20)

tv_denoised = tv_denoise(noisy, weight=50)
plt.subplot(133)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('(more) TV denoising', fontsize=20)

plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0,
"""
This example compares several denoising filters available in scikit-image:
a Gaussian filter, a median filter, and total variation denoising.
"""

import matplotlib.pyplot as plt
from skimage import data
from skimage import filter
from scipy import ndimage

coins = data.coins()
gaussian_filter_coins = ndimage.gaussian_filter(coins, sigma=2)
med_filter_coins = filter.median_filter(coins)
tv_filter_coins = filter.tv_denoise(coins, weight=0.1)

plt.figure(figsize=(16, 4))
plt.subplot(141)
plt.imshow(coins[10:80, 300:370], cmap='gray', interpolation='nearest')
plt.axis('off')
plt.title('Image')
plt.subplot(142)
plt.imshow(gaussian_filter_coins[10:80, 300:370],
           cmap='gray',
           interpolation='nearest')
plt.axis('off')
plt.title('Gaussian filter')
plt.subplot(143)
plt.imshow(med_filter_coins[10:80, 300:370],
           cmap='gray',
           interpolation='nearest')
plt.axis('off')
示例#20
0
def filter_volume_lowpass(filename, spi, sp, filter_type=2, fermi_temp=0.0025, bw_pass=0.05, bw_stop=0.05, reg=0.006, outputfile=None, **extra):
    ''' Low-pass filter the specified volume
    
    :Parameters:
    
    filename : str
               Filename of the input volume
    spi : spider.Session
          Current SPIDER session
    sp : float
         Spatial frequency to filter volume
    filter_type : int
                  Type of low-pass filter to use with resolution: [1] Fermi(SP, fermi_temp) [2] Butterworth (SP-bp_pass, SP+bp_stop) [3] Gaussian (SP)
    fermi_temp : float
                 Fall off for Fermi filter (both high pass and low pass)
    bw_pass : float
              Offset for pass band of the butterworth lowpass filter (sp-bw_pass)
    bw_stop : float
              Offset for stop band of the butterworth lowpass filter (sp+bw_stop)
    reg : float
          Regularization for total variance denoising
    outputfile : str
                 Output filename for filtered volume
    extra : dict
            Unused keyword arguments
    
    :Returns:
    
    outputfile : str
                 Output filename for filtered volume
    '''
    
    if int(filter_type) == 4:
        try:
            from skimage.filter import denoise_tv_chambolle as tv_denoise  #@UnresolvedImport
            tv_denoise;
        except:
            from skimage.filter import tv_denoise  #@UnresolvedImport
        from ..core.image import ndimage_file
        _logger.info("Total variation filter")
        img = ndimage_file.read_image(spi.replace_ext(filename))
        img = tv_denoise(img, weight=reg, eps=2.e-4, n_iter_max=200)
        ndimage_file.write_image(spi.replace_ext(outputfile), img)
        return outputfile
    
    if filename == outputfile: filename = spi.cp(filename)
    _logger.info("Filtering with %f, %d"%(sp, filter_type))
    if sp > 0.08:
        if filter_type == 1:
            rad = sp
            if rad > 0.45: rad = 0.45
            outputfile = spi.fq(filename, spi.FERMI_LP, filter_radius=rad, temperature=fermi_temp, outputfile=outputfile)
        elif filter_type==2:
            pass_band = sp-bw_pass
            stop_band = sp+bw_stop
            if pass_band > 0.35: pass_band = 0.4
            if stop_band > 0.4: stop_band = 0.45
            outputfile = spi.fq(filename, spi.BUTER_LP, pass_band=pass_band, stop_band=stop_band, outputfile=outputfile)
        elif filter_type != 3: outputfile=filename
    else:
        _logger.warn("Spatial frequency %f exceeds the safe value, switching to Gaussian filter: %d"%(sp, filter_type))
        filter_type = 3
    if filter_type == 3:
        _logger.info("Filtering with Gaussian: %s -> %f"%(filename, sp))
        outputfile = spi.fq(filename, spi.GAUS_LP, filter_radius=sp, outputfile=outputfile)
    return outputfile
示例#21
0
                  type=int,
                  default=6,
                  help="Payload length (default is 6)")
parser.add_option("-e",
                  dest="ecc_length",
                  type=int,
                  default=4,
                  help="ECC length (default is 4)")

if __name__ == "__main__":
    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.error("Usage: [options] <input image file> <payload>")
    infile, payload = args
    if not options.outfile:
        options.outfile = "%s-%s.png" % (
            os.path.basename(infile).split(".")[0], payload)

    t0 = time.time()
    w = Watermarker(options.payload_length,
                    options.ecc_length,
                    seed=options.seed,
                    mother=options.mother)
    out = w.embed(misc.imread(infile), payload, options.k)
    t1 = time.time()
    if options.tv_weight > 0:
        out = tv_denoise(out, options.tv_weight)

    misc.imsave(options.outfile, out)
    print "Created %s in %s seconds" % (options.outfile, t1 - t0)
示例#22
0
文件: embed.py 项目: Peaker/tau
parser.add_option("-m", dest="mother", type=str, default = "bior3.1",
    help="The mother wavelet (default is bior3.1)")
parser.add_option("-t", dest="tv_weight", type=int, default = 0,
    help="TV denoising weight (default is 0, meaning no denoising is performed)")
parser.add_option("-p", dest="payload_length", type=int, default = 6,
    help="Payload length (default is 6)")
parser.add_option("-e", dest="ecc_length", type=int, default = 4,
    help="ECC length (default is 4)")


if __name__ == "__main__":
    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.error("Usage: [options] <input image file> <payload>")
    infile, payload = args
    if not options.outfile:
        options.outfile = "%s-%s.png" % (os.path.basename(infile).split(".")[0], payload)
    
    t0 = time.time()
    w = Watermarker(options.payload_length, options.ecc_length, seed = options.seed, 
        mother = options.mother)
    out = w.embed(misc.imread(infile), payload, options.k)
    t1 = time.time()
    if options.tv_weight > 0:
        out = tv_denoise(out, options.tv_weight)
    
    misc.imsave(options.outfile, out)
    print "Created %s in %s seconds" % (options.outfile, t1-t0)


示例#23
0
def process(filename,
            output,
            apix,
            resolution,
            window,
            id_len=0,
            diameter=False,
            cur_apix=0,
            mask_type='None',
            weight=0,
            **extra):
    '''Concatenate files and write to a single output file
        
    :Parameters:
    
        filename : str
                   Input filename
        output : str
                 Output filename
        apix : float
               Target pixel size
        resolution : float
                     Low pass filter
        window : int
               New windows size
        id_len : int, optional
                 Maximum length of the ID
        diameter : bool
                   Meaure diameter of object
        cur_apix : float
                   Pixel size of input volume
        mask_type : choice
                    Type of masking to perform
        weight : float
                 Regularization parameter for total variance denoising
        extra : dict
                Unused key word arguments
                
    :Returns:
        
        filename : str
                   Current filename
    '''

    if spider_utility.is_spider_filename(filename):
        output = spider_utility.spider_filename(output, filename, id_len)
    header = {}
    vol = ndimage_file.read_image(filename, header=header, force_volume=True)
    if vol.min() == vol.max():
        raise ValueError, "Input image has no information: %s" % str(vol.shape)
    if cur_apix == 0: cur_apix = header['apix']
    _logger.debug("Got pixel size: %f" % cur_apix)
    if cur_apix == 0:
        raise ValueError, "Pixel size not found in volume header! Use --cur-apix to set current pixel size"
    if resolution > 0:
        _logger.debug("Filtering volume")
        vol = ndimage_filter.filter_gaussian_lowpass(vol,
                                                     cur_apix / resolution, 2)
    if apix > 0:
        _logger.debug("Interpolating volume")
        # todo -- pad to ensure better interpolation
        vol = ndimage_interpolate.resample_fft_fast(vol, apix / cur_apix)
    else:
        apix = cur_apix
    if weight > 0:
        vol = tv_denoise(vol, weight=weight, eps=2.e-4, n_iter_max=200)
    if window > 0:
        window = int(window)
        if window > vol.shape[0]:
            _logger.debug("Increasing window size")
            vol = ndimage_filter.pad(vol,
                                     tuple([window for _ in xrange(vol.ndim)]))
        elif window < vol.shape[0]:
            _logger.debug("Decreasing window size")
            vol = ndimage_filter.depad_image(
                vol, tuple([window for _ in xrange(vol.ndim)]))
    _logger.debug("Setting pixel size: %f" % apix)
    if mask_type != 'None':
        if mask_type == 'Adaptive':
            mask = tight_mask(vol, **extra)
        elif mask_type == 'Sphere':
            mask = sphere_mask(vol, apix, **extra)
        else:
            mask = ndimage_file.read_image(extra['mask_file'])
        ndimage_file.write_image(format_utility.add_suffix(output, "_mask"),
                                 mask,
                                 header=dict(apix=apix))
        vol *= mask
    ndimage_file.write_image(output, vol, header=dict(apix=apix))
    if diameter:
        from ..core.image import measure
        print measure.estimate_diameter(vol, cur_apix)
        print measure.estimate_shape(vol, cur_apix)
    return filename
示例#24
0
def power_spectra_model_range(powspec,
                              defu,
                              defv,
                              defa,
                              beg,
                              end,
                              bswindow,
                              ampcont,
                              cs,
                              voltage,
                              apix,
                              bfactor=0,
                              out=None,
                              tdv=0.0,
                              bs=False,
                              mask_pow=False,
                              **extra):
    ''' Generate model for a specific range of rings
    
    :Parameters:
        
        powspec : array
                  Image of 2D power spectra
        defu : float
               Defocus on minor axis in angstroms
        defv : float
               Defocus on major axis in angstroms
        defa : float
               Astigmatism angle in degrees between x-axis and minor defocus axis
        beg : int
              Starting ring
        end : int
              Last ring
        bswindow : int
                 Size of window for background subtraction
        ampcont : float
                  Amplitude contrast in percent
        cs : float
             Spherical abberation in mm
        voltage : float
                  Electron energy in kV
        apix : float
               Pixel size
        bfactor : float
                  Fall off in angstroms^2
        out : array
              Image of 2D power spectra with model on left and data on right
        extra : dict
                Unused keyword arguments
        
    :Returns:
        
        out : array
              Image of 2D power spectra with model on left and data on right
              
    '''

    mask = ndimage_utility.model_ring(beg, end, powspec.shape) < 0.5
    out = powspec.copy()
    model = ctf_model.transfer_function_2D_full(powspec.shape, defu, defv,
                                                defa, ampcont, cs, voltage,
                                                apix, bfactor)**2
    if bs:
        powspec = subtract_background(powspec, bswindow)
    if tdv > 0:
        from skimage.filter import denoise_tv_chambolle as tv_denoise
        powspec = tv_denoise(powspec, weight=tdv, eps=2.e-4, n_iter_max=200)

    out[:, :powspec.shape[0] / 2] = model[:, :powspec.shape[0] / 2]

    if mask_pow:
        tmask = mask.copy()
        tmask[:, powspec.shape[0] / 2:] = 0
        gmask = numpy.logical_not(mask.copy())
        gmask[:, powspec.shape[0] / 2:] = 0
        out[tmask] = numpy.mean(model[gmask])

    out[:, powspec.shape[0] / 2:] = powspec[:, powspec.shape[0] / 2:]

    if mask_pow:
        tmask = mask.copy()
        tmask[:, :powspec.shape[0] / 2] = 0
        gmask = numpy.logical_not(mask.copy())
        gmask[:, :powspec.shape[0] / 2] = 0
        out[tmask] = numpy.mean(model[gmask])

    out[:, :powspec.shape[0] / 2] = ndimage_utility.histeq(
        out[:, :powspec.shape[0] / 2])
    out[:, powspec.shape[0] / 2:] = ndimage_utility.histeq(
        out[:, powspec.shape[0] / 2:])
    return out
import numpy as np
import scipy
import matplotlib.pyplot as plt
from skimage.filter import tv_denoise

l = scipy.misc.lena()
l = l[230:290, 220:320]

noisy = l + 0.4 * l.std() * np.random.random(l.shape)

tv_denoised = tv_denoise(noisy, weight=10)

plt.figure(figsize=(12, 2.8))

plt.subplot(131)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('noisy', fontsize=20)
plt.subplot(132)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('TV denoising', fontsize=20)

tv_denoised = tv_denoise(noisy, weight=50)
plt.subplot(133)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('(more) TV denoising', fontsize=20)

plt.subplots_adjust(wspace=0.02,
                    hspace=0.02,
def transforms_1():
    """
    WIP image transforms collection.
    """

    assert False,'TODO'
    
    from PIL import Image, ImageEnhance
    image = Image.open('downloads/jcfeb2011.jpg')

    ## Sharpness - 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image:
    i2 = ImageEnhance.Sharpness(image).enhance(factor)
    
    ## An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
    i2 = ImageEnhance.Brightness(image).enhance(factor)
    
    ## An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image.
    i2 = ImageEnhance.Contrast(image).enhance(factor)

    ## An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image.
    i2 = ImageEnhance.Color(image).enhance(factor)

    ## Rotate, -180 to 180, resample=Image.NEAREST, resample=Image.BILINEAR, resample=Image.BICUBIC:
    i2 = i1.rotate(45)

    ## Rotate without cropping:
    i2 = i2.rotate(45, expand=True)

    ## Specify transparent color:
    transparency = im.info['transparency'] 
    im.save('icon.gif', transparency=transparency)

    ## Crop off max 10% from each side:

    width, height = i1.size
    left = width / randint(10, 100)
    top = height / randint(10, 100)
    right = width - (width / randint(10, 100))
    bottom = height - (height / randint(10, 100))
    i2 = i1.crop((left, top, right, bottom))

    ### http://pillow.readthedocs.io/en/3.1.x/reference/ImageOps.html

    ## cutoff – How many percent to cut off from the histogram. ignore – The background pixel value (use None for no background).
    PIL.ImageOps.autocontrast(image, cutoff=0, ignore=None)

    ## The black and white arguments should be RGB tuples;
    PIL.ImageOps.colorize(image, black, white)

    ## Remove border from image. The same amount of pixels are removed from all four sides. 
    PIL.ImageOps.crop(image, border=0)

    ## Applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image.
    PIL.ImageOps.equalize(image, mask=None)

    ## Add border to the image
    PIL.ImageOps.expand(image, border=0, fill=0)

    ## Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size.
    PIL.ImageOps.fit(image, size, method=0, bleed=0.0, centering=(0.5, 0.5))

    ## Convert the image to grayscale.
    PIL.ImageOps.grayscale(image)

    ## Reduce the number of bits for each color channel.
    PIL.ImageOps.posterize(image, bits)
    
    #### Perspective transformation: http://stackoverflow.com/questions/14177744/how-does-perspective-transformation-work-in-pil

    #######
    ## http://cbio.ensmp.fr/~nvaroquaux/formations/scipy-lecture-notes/advanced/image_processing/index.html
    ## http://www.scipy-lectures.org/advanced/image_processing/

    from scipy import ndimage
    from scipy import misc
    lena = misc.imread('lena.png')
    
    ###

    ## Cropping
    lena = misc.lena()
    lx, ly = lena.shape
    crop_lena = lena[lx / 4: - lx / 4, ly / 4: - ly / 4]
    
    ## up <-> down flip
    flip_ud_lena = np.flipud(lena)
    
    ## rotation
    rotate_lena = ndimage.rotate(lena, 45)
    rotate_lena_noreshape = ndimage.rotate(lena, 45, reshape=False)

    
    ## Add noise to image:
    noisy = l + 0.4 * l.std() * np.random.random(l.shape)
    
    ## A Gaussian filter smoothes the noise out... and the edges as well:
    blurred_lena = ndimage.gaussian_filter(lena, sigma=3)
    very_blurred = ndimage.gaussian_filter(lena, sigma=5)

    ##A median filter preserves better the edges:
    med_denoised = ndimage.median_filter(noisy, 3)

    ##Total-variation (TV) denoising. Find a new image so that the total-variation of the image (integral of the norm L1 of the gradient) is minimized, while being close to the measured image:
    from skimage.filter import tv_denoise
    tv_denoised = tv_denoise(noisy, weight=50)

    
    ## Increase the weight of edges by adding an approximation of the Laplacian:
    filter_blurred_l = ndimage.gaussian_filter(blurred_l, 1)
    alpha = 30
    sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l)
"""
This example compares several denoising filters available in scikit-image:
a Gaussian filter, a median filter, and total variation denoising.
"""

import matplotlib.pyplot as plt
from skimage import data
from skimage import filter
from scipy import ndimage

coins = data.coins()
gaussian_filter_coins = ndimage.gaussian_filter(coins, sigma=2)
med_filter_coins = filter.median_filter(coins)
tv_filter_coins = filter.tv_denoise(coins, weight=0.1)

plt.figure(figsize=(16, 4))
plt.subplot(141)
plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("Image")
plt.subplot(142)
plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("Gaussian filter")
plt.subplot(143)
plt.imshow(med_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("Median filter")
plt.subplot(144)
plt.imshow(tv_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
示例#28
0
def transforms_1():
    """
    WIP image transforms collection.
    """

    assert False, 'TODO'

    from PIL import Image, ImageEnhance
    image = Image.open('downloads/jcfeb2011.jpg')

    ## Sharpness - 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image:
    i2 = ImageEnhance.Sharpness(image).enhance(factor)

    ## An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
    i2 = ImageEnhance.Brightness(image).enhance(factor)

    ## An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image.
    i2 = ImageEnhance.Contrast(image).enhance(factor)

    ## An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image.
    i2 = ImageEnhance.Color(image).enhance(factor)

    ## Rotate, -180 to 180, resample=Image.NEAREST, resample=Image.BILINEAR, resample=Image.BICUBIC:
    i2 = i1.rotate(45)

    ## Rotate without cropping:
    i2 = i2.rotate(45, expand=True)

    ## Specify transparent color:
    transparency = im.info['transparency']
    im.save('icon.gif', transparency=transparency)

    ## Crop off max 10% from each side:

    width, height = i1.size
    left = width / randint(10, 100)
    top = height / randint(10, 100)
    right = width - (width / randint(10, 100))
    bottom = height - (height / randint(10, 100))
    i2 = i1.crop((left, top, right, bottom))

    ### http://pillow.readthedocs.io/en/3.1.x/reference/ImageOps.html

    ## cutoff – How many percent to cut off from the histogram. ignore – The background pixel value (use None for no background).
    PIL.ImageOps.autocontrast(image, cutoff=0, ignore=None)

    ## The black and white arguments should be RGB tuples;
    PIL.ImageOps.colorize(image, black, white)

    ## Remove border from image. The same amount of pixels are removed from all four sides.
    PIL.ImageOps.crop(image, border=0)

    ## Applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image.
    PIL.ImageOps.equalize(image, mask=None)

    ## Add border to the image
    PIL.ImageOps.expand(image, border=0, fill=0)

    ## Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size.
    PIL.ImageOps.fit(image, size, method=0, bleed=0.0, centering=(0.5, 0.5))

    ## Convert the image to grayscale.
    PIL.ImageOps.grayscale(image)

    ## Reduce the number of bits for each color channel.
    PIL.ImageOps.posterize(image, bits)

    #### Perspective transformation: http://stackoverflow.com/questions/14177744/how-does-perspective-transformation-work-in-pil

    #######
    ## http://cbio.ensmp.fr/~nvaroquaux/formations/scipy-lecture-notes/advanced/image_processing/index.html
    ## http://www.scipy-lectures.org/advanced/image_processing/

    from scipy import ndimage
    from scipy import misc
    lena = misc.imread('lena.png')

    ###

    ## Cropping
    lena = misc.lena()
    lx, ly = lena.shape
    crop_lena = lena[lx / 4:-lx / 4, ly / 4:-ly / 4]

    ## up <-> down flip
    flip_ud_lena = np.flipud(lena)

    ## rotation
    rotate_lena = ndimage.rotate(lena, 45)
    rotate_lena_noreshape = ndimage.rotate(lena, 45, reshape=False)

    ## Add noise to image:
    noisy = l + 0.4 * l.std() * np.random.random(l.shape)

    ## A Gaussian filter smoothes the noise out... and the edges as well:
    blurred_lena = ndimage.gaussian_filter(lena, sigma=3)
    very_blurred = ndimage.gaussian_filter(lena, sigma=5)

    ##A median filter preserves better the edges:
    med_denoised = ndimage.median_filter(noisy, 3)

    ##Total-variation (TV) denoising. Find a new image so that the total-variation of the image (integral of the norm L1 of the gradient) is minimized, while being close to the measured image:
    from skimage.filter import tv_denoise
    tv_denoised = tv_denoise(noisy, weight=50)

    ## Increase the weight of edges by adding an approximation of the Laplacian:
    filter_blurred_l = ndimage.gaussian_filter(blurred_l, 1)
    alpha = 30
    sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l)