Esempio n. 1
0
def main():
    print('\nADD GAUSSIAN BLURRING TO IMAGES\n')



    ##  Get input arguments
    args = getArgs()



    ##  Get input and output path
    pathin = args.pathin
    if pathin[len(pathin)-1] != '/':
        pathin += '/'

    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout
    if pathout[len(pathout)-1] != '/':
        pathout += '/'

    print('\nInput path:\n', pathin)
    print('\nOutput path:\n', pathout)



    ##  Get single image
    if args.image is not None:
        ##  Reading image
        filein = args.image
        imagein = io.readImage( pathin + filein )
        nrows , ncols = imagein.shape
        
        print('\nReading image:\n', filein)
        print('Image size: ', nrows,' X ', ncols)


        ##  Check plot
        if args.plot is True:
            dis.plot( imagein , 'Input image' )
        
        
        ##  Allocate memory for the noisy temporary image
        image_noisy = np.zeros( ( nrows, ncols ) , dtype=myfloat )


        ##  Compute standard deviation of the image
        ##  and, subsequently, the gaussian sigmas
        sigma = np.mean( imagein )
        
        sigma_list = args.sigma_list
        sigma_list = np.array( sigma_list.split(':') , dtype=myfloat )
        nimg = len( sigma_list )

        sigma_arr = sigma * sigma_list / 100.0

        print('\nSigma of the input image: ', sigma)
        print('Sigma percentages: ', sigma_list)
        print('\nGaussian sigma values: ')
        pp.printArray( sigma_arr , 4 , 'r' )      


        ##  Loop on each gaussian sigma
        for im in range( nimg ):
            ##  Add gaussian noise
            image_noisy[:,:] = add_gaussian_blurring( imagein , sigma_arr[im] )

            ##  Check noisy image
            if args.plot is True:
                dis.plot( image_noisy , 'Noisy image -- sigma: ' + str( sigma_list[im] ) )

            ##  Write noisy image to file
            fileout = filein[:len(filein)-4] + '_blur' 
            if sigma_list[im] < 10:
                fileout += '00' + str( int( sigma_list[im] ) ) + '.DMP'
            elif sigma_list[im] < 100:
                fileout += '0' + str( int( sigma_list[im] ) ) + '.DMP' 
            else:
                fileout += str( int( sigma_list[im] ) ) + '.DMP'  
            io.writeImage( pathout + fileout , image_noisy )



    
    ##  Get bunch of input images
    elif args.label is not None:
        curr_dir = os.getcwd()

        ##  Reading images
        os.chdir( pathin )
        files = sorted( glob.glob( '*' + args.label + '*' ) )
        os.chdir( curr_dir )

        num_im_input = len( files )

        for i in range( num_im_input ):
            imagein = io.readImage( pathin + files[i] )
            nrows , ncols = imagein.shape
            
            print('\nReading image:\n', files[i])
            print('Image size: ', nrows,' X ', ncols)  
                
                
            ##  Compute standard deviation of the image
            ##  and, subsequently, the gaussian sigmas
            sigma = np.mean( imagein )
        
            sigma_list = args.sigma_list
            sigma_list = np.array( sigma_list.split(':') , dtype=myfloat )
            nimg = len( sigma_list )

            sigma_arr = sigma * sigma_list / 100.0

            print('\nSigma of the input image: ', sigma)
            print('Sigma percentages: ', sigma_list)
            print('\nGaussian sigma values: ')
            pp.printArray( sigma_arr , 4 , 'r' )      


            ##  Loop on each gaussian sigma
            for im in range( nimg ):
                ##  Add gaussian noise
                image_noisy = add_gaussian_blurring( imagein , sigma_arr[im] )

                ##  Write noisy image to file
                fileout = files[i][:len(files[i])-4] + '_blur' 
                if sigma_list[im] < 10:
                    fileout += '00' + str( int( sigma_list[im] ) ) + '.DMP'
                elif sigma_list[im] < 100:
                    fileout += '0' + str( int( sigma_list[im] ) ) + '.DMP' 
                else:
                    fileout += str( int( sigma_list[im] ) ) + '.DMP'
                io.writeImage( pathout + fileout , image_noisy )  

    print('\n\n')
Esempio n. 2
0
def main():
    print('\nADD GAUSSIAN NOISE TO IMAGES\n')



    ##  Get input arguments
    args = getArgs()



    ##  Get input and output path
    pathin = args.pathin
    if pathin[len(pathin)-1] != '/':
        pathin += '/'

    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout
    if pathout[len(pathout)-1] != '/':
        pathout += '/'

    print('\nInput path:\n', pathin)
    print('\nOutput path:\n', pathout)



    ##  Get single image
    if args.image is not None:
        ##  Reading image
        filein  = args.image
        imagein = io.readImage( pathin + filein ).astype( myfloat )
        shape   = np.array( imagein.shape )
        print('\nReading image:\n', filein)  

        if len( shape ) == 2:
            dim = 2
            nrows , ncols = shape
            print('Image size: ', nrows,' X ', ncols)
            if args.plot is True:
                dis.plot( imagein , 'Input image' )
        else:
            dim = 3
            nz , nrows , ncols = shape
            print('Image size: ', nz , ' X ' , nrows,' X ', ncols)
            if args.plot is True:
                dis.plot( imagein[0,:,:] , 'Input image' ) 
        

        ##  Compute standard deviation of the image
        ##  and, subsequently, the gaussian sigmas
        sigma = 0.5 * np.max( imagein )
        
        sigma_list = args.sigma_list
        sigma_list = np.array( sigma_list.split(':') , dtype=myfloat )
        nimg = len( sigma_list )

        sigma_arr = sigma * sigma_list / 100.0

        print('\nSigma of the input image: ', sigma)
        print('Sigma percentages: ', sigma_list)
        print('\nNoise sigma values: ')
        pp.printArray( sigma_arr , 4 , 'r' )


        ##  Loop on each gaussian sigma
        for im in range( nimg ):
            ##  Add noise
            if args.noise == 'gaussian':
                image_noisy = add_gaussian_noise( imagein , sigma_arr[im] )
                label = 'gauss'
            elif args.noise == 'poisson':
                image_noisy = add_poisson_noise( imagein , sigma_arr[im] )
                label = 'poiss'


            ##  Check noisy image
            if args.plot is True:
                if dim == 2:
                    if args.noise == 'gaussian':
                        dis.plot( image_noisy , 'Gaussian noisy image -- sigma: ' + str( sigma_list[im] ) )
                    elif args.noise == 'poisson':
                        dis.plot( image_noisy , 'Poisson noisy image -- sigma: ' + str( sigma_list[im] ) ) 
                else:
                    if args.noise == 'gaussian':
                        dis.plot( image_noisy[0,:,:] , 'Gaussian noisy image -- sigma: ' + str( sigma_list[im] ) )
                    elif args.noise == 'poisson':
                        dis.plot( image_noisy[0,:,:] , 'Poisson noisy image -- sigma: ' + str( sigma_list[im] ) )      


            ##  Write noisy image to file
            extension = filein[len(filein)-4:] 
            fileout = filein[:len(filein)-4] + '_' + label

            if sigma_list[im] < 1:
                fileout += '000' + str( int( sigma_list[im] * 10 ) ) + extension  

            elif sigma_list[im] < 10:
                fileout += '00' + str( int( sigma_list[im] * 10 ) ) + extension
                
            elif sigma_list[im] < 100:
                fileout += '0' + str( int( sigma_list[im] * 10 ) ) + extension 
            
            else:
                fileout += str( int( sigma_list[im] * 10 ) ) + extension  
            
            io.writeImage( pathout + fileout , image_noisy )



    
    ##  Get bunch of input images
    elif args.label is not None:
        curr_dir = os.getcwd()

        ##  Reading images
        os.chdir( pathin )
        files = sorted( glob.glob( '*' + args.label + '*' ) )
        os.chdir( curr_dir )

        num_im_input = len( files )

        for i in range( num_im_input ):
            imagein = io.readImage( pathin + files[i] ).astype( myfloat )
            nrows , ncols = imagein.shape
            
            print('\nReading image:\n', files[i])
            print('Image size: ', nrows,' X ', ncols)  
                
                
            ##  Compute standard deviation of the image
            ##  and, subsequently, the gaussian sigmas
            sigma = np.mean( imagein )
        
            sigma_list = args.sigma_list
            sigma_list = np.array( sigma_list.split(':') , dtype=myfloat )
            nimg = len( sigma_list )

            sigma_arr = sigma * sigma_list / 100.0

            print('\nSigma of the input image: ', sigma)
            print('Sigma percentages: ', sigma_list)
            print('Gaussian sigma values: ', sigma_arr)


            ##  Loop on each gaussian sigma
            for im in range( nimg ):
                ##  Add noise
                if args.noise == 'gaussian':
                    image_noisy = add_gaussian_noise( imagein , sigma_arr[im] )
                    label = 'gauss'
                elif args.noise == 'poisson':
                    image_noisy = add_poisson_noise( imagein , sigma_arr[im] )
                    label = 'poiss'

                ##  Write noisy image to file
                extension = files[i][len(files[i])-4:] 
                fileout = files[i][:len(files[i])-4] + '_noise_' + label
                
                if sigma_list[im] < 1:
                    fileout += '000' + str( int( sigma_list[im] * 10 ) ) + extension  

                elif sigma_list[im] < 10:
                    fileout += '00' + str( int( sigma_list[im] * 10 ) ) + '0' + extension
                
                elif sigma_list[im] < 100:
                    fileout += '0' + str( int( sigma_list[im] * 10 ) ) + '0' + extension 
                
                else:
                    fileout += str( int( sigma_list[im] * 10 ) ) + '0' + extension
                
                io.writeImage( pathout + fileout , image_noisy )  

    print('\n\n')
Esempio n. 3
0
def compute_lir( args ):
    ##  Get input images
    inputs = args.inputs
    file1 , file2 , file3 = inputs.split( ':' )
    rec_ref = io.readImage( file1 )
    rec_imp = io.readImage( file2 )
    imp_pos = np.loadtxt( file3 ).astype( int )
    npix = rec_ref.shape[0]
    nimp = imp_pos.shape[0]


    ##  Display input images
    if args.plot is True:
        image_imp = np.zeros( ( npix , npix ) )
        image_list = [ rec_ref , rec_imp ]
        title_list = [ 'Reference reconstruction' ,
                       'Impulsed reconstruction'  ]
        dis.plot_multi( image_list , title_list )


    ##  Compute image difference
    rec_diff = rec_imp - rec_ref


    ##  Resize image
    zoom_factor = args.zoom
    rec_diff = zoom( rec_diff , zoom_factor )

    if args.plot is True:
        dis.plot( rec_diff , 'Difference image x' + str( zoom_factor ), ')')


    ##  Compute FWHM for each impulse and get an average of them
    fwhm = np.zeros( nimp , dtype=myfloat )
    denom = zoom_factor

    for i in range( nimp ):
        x0 = int( zoom_factor * imp_pos[i,0] );  y0 = int( zoom_factor * imp_pos[i,1] )
        square = rec_diff[x0-r:x0+r,y0-r:y0+r]
        hh = np.max( square ) * 0.5
        aux = np.argwhere( square >= hh )
        fwhm[i] = np.sqrt( len( aux ) ) / denom

    FWHM = np.sum( fwhm ) / myfloat( nimp )
    print('\nFWHM values:\n')
    pp.printArray( fwhm )
    print('\nFWHM average: ', FWHM)
    print('\n')

    
    ##  Write log file of the results
    namebase = file1
    pathout = None
    
    if namebase.find( '/' ) != -1:
        namebase = namebase.split( '/' )
        filename = namebase[len(namebase)-1]
        filename = filename[:len(filename)-4]
        for i in range( len(namebase)-1 ):
            if i == 0:
                pathout = '/' + namebase[i] 
            else:
                pathout += namebase[i] + '/'
    else:
        filename = namebase
        filename = filename[:len(filename)-4]
        pathout = './'

    print('\nWriting files ...')

    fileout = pathout + filename + '_lir_diff.DMP'
    io.writeImage( fileout , rec_diff )
    print( fileout )

    fileout = pathout + filename + '_lir_analysis.txt'
    fp = open( fileout , 'w' )
    fp.write('\n')
    fp.write('\n###########################################')
    fp.write('\n###########################################') 
    fp.write('\n###                                     ###')
    fp.write('\n###   LOCAL IMPULSE RESPONSE ANALYSIS   ###')
    fp.write('\n###                                     ###')
    fp.write('\n###########################################')
    fp.write('\n###########################################') 
    fp.write('\n')
    today = datetime.datetime.now()
    fp.write('\nLIR calculation performed on the ' + str( today ))
    fp.write('\n\nNumbers of impulses: ' + str( nimp ))
    fp.write('\n\nAverage FWHM: ' + str( FWHM ))
    print( fileout )
    print( '\n' )
Esempio n. 4
0
def analysis_spectrum( image , args , im , plot_name , label ):
    ##  Get the Nyquist frequency
    nx,ny = image.shape
    
    if nx == ny:
        nmax = nx
    elif nx < ny:
        nmax = ny
    else:
        nmax = nx
    
    freq_nyq = int( np.floor( nmax/2.0 ) )

   
    ##  Initialize progress bar
    bar = progressbar.ProgressBar(maxval=freq_nyq, \
                                  widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])


    ##  Create Fourier grid
    x = np.arange( -np.floor( ny/2.0 ) , np.ceil( ny/2.0 ) )
    y = np.arange( -np.floor( ny/2.0 ) , np.ceil( ny/2.0 ) )
    x,y = np.meshgrid( x , y )
    map_dist = np.sqrt( x*x + y*y )

    #print( '\nx-linspace:\n' , x )

    #print('\n\nDistance map:')
    #pp.printArray2D( map_dist )
    #print('\n')


    ##  FFT transforms of the input images
    fft_image = np.fft.fftshift( np.fft.fft2( image ) )

    #print('\n\nFFT IMAGE 1:\n', fft_image1)
    #print('\n\nFFT IMAGE 2:\n', fft_image2)  

    
    ##  Get thickness of the rings
    width_ring = args.width_ring


    ##  Calculate FRC and 2*sigma curve
    spectrum_ring = [];  radii = [] 
    r = 0.0
    l = 0

    while r + width_ring < freq_nyq :
        bar.update(r+1)
        sleep(0.1)
        
        ind_ring = find_points_interval( map_dist , r , r + width_ring )
        
        aux = fft_image[ind_ring[:,0],ind_ring[:,1]]

        #print( '\nRadius: ', r,'  ---  ring between: ', r,' - ', r + width_ring )
        #print('Ring indices:\n', ind_ring)
        #print('aux1:\n', aux1)
        #print('aux2:\n', aux2)

        #image_aux = np.zeros( ( 2*freq_nyq , 2*freq_nyq ) )
        #image_aux[ind_ring[:,0],ind_ring[:,1]] = 1.0
        #dis.plot( image_aux )

        spectrum_ring.append( np.sum( np.abs( aux )**2  ) / myfloat( len( aux ) ) )
        
        radii.append( r )
        r += width_ring
        l += 1

    radii = np.array( radii )
    spatial_freq = radii / myfloat( freq_nyq )
    spectrum_ring = np.array( spectrum_ring )
    spectrum_ring /= np.max( spectrum_ring )
    #spectrum_ring = np.log10( spectrum_ring + eps )
    #spectrum_ring += np.abs( np.min( spectrum_ring ) )

    print('\nRing-spectrum:\n')
    pp.printArray( spectrum_ring )



    ##  Plot FRC curve (alone)
    title = label
    label_curves = ['FRC']
    point = None
    style = 'points'
    plot_spectrum_curves( spectrum_ring , spatial_freq , args , label_curves , title ,
                          point, style )

    '''
    ##  Get resol point by means of the 2*sigma criterion 
    resol_point , index = criterion_2sigma( plot_curves , spatial_freq )


    ##  Plot FRC curve , 2*sigma curve , intersection point
    title = 'Resol. point as intersec. with 2*sigma curve'
    label_curves = ['FRC','2*sigma']
    style = 'points'
    plot_spectrum_curves( plot_curves , spatial_freq , args , label_curves , title ,
                     resol_point , style )

    print('Criterion number 1: resol point found as intersection between'
          + ' the FRC and the 2*sigma curve')
    
    if index != -1: 
        if args.pixsize is None:
            resol1 = freq_nyq / myfloat( index )
            print('Resolution : ', resol1,' pixel')
        else:
            resol1 = freq_nyq / myfloat( index ) * args.pixsize
            print('Resolution: ', resol1,' micro_meters')
        print('\n')

    else:
        print('No intersection between FRC data and 2*sigma curve!')
        resol1 = None

    
    ##  Get resol point by means of the half height criterion    
    resol_point , index = criterion_half( FRC, spatial_freq )


    ##  Plot FRC curve and half height point 
    title = 'Resol. point 0.5 criterion'
    style = 'points'
    plot_spectrum_curves( plot_curves[0] , spatial_freq , args , label_curves , title ,
                     resol_point , style )

    print('Criterion number 2: resol point found as the point at'
           + ' half height of the FRC curve')

    if args.pixsize is None:
        resol2 = freq_nyq / myfloat( index )
        print('Resolution: ', resol2,' pixel')
    else:
        resol2 = freq_nyq / myfloat( index ) * args.pixsize
        print('Resolution: ', resol2,' micro_meters')
    print('\n')
    
    bar.finish()
    '''

    return spectrum_ring , spatial_freq