예제 #1
0
def write_output_files( sino_down , angles_down , args , pathin , filename ):
    nang_down = sino_down.shape[0]

    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout

    extension = filename[len(filename)-4:]
    name_base = filename[:len(filename)-4] + '_'
    fileout = name_base + 'ang'

    if nang_down < 10:
        string_nang = '000' + str( nang_down )
    elif nang_down < 100:
        string_nang = '00' + str( nang_down )
    elif nang_down < 1000:
        string_nang = '0' + str( nang_down )
    else:
        string_nang = str( nang_down )  

    fileout += string_nang + extension
    io.writeImage( pathout + fileout , sino_down )
    print('\nWritten downsampled sinogram:\n', pathout + fileout)

    fileout = name_base + string_nang + '_angle_list.txt'   
    np.savetxt( pathout + fileout , angles_down , delimiter='\n' )
    print('\nWritten corresponding list of angles:\n', pathout + fileout)     
예제 #2
0
def write_reconstruction(reco, pathin, args):
    ##  Get output directory
    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout

    if os.path.exists(pathout) is False:
        print("\nOutput directory ", pathout, " does not exist  --->  created!")
        os.makedirs(pathout)

    print("\n\nOutput directory:\n", pathout)

    ##  Save output file
    filename = args.sino
    extension = filename[len(filename) - 4 :]
    filename = filename[: len(filename) - 4]

    if args.full_output is True:
        filename += "_b" + str(args.base_size) + "_d" + str(args.down_size)
        filename += "_" + args.filt

    filename += "_fhbp_rec" + extension
    filename = pathout + filename

    io.writeImage(filename, reco)
예제 #3
0
def main():
    print('\n')
    print('##############################################')
    print('##############################################')
    print('####                                      ####')
    print('####         DOWNSAMPLE SINOGRAM          ####')
    print('####                                      ####')      
    print('##############################################')
    print('##############################################')  
    print('\n') 


    ##  Get input arguments
    args = getArgs()


    
    ##  Read input sinogram
    pathin = args.pathin
    if pathin[len(pathin)-1] != '/':
        pathin += '/'

    filename = args.sino
    sino = io.readImage( pathin + filename )
    nang , npix = sino.shape

    print('\nInput path:\n', pathin)
    print('\nInput sinogram:\n', filename)
    print('Sinogram size: ', nang,' ang  X  ', npix,' pixels')


    
    ##  Get input sinogram
    factor = int( args.factor )
    print('\nDownsampling factor: ', factor)



    ##  Downsample in pixels
    sino_down = sino[:,::factor]

    if args.plot is True:
        sino_list = [ sino , sino_down ]
        title_list = [ 'Original sinogram' , 'Undersampled sinogram' ]
        dis.plot_multi( sino_list , title_list )



    ##  Write image
    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout

    fileout = filename[:len(filename)-4] + '_downsampl' + str( factor ) + '.DMP'
    io.writeImage( pathout + fileout , sino_down )
                 
    print('\n')
예제 #4
0
def write_sinogram( sino , pathin , angles , args ):
    nang = len( angles )

    ##  Get output directory
    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout

    if os.path.exists( pathout ) is False:
        print('\nOutput directory ', pathout,' does not exist  --->  created!')
        os.makedirs( pathout )

    print('\n\nOutput directory:\n', pathout)    


    ##  Save output file
    filename = args.image
    extension = filename[len(filename)-4:] 
    filename = filename[:len(filename)-4]

    nang = args.nang
    if nang < 10:
        str_nang = '000' + str( nang )
    elif nang < 100:
        str_nang = '00' + str( nang )
    elif nang < 1000:
        str_nang = '0' + str( nang )    
    else:
        str_nang = str( nang )

    filename += '_ang' + str_nang


    if args.full_output is True:
        filename += '_b' + str( args.base_size ) + '_d' + str( args.down_size )   

    filename += '_fhbp_sino' + extension
    filename = pathout + filename

    io.writeImage( filename , sino )


    ##  Save list of projection angles
    if args.list_ang is True:
        listang = filename[:len(filename)-4]
        listang += '_ang' + str( nang ) + '_list.txt'

        print('\nWriting list of projection angles:\n', listang) 
        fd = open( listang , 'w' )
        for i in range( len( angles ) ):
            fd.write('%.8f\n' % angles[i] )
        fd.close()     
예제 #5
0
파일: radon.py 프로젝트: arcaduf/radon
def save_sinogram( sinogram , angles , args ):
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout

    if pathout[len(pathout)-1] != '/':
        pathout += '/'

    
    if args.sino is None:
        filename = args.image
        extension = filename[len(filename)-4:] 
        filename = filename[:len(filename)-4]
        nang = args.nang

        if nang < 10:
            str_nang = '000' + str( nang )
        elif nang < 100:
            str_nang = '00' + str( nang )
        elif nang < 1000:
            str_nang = '0' + str( nang )
        else:
            str_nang = str( nang )

        if args.geometry != '1':
            filename += '_ang' + str_nang + '_radon_' + args.interp + '_polar_sino'
        else:
            filename += '_ang' + str_nang + '_radon_' + args.interp + '_pseudo_sino' 
        filename = pathout + filename + extension
    else:
        filename = pathout + args.sino

    io.writeImage( filename , sinogram )


    if args.list_ang is True:
        listang = filename[:len(filename)-4]

        if args.geometry != '1':
            listang += '_ang' + str( args.nang ) + '_list.txt'
        else:
            listang += '_ang' + str( args.nang ) + '_pseudopol_list.txt'

        print('\nWriting list of projection angles:\n', listang) 
        fd = open( listang , 'w' )
        for i in range( len( angles ) ):
            fd.write('%.8f\n' % angles[i] )
        fd.close()
예제 #6
0
파일: iradon.py 프로젝트: arcaduf/radon
def saveReco( reco , args ):
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout
    
    if args.reco is None:
        filename = args.sino
        filename = filename[:len(filename)-4]
        filename += '_iradon_' + args.interp + '_rec.DMP'
        filename = pathout + filename
    else:
        filename = pathout + args.reco

    io.writeImage( filename , reco )
예제 #7
0
파일: iradon.py 프로젝트: xiaolongma/radon
def saveReco(reco, args):
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout

    if args.reco is None:
        filename = args.sino
        filename = filename[:len(filename) - 4]
        filename += '_iradon_' + args.interp + '_rec.DMP'
        filename = pathout + filename
    else:
        filename = pathout + args.reco

    io.writeImage(filename, reco)
예제 #8
0
def main():
    x = io.readImage( sys.argv[1] )
    M = int( sys.argv[2] )
    dis.plot( x , 'Input image' )
    N , p = x.shape
    d = N;
    angles = np.arange( M )/myfloat( M ) * 180.0
    angles = np.fft.fftshift( angles )
    A = paralleltomo( angles , N , p , d )
    #dis.plot( A.todense() , 'Matrix A' )    
    sinogram = A.dot( x.reshape(-1) )
    sinogram = sinogram.reshape( M , N )
    dis.plot( sinogram , 'Output sinogram' )
    io.writeImage( sys.argv[1][:len(sys.argv[1])-4] + 'sino_par_tomo.DMP' , 
                   sinogram )
예제 #9
0
def save_reco(reco, args):
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout

    if args.reco is None:
        filename = args.sino
        filename = filename[:len(filename) - 4]
        filename += '_pyfbp' + '_reco.DMP'
        filename = pathout + filename
    else:
        filename = pathout + args.reco

    io.writeImage(filename, reco)
예제 #10
0
파일: radon.py 프로젝트: xiaolongma/radon
def save_sinogram(sinogram, angles, args):
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout

    if pathout[len(pathout) - 1] != '/':
        pathout += '/'

    if args.sino is None:
        filename = args.image
        extension = filename[len(filename) - 4:]
        filename = filename[:len(filename) - 4]
        nang = args.nang

        if nang < 10:
            str_nang = '000' + str(nang)
        elif nang < 100:
            str_nang = '00' + str(nang)
        elif nang < 1000:
            str_nang = '0' + str(nang)
        else:
            str_nang = str(nang)

        if args.geometry != '1':
            filename += '_ang' + str_nang + '_radon_' + args.interp + '_polar_sino'
        else:
            filename += '_ang' + str_nang + '_radon_' + args.interp + '_pseudo_sino'
        filename = pathout + filename + extension
    else:
        filename = pathout + args.sino

    io.writeImage(filename, sinogram)

    if args.list_ang is True:
        listang = filename[:len(filename) - 4]

        if args.geometry != '1':
            listang += '_ang' + str(args.nang) + '_list.txt'
        else:
            listang += '_ang' + str(args.nang) + '_pseudopol_list.txt'

        print('\nWriting list of projection angles:\n', listang)
        fd = open(listang, 'w')
        for i in range(len(angles)):
            fd.write('%.8f\n' % angles[i])
        fd.close()
예제 #11
0
def save_reco(reco, args):
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout

    if args.reco is None:
        filename = args.sino
        filename = filename[:len(filename) - 4]
        filename += '_ang' + str( args.nang ) + '_fbp_bspline' + \
                    str( args.bspline_degree ) + \
                    '_' + args.filt + '_rec.DMP'
        filename = pathout + filename
    else:
        filename = pathout + args.reco

    io.writeImage(filename, reco)
예제 #12
0
파일: pysart.py 프로젝트: xiaolongma/radon
def saveReco( reco , args ):
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout

    if pathout[len(pathout)-1] != '/':
        pathout += '/'
                            
    
    if args.reco is None:
        filename = args.sino
        filename = filename[:len(filename)-4]
        filename += '_rec_isart.DMP'
        filename = pathout + filename
    else:
        filename = pathout + args.reco

    io.writeImage( filename , reco )
예제 #13
0
def saveReco( reco , pathin , args ):
    ##  Get output directory
    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout

    if os.path.exists( pathout ) is False:
        print('\nOutput directory ', pathout,' does not exist  --->  created!')
        os.makedirs( pathout )

    print('\nOutput directory:\n', pathout)  


    ##  Save output file
    filename = args.sino
    filename = filename[:len(filename)-4]
    filename += '_est_rec.DMP'
    filename = pathout + filename
    io.writeImage( filename , reco )
예제 #14
0
def saveSino( sino , angles , args ):
    ##  Save sinogram
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout
    
    if args.sino is None:
        filename = args.image
        filename = filename[:len(filename)-4]

        if args.nang < 10:
            str_ang = '000' + str( args.nang )
        elif args.nang < 100:
            str_ang = '00' + str( args.nang )
        elif args.nang < 1000:
            str_ang = '0' + str( args.nang ) 

        filename += '_ang' + str_ang + '_radon_kb_r' \
                    + str( args.kb_radius ) + '_deg' \
                    + str( args.kb_degree ) 
        
        if args.geometry == '0':
            filename += '_polar'
        elif args.geometry == '1':
            filename += '_pseudo'
        else:
            filename += '_text'
        aux = filename
        filename += '_sin.DMP' 
        filename = pathout + filename
    else:
        filename = pathout + args.sino

    io.writeImage( filename , sino )


    ##  Save list of projection angles
    if args.listang is True:        
        fileang = aux + '_list_angles.txt'
        np.savetxt( pathout + fileang , angles , fmt='%.10f', delimiter='\n' )
예제 #15
0
def main():
    sino = io.readImage( sys.argv[1] )
    ctr = np.float32( sys.argv[2] )
    dis.plot( sino , 'Input sinogram' )

    sino_new = proc.sino_correct_rot_axis( sino , ctr )
    '''
    nang , npix = sino.shape
    sino_out = sino.copy()

    x = np.arange( npix )
    x_out = x - shift
    
    for i in range( nang ):
        s = InterpolatedUnivariateSpline( x , sino[i,:] )
        sino_out[i,:] = s( x_out )
    '''

    dis.plot( sino_new , 'Output sinogram' )
    filename = sys.argv[1][:len(sys.argv[1])-4] + '_interp.DMP'
    io.writeImage( filename , sino_new )
예제 #16
0
def main():
    filename = sys.argv[1]
    image = io.readImage( filename )
    limits = sys.argv[2]

    if len( limits.split(':') ) == 4:
        x1 = int( limits.split(':')[0] )
        x2 = int( limits.split(':')[1] )  
        y1 = int( limits.split(':')[2] )  
        y2 = int( limits.split(':')[3] )
        image_out = image[x1:x2,y1:y2]

    elif len( limits.split(':') ) == 3:
        x1 = int( limits.split(':')[0] )
        y1 = int( limits.split(':')[1] )  
        w = int( limits.split(':')[2] )  
        image_out = image[x1:x1+w,y1:y1+w]
                                      

    fileout = filename[:len(filename)-4] + '.crop.DMP'
    io.writeImage( fileout, image_out )
예제 #17
0
def main():
    sino = io.readImage(sys.argv[1])
    ctr = np.float32(sys.argv[2])
    dis.plot(sino, 'Input sinogram')

    sino_new = proc.sino_correct_rot_axis(sino, ctr)
    '''
    nang , npix = sino.shape
    sino_out = sino.copy()

    x = np.arange( npix )
    x_out = x - shift
    
    for i in range( nang ):
        s = InterpolatedUnivariateSpline( x , sino[i,:] )
        sino_out[i,:] = s( x_out )
    '''

    dis.plot(sino_new, 'Output sinogram')
    filename = sys.argv[1][:len(sys.argv[1]) - 4] + '_interp.DMP'
    io.writeImage(filename, sino_new)
예제 #18
0
파일: pyradon.py 프로젝트: arcaduf/radon
def saveSino( sino , angles , args ):
    ##  Save sinogram
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout
    
    if args.sino is None:
        filename = args.image
        filename = filename[:len(filename)-4]

        if args.nang < 10:
            str_ang = '000' + str( args.nang )
        elif args.nang < 100:
            str_ang = '00' + str( args.nang )
        elif args.nang < 1000:
            str_ang = '0' + str( args.nang ) 

        filename += '_ang' + str_ang + '_radon_' + args.interp 
        
        if args.geometry == '0':
            filename += '_polar'
        elif args.geometry == '1':
            filename += '_pseudo'
        else:
            filename += '_text'
        aux = filename
        filename += '_sin.DMP' 
        filename = pathout + filename
    else:
        filename = pathout + args.sino

    io.writeImage( filename , sino )


    ##  Save list of projection angles
    if args.listang is True:        
        fileang = aux + '_list_angles.txt'
        np.savetxt( pathout + fileang , angles , fmt='%.10f', delimiter='\n' )
예제 #19
0
def save_sino( sino , angles , args ):
    ##  Save sinogram
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout
    
    if args.sino is None:
        filename = args.image
        filename = filename[:len(filename)-4]

        if args.nang < 10:
            str_ang = '000' + str( args.nang )
        elif args.nang < 100:
            str_ang = '00' + str( args.nang )
        elif args.nang < 1000:
            str_ang = '0' + str( args.nang )
        else:
            str_ang = str( args.nang ) 

        filename += '_ang' + str_ang + '_radon_bspline_deg' \
                    + str( args.bspline_degree )
        
        if args.geometry == '0':
            filename += '_polar'
        elif args.geometry == '1':
            filename += '_pseudo'
        else:
            filename += '_text'
        aux = filename
        filename += '_sino.DMP' 
        filename = pathout + filename
    else:
        filename = pathout + args.sino

    io.writeImage( filename , sino )
예제 #20
0
def save_sino(sino, angles, args):
    ##  Save sinogram
    if args.pathout is None:
        pathout = args.pathin
    else:
        pathout = args.pathout

    if args.sino is None:
        filename = args.image
        filename = filename[:len(filename) - 4]

        if args.nang < 10:
            str_ang = '000' + str(args.nang)
        elif args.nang < 100:
            str_ang = '00' + str(args.nang)
        elif args.nang < 1000:
            str_ang = '0' + str(args.nang)
        else:
            str_ang = str(args.nang)

        filename += '_ang' + str_ang + '_radon_bspline_deg' \
                    + str( args.bspline_degree )

        if args.geometry == '0':
            filename += '_polar'
        elif args.geometry == '1':
            filename += '_pseudo'
        else:
            filename += '_text'
        aux = filename
        filename += '_sino.DMP'
        filename = pathout + filename
    else:
        filename = pathout + args.sino

    io.writeImage(filename, sino)
예제 #21
0
def main():

    print('')
    print('############################################') 
    print('############################################')
    print('####                                    ####')
    print('####  PROGRESSIVE DILATION OF AN IMAGE  ####')
    print('####                                    ####')   
    print('############################################')
    print('############################################') 


    ##  Get input arguments
    args = getArgs()

    
    ##  Get input path
    pathin = args.pathin
    if pathin[len(pathin)-1] != '/':
       pathin += '/'
    print('\nInput path:\n', pathin)


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

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


    ##  Read input image
    image = io.readImage( pathin + args.input )
    filein = args.input 
    nrows , ncols = image.shape


    ## Open log file
    logfile = args.log
    flog = open( pathout + logfile , 'w' ) 
    
    
    print('\nInput path:\n', pathin)
    print('\nOutput path:\n', pathout)
    print('\nInput image:\n', pathin + args.input)
    print('Image size: ', nrows,' X ', ncols)
    print('\nLog file:\n', pathout + logfile)
    flog.write('########  CREATE DILATED VERSIONS OF AN IMAGE  ########')
    today = datetime.datetime.now()
    flog.write('\nCalculation performed on the ' + str(today))
    flog.write('\nInput image:\n' + pathin + args.input )
    flog.write('Image size: ' + str( nrows ) + ' X ' + str( ncols ) )  


    ##  Allocate memory for array hosting the dilated images
    image_dil = np.zeros( ( nrows , ncols ) , dtype=myFloat )


    ##  Get dilation factors
    dilate_factors = args.dilate_factors
    dilate_factors = np.array( dilate_factors.split(':') ).astype( int )
    nimg = len( dilate_factors )
    print('\nNumber of dilated images to create: ', nimg)
    print('\nDilation factors: ', dilate_factors) 
    print('\n')
    flog.write('\nNumber of dilated images to create: ' + str( nimg ) + '\n')
    flog.write('\nDilation factors: ' + str( dilate_factors ) + '\n')    


    print('Original image')               
    meanSI , gsiIndex = complx_indeces( image ) 
    ind1 = round( meanSI , 4 )
    ind2 = round( gsiIndex , 4 )
    if args.plot:
        plot_image( image , 'Input image' , [ ind1 , ind2 ] )  

    ##  Create dilated version of the original image
    for im in dilate_factors:
        print('Dilation of size: ', im,' X ', im)
        flog.write('\nDilation of size ' + str( im ) + ' X ' + str( im ) )     
            
        ##  Dilation
        image_dil[:,:] = ndimage.grey_dilation( image , size=( im , im ) )  

        ##  Calculate image complexity index based on spatial information (SI)
        ##  and gradient sparsity index
        meanSI , gsiIndex = complx_indeces( image_dil ) 
        ind1 = round( meanSI , 4 )
        ind2 = round( gsiIndex , 4 )  
        print('meanSI ', meanSI,'   gsiIndex = ', gsiIndex)
        flog.write('\nmeanSI ' + str( meanSI ) + '   gsiIndex = ' + str( gsiIndex ) )    

        ##  Plot result
        if args.plot:
            plot_image( image_dil , 'Dilation ' + str( im ) , [ ind1 , ind2 ] )

        ##  Write image
        filename = pathout + filein[:len(filein)-4]
        if im < 10:
            filename += '.dil0' + str(im) + '.DMP'
        else:
            filename += '.dil' + str(im) + '.DMP' 
        io.writeImage( filename , image_dil )
        print('Writing:\n', filename)
        print('\n')
        flog.write('\n\n')

   
    flog.close()
예제 #22
0
def main():
    print('\n')
    print('#########################################################')
    print('#########################################################')
    print('###                                                   ###')
    print('###     ANALYTICAL RADON TRANSFORM OF SHEPP-LOGAN     ###')
    print('###                                                   ###')
    print('#########################################################')
    print('#########################################################')
    print('\n')

    ##  Get arguments
    args = getArgs()

    ##  Get number of pixels
    npix = args.npix
    nang = args.nang

    print('\nNumber of pixels: ', npix)
    print('Number of views: ', nang)

    ##  Create look-up-table of Shepp-Logan ellipses or read specifics from file
    if args.filein is None:
        LUT = lut_shepp_logan(npix, nang)
        print('\nCreated LUT for Shepp-Logan phantom')

    else:
        lut_file = np.loadtxt(args.filein)
        LUT = lut_generic_phantom(lut_file, npix, nang)

        if args.filein.find('/') == -1:
            name = args.filein.split('.')[0]
        else:
            tokens = args.filein.split('/')
            name = tokens[len(tokens) - 1].split('.')[0]

        print('\nReading LUT for phantom from file:\n', args.filein)
        print('Label selected for the putput files: ', name)

    ##  Create Shepp-Logan phantom
    phantom = create_phantom(LUT, npix)

    ##  Write phantom
    path = args.path
    if path[len(path) - 1] != '/':
        path += '/'

    if args.filein is None:
        filename = path + 'shepp_logan_pix'
    else:
        filename = path + name + '_pix'

    if npix < 10:
        common = '000' + str(npix)
    elif npix < 100:
        common = '00' + str(npix)
    elif npix < 1000:
        common = '0' + str(npix)
    else:
        common = str(npix)

    filename += common + args.file_format

    io.writeImage(filename, phantom)

    print('\nWriting sinogram in:\n', filename)

    ##  Plot phantom
    if args.plot is True:
        dis.plot(phantom, 'Shepp-Logan phantom  npix=' + str(npix))

    ##  Compute analitically radon transform of the phantom
    if args.nang is not None:
        print('\nCalculating analytical radon transform of the phantom ....')

        sinogram = radon_transform_analytical(phantom, LUT, npix, nang)
        sinogram[:, :] = sinogram[:, ::-1]
        sinogram[:, :] = np.roll(sinogram, 1, axis=1)

        ##  Plot Shepp-Logan phantom
        if args.plot is True:
            dis.plot(
                sinogram,
                'Sinogram  ' + str(nang) + ' nang X ' + str(npix) + ' npix')

        ##  Write sinogram
        if args.filein is None:
            filename = path + 'shepp_logan_pix' + common + '_ang'
        else:
            filename = path + name + '_pix' + common + '_ang'

        if nang < 10:
            filename += '000' + str(nang) + '_rt_anal_sino' + '.DMP'
        elif nang < 100:
            filename += '00' + str(nang) + '_rt_anal_sino' + '.DMP'
        elif nang < 1000:
            filename += '0' + str(nang) + '_rt_anal_sino' + '.DMP'
        else:
            filename += str(nang) + '_rt_anal_sino' + args.file_format

        io.writeImage(filename, sinogram)

        print('\nWriting sinogram in:\n', filename)

    print('\n\n')
예제 #23
0
def main():
    print('\n')
    print('##############################################')
    print('##############################################')
    print('####                                      ####')
    print('####         DOWNSAMPLE SINOGRAM          ####')
    print('####                                      ####')      
    print('##############################################')
    print('##############################################')  
    print('\n') 


    ##  Get input arguments
    args = getArgs()


    
    ##  Read input sinogram
    pathin = args.pathin
    if pathin[len(pathin)-1] != '/':
        pathin += '/'

    filename = args.sino
    sino = io.readImage( pathin + filename )
    nang , npix = sino.shape

    print('\nInput path:\n', pathin)
    print('\nInput sinogram:\n', filename)
    print('Sinogram size: ', nang,' ang  X  ', npix,' pixels')


    
    ##  Calculate downsampling factors
    factors = calc_downsampl_factors( nang )
    nfact = len( factors )
    
    print('\nNumber of downsampling factors: ', nfact)


    
    ##  Get projection geometry  
    ##  1) Case of equiangular projections distributed in [0,180)
    if args.geometry == '0':
        angles = np.arange( nang )
        angles = ( angles * 180.0 )/myFloat( nang )
        print('\nDealing with equally angularly spaced projections in [0,180)')

    ##  2) Case of equally sloped projections distributed in [0,180) 
    elif args.geometry == '1':
        angles = create_pseudo_polar_angles( nang ) * 180.0 / np.pi
        print('\nDealing with equally sloped projections in [0,180)') 

    ##  3) Case of list of projection angles in degrees
    else:
        geometryfile = pathin + args.geometry
        angles = np.fromfile( geometryfile , sep="\t" )
        nang = len( angles )
        print('\nReading list of projection angles: ', geometryfile)



    ##  Additional label for output downsampled sinogram
    label_base = '.angle_downsampl.'


    
    ##  Get output directory
    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout

    if pathout[len(pathout)-1] != '/':
        pathout += '/'

    print('\nOutput directory:\n', pathout)



    ##  Loop on each downsampling factor
    for i in range( nfact ):
        ##  Create downsampled version of the original sinogram
        print('\n########################################')
        print('\nDownsampling with factor: ', factors[i])
        sino_down , anglist_new , nang_new = discard_proj( sino , angles , factors[i] )

        ##  Naming conventions for ordering purpose
        if nang_new < 100:
            label_add = '00' + str( nang_new )
        elif nang_new < 1000:
            label_add = '0'+str( nang_new )
        else:
            label_add = str( nang_new )  

        ##  Create name for the output sinogram and the corresponding
        ##  list of projection angles
        filename_out = filename + label_base + label_add + '.sin.DMP'
        fileang = filename + label_base + label_add + '.txt'

        print('\nCreating files:\n', filename_out,'\n', fileang)

        ##  Save downsampled sinogram
        io.writeImage( pathout + filename_out , sino_down )

        ##  Save list of projection angles
        fw = open( pathout + fileang , 'w' )
        for i in range( nang_new ):
            fw.write("%.4f\n" % anglist_new[i] )
        fw.close()
    
    print('\n')
예제 #24
0
def main():
    print('\n')
    print('################################################')
    print('################################################')
    print('############                        ############')
    print('############   MY IMAGE TRANSFORM   ############')
    print('############                        ############')
    print('################################################')
    print('################################################')
    print('\n')

    ##  Get arguments
    args = getArgs()

    ##  Get input path
    pathin = args.pathin

    if pathin[len(pathin) - 1] != '/':
        pathin += '/'

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

    ##  Get output path
    if args.pathout is None:
        pathout = pathin
        flag_rename = 1
    else:
        pathout = args.pathout
        if pathout == pathin:
            flag_rename = 1
        else:
            flag_rename = 0

    if pathout[len(pathout) - 1] != '/':
        pathout += '/'

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

    ##  Get single input image and apply array of actions
    if args.input is not (None):
        fileinput = args.input
        flag_single = 1

    ##  Get group of images and apply array of actions

    elif args.label is not (None):
        curr_dir = os.getcwd()
        os.chdir(pathin)

        label = args.label
        fileinput = sorted(glob.glob('*' + label + '*'))
        flag_single = 0

        os.chdir(curr_dir)

    ##  Get list of actions to be performed
    if args.action is not (None):
        actionArray = getListOfActions(args.action)

        ##  Loop on all the listed actions and the listed inputs
        if flag_single:
            print('\nReading image: ', fileinput)
            imageArray = io.readImage(pathin + fileinput)

            for action in actionArray:
                if action == 'rc':
                    print('Applying clockwise rotation of 90 degrees')
                    imageArray = rotate90Clockwise(imageArray)

                if action == 'ra':
                    print('Applying counter-clockwise rotation of 90 degrees')
                    imageArray = rotate90Counterclockwise(imageArray)

                if action == 'fv':
                    print('Applying vertical flip')
                    imageArray = flipVertically(imageArray)

                if action == 'fh':
                    print('Applying horizontal flip')
                    imageArray = flipHorizontally(imageArray)

                if action == 'tr':
                    print('Applying transpose')
                    imageArray = transposeImage(imageArray)

                if flag_rename and args.overwrite is False:
                    newFileName = createOutputName(fileinput, action)
                else:
                    newFileName = fileinput

                print('Output file = ', newFileName)

            io.writeImage(pathout + newFileName, imageArray)

        else:
            for index in range(len(fileinput)):
                print('Reading image: ', fileinput[index])
                imageArray = io.readImage(pathin + fileinput[index])

                for action in actionArray:
                    if action == 'rc':
                        print('Applying clockwise rotation of 90 degrees')
                        imageArray = rotate90Clockwise(imageArray)

                    if action == 'ra':
                        print(
                            'Applying counter-clockwise rotation of 90 degrees'
                        )
                        imageArray = rotate90Counterclockwise(imageArray)

                    if action == 'fv':
                        print('Applying vertical flip')
                        imageArray = flipVertically(imageArray)

                    if action == 'fh':
                        print('Applying horizontal flip')
                        imageArray = flipHorizontally(imageArray)

                    if action == 'tr':
                        print('Applying transpose')
                        imageArray = transposeImage(imageArray)

                    if flag_rename and args.overwrite is False:
                        newFileName = createOutputName(fileinput[index],
                                                       action)
                    else:
                        newFileName = fileinput[index]
                    print('Output file = ', newFileName)

                io.writeImage(pathout + newFileName, imageArray)

        print('\n')

    ##  Change dynamic range of grey levels
    elif args.dynRange is not (None):
        dynRange = args.dynRange
        [minValue, maxValue] = [
            myFloat(dynRange.split(':')[0]),
            myFloat(dynRange.split(':')[1])
        ]
        print('Selected dynamic range interval: [', minValue, ',', maxValue,
              ']')
        # loop on all the listed actions and the listed inputs

        if flag_single:
            print('\nReading image: ', fileinput)
            imageArray = io.readImage(pathin + fileinput)

            print('Changing dynamic range')
            imageArray = changeDynamicRange(imageArray, minValue, maxValue)

            if flag_rename and args.overwrite is False:
                newFileName = createOutputName(fileinput, 'dr')
            else:
                newFileName = fileinput

            io.writeImage(pathout + newfileName, imageArray)

        else:
            for index in range(len(fileinput)):
                print('\nReading image: ', fileinput[index])
                imageArray = io.readImage(pathin + fileinput[index])

                print('Changing dynamic range')
                imageArray = changeDynamicRange(imageArray, minValue, maxValue)

                if flag_rename and args.overwrite:
                    newFileName = createOutputName(fileinput[index], 'dr')
                else:
                    newFileName = fileinput[index]

                io.writeImage(pathout + newFileName, imageArray)

        print('\n')

    ##  Change dynamic range of grey levels
    elif args.crop is not (None):
        roiEdges = args.crop

        if roiEdges.find(':') == -1:
            roiEdges = int(roiEdges)
            flag_square = 1
            print('\nCrop center square of side: ', roiEdges)

        else:
            roiEdges = roiEdges.split(':')
            flag_square = 0

            if len(roiEdges) == 4:
                edge1 = np.array([int(roiEdges[0]), int(roiEdges[1])])
                edge2 = np.array([int(roiEdges[2]), int(roiEdges[3])])

            elif len(roiEdges) == 3:
                edge1 = np.array([int(roiEdges[0]), int(roiEdges[1])])
                width_x = int(roiEdges[2])
                width_y = int(roiEdges[3])
                edge2 = np.array([edge1[0] + width_x, edge1[1] + width_y])

            print('\nEdges of the ROI to crop:  edge1 = ( ', edge1[0], ' , ',
                  edge1[1], ')   edge2 = ( ', edge2[0], ' , ', edge2[1], ' )')

        ##  Loop on all the listed actions and the listed inputs
        if flag_single:
            print('\nReading image: ', fileinput)
            imageArray = io.readImage(pathin + fileinput)

            if flag_square:
                nrows, ncols = imageArray.shape
                edge1 = np.array([
                    int((nrows - roiEdges) * 0.5),
                    int((nrows - roiEdges) * 0.5)
                ],
                                 dtype=int)
                edge2 = np.array([edge1[0] + roiEdges, edge1[0] + roiEdges],
                                 dtype=int)

            print('\nCropping selected ROI')
            imageArray = cropROI(imageArray, edge1, edge2)

            plt.imshow(imageArray, cmap=cm.Greys_r)
            plt.show()

            if flag_rename and args.overwrite is False:
                newFileName = createOutputName(fileinput[index], 'cr')
            else:
                newFileName = fileinput[index]

            io.writeImage(pathout + newFileName, imageArray)

        else:
            for index in range(len(fileinput)):
                print('\nReading image: ', fileinput[index])
                imageArray = io.readImage(pathin + fileinput[index])

                if flag_square:
                    nrows, ncols = imageArray.shape
                    edge1 = np.array([
                        int((nrows - roiEdges) * 0.5),
                        int((nrows - roiEdges) * 0.5)
                    ],
                                     dtype=int)
                    edge2 = np.array(
                        [edge1[0] + roiEdges, edge1[0] + roiEdges], dtype=int)

                print('\nCropping selecting ROI')
                imageArray = cropROI(imageArray, edge1, edge2)

                if flag_rename and args.overwrite is False:
                    newFileName = createOutputName(fileinput[index], 'cr')
                else:
                    newFileName = fileinput[index]

                io.writeImage(pathout + newFileName, imageArray)

        print('\n')

    print('\n')
    print('################################################')
    print('################################################')
    print('############                        ############')
    print('############   MY IMAGE TRANSFORM   ############')
    print('############                        ############')
    print('################################################')
    print('################################################')
    print('\n')
예제 #25
0
def write_output_file( array , mode , args ):
    ##  Get path
    path = args.path
    if path[len(path)-1] != '/':
        path += '/'     


    ##  Get degree
    deg = args.degree
    str_deg = '_deg' + str( deg )


    ##  String for number of pixels
    npix = args.npix

    if npix < 10:
        common = '000' + str( npix )    
    elif npix < 100:
        common = '00' + str( npix )
    elif npix < 1000:
        common = '0' + str( npix )
    else:
        common = str( npix )         


    ##  Save phantom
    if mode == 'image':
        if args.fileout is None:
            filename = path + 'radial_phantom'
        else:
            name = args.fileout
            filename = path + name + '_pix'

        filename += common + str_deg + args.file_format
        io.writeImage( filename , array )   
        print('\nWriting sinogram in:\n', filename)


    ##  Save sinogram
    elif mode == 'sinogram':
        nang = args.nang

        if args.fileout is None:
            filename = path + 'radial_phantom' + common + '_ang'
        else:
            name = args.fileout
            filename = path + name + '_pix' + common + '_ang'

        string = '_rt_anal_sino' 
        if args.dpc is True:
            string += '_dpc'

        if nang < 10:
            filename += '000' + str( nang )
        elif nang < 100:
            filename += '00' + str( nang ) 
        elif nang < 1000:
            filename += '0' + str( nang ) 
        else:
            filename += str( nang )  

        filename += string + str_deg + args.file_format 
        
        io.writeImage( filename , array )   
        print('\nWriting sinogram in:\n', filename)  
예제 #26
0
def main():
    print('\nCREATE PHANTOM WITH DIFFERENT CNR\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
    filein  = args.filein
    img     = io.readImage( pathin + filein ).astype( myfloat )
    shape   = np.array( img.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( img , 'Input image' )
    else:
        dim = 3
        nz , nrows , ncols = shape
        print('Image size: ', nz , ' X ' , nrows,' X ', ncols)
        if args.plot is True:
            dis.plot( img[0,:,:] , 'Input image' ) 
        

    ##  Get list of CNR     
    cnr_str = args.cnr
        
    if cnr_str.find( ':' ) == -1:
        cnr  = cnr_str
        n_cnr = 1
        print( 'Selected 1 factor: ' , cnr )
    else:
        cnr_str = np.array( cnr_str.split( ':' ) ).astype( myfloat )
        cnr     = np.linspace( cnr_str[0] , cnr_str[1] , np.int( cnr_str[2] ) )
        n_cnr   = len( cnr )
        print( 'Selected 1 factor: ' , cnr )
    print( '\n' )


    ##  Loop on each CNR value
    img_cnr = img.copy()

    for i in range( n_cnr ):
        img_cnr[:] = img
        img_cnr *= cnr[i]

        if n_cnr < 10:
            n_str = 'cnr' + str( i )
        elif n_cnr < 100:
            if i < 10:
                n_str = 'cnr0' + str( i )
            else:
                n_str = 'cnr' + str( i ) 

        fileout  = filein[:len(filein)-4] + '_' + n_str + '.DMP'
        io.writeImage( pathout + fileout , img_cnr )
        print( 'Created phantom factor: ' , cnr[i] , '\n', pathout + fileout) 

    print('\n\n')
예제 #27
0
def main():
    print('\n')
    print('#########################################################')
    print('#########################################################')
    print('###                                                   ###')
    print('###     ANALYTICAL RADON TRANSFORM OF SHEPP-LOGAN     ###')        
    print('###                                                   ###')     
    print('#########################################################')
    print('#########################################################') 
    print('\n')


    
    ##  Get arguments
    args = getArgs()


    
    ##  Get number of pixels
    npix = args.npix
    nang = args.nang
    
    print('\nNumber of pixels: ', npix)
    print('Number of views: ', nang)   

    
    
    ##  Create look-up-table of Shepp-Logan ellipses or read specifics from file
    if args.filein is None:
        LUT = lut_shepp_logan( npix , nang ) 
        print('\nCreated LUT for Shepp-Logan phantom')

    else:
        lut_file = np.loadtxt( args.filein )
        LUT = lut_generic_phantom( lut_file , npix , nang )
        
        if args.filein.find( '/' ) == -1:
            name = args.filein.split( '.' )[0]
        else:
            tokens = args.filein.split( '/' )
            name = tokens[len(tokens)-1].split('.')[0]  

        print('\nReading LUT for phantom from file:\n', args.filein)
        print('Label selected for the putput files: ', name)
        


    ##  Create Shepp-Logan phantom
    phantom = create_phantom( LUT , npix )

    

    ##  Write phantom
    path = args.path
    if path[len(path)-1] != '/':
        path += '/'

    if args.filein is None:
        filename = path + 'shepp_logan_pix'
    else:
        filename = path + name + '_pix'

    if npix < 10:
        common = '000' + str( npix )    
    elif npix < 100:
        common = '00' + str( npix )
    elif npix < 1000:
        common = '0' + str( npix )
    else:
        common = str( npix )

    filename += common + args.file_format

    io.writeImage( filename , phantom )   
    
    print('\nWriting sinogram in:\n', filename)     


    
    ##  Plot phantom
    if args.plot is True:
        dis.plot( phantom , 'Shepp-Logan phantom  npix=' + str( npix ) )

    

    ##  Compute analitically radon transform of the phantom
    if args.nang is not None:
        print('\nCalculating analytical radon transform of the phantom ....')
        
        sinogram = radon_transform_analytical( phantom , LUT , npix , nang )
        sinogram[:,:] = sinogram[:,::-1]
        sinogram[:,:] = np.roll( sinogram , 1 , axis=1 )


        ##  Plot Shepp-Logan phantom
        if args.plot is True:
            dis.plot( sinogram , 'Sinogram  ' + str( nang ) + ' nang X ' + str( npix ) + ' npix' )


        ##  Write sinogram
        if args.filein is None:
            filename = path + 'shepp_logan_pix' + common + '_ang'
        else:
            filename = path + name + '_pix' + common + '_ang'

        if nang < 10:
            filename += '000' + str( nang ) + '_rt_anal_sino' + '.DMP'
        elif nang < 100:
            filename += '00' + str( nang ) + '_rt_anal_sino' + '.DMP'
        elif nang < 1000:
            filename += '0' + str( nang ) + '_rt_anal_sino' + '.DMP'
        else:
            filename += str( nang ) + '_rt_anal_sino' + args.file_format  
        
        io.writeImage( filename , sinogram )
   
        print('\nWriting sinogram in:\n', filename)      
    
    
    print('\n\n')
예제 #28
0
def write_output_file(array, mode, args):
    ##  Get path
    path = args.path
    if path[len(path) - 1] != '/':
        path += '/'

    ##  Get degree
    deg = args.degree
    str_deg = '_deg' + str(deg)

    ##  String for number of pixels
    npix = args.npix

    if npix < 10:
        common = '000' + str(npix)
    elif npix < 100:
        common = '00' + str(npix)
    elif npix < 1000:
        common = '0' + str(npix)
    else:
        common = str(npix)

    ##  Save phantom
    if mode == 'image':
        if args.fileout is None:
            filename = path + 'radial_phantom'
        else:
            name = args.fileout
            filename = path + name + '_pix'

        filename += common + str_deg + args.file_format
        io.writeImage(filename, array)
        print('\nWriting sinogram in:\n', filename)

    ##  Save sinogram
    elif mode == 'sinogram':
        nang = args.nang

        if args.fileout is None:
            filename = path + 'radial_phantom' + common + '_ang'
        else:
            name = args.fileout
            filename = path + name + '_pix' + common + '_ang'

        string = '_rt_anal_sino'
        if args.dpc is True:
            string += '_dpc'

        if nang < 10:
            filename += '000' + str(nang)
        elif nang < 100:
            filename += '00' + str(nang)
        elif nang < 1000:
            filename += '0' + str(nang)
        else:
            filename += str(nang)

        filename += string + str_deg + args.file_format

        io.writeImage(filename, array)
        print('\nWriting sinogram in:\n', filename)
예제 #29
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')
예제 #30
0
def main():
    print('\n')
    print('#######################################')
    print('#######################################') 
    print('###                                 ###')
    print('###   STRUCTURAL SIMILARITY INDEX   ###')
    print('###                                 ###')
    print('#######################################')
    print('#######################################') 
    print('\n')

    
    
    ##  Get input arguments
    args = getArgs()



    ## Get oracle image
    currDir = os.getcwd()
    image1 = io.readImage( args.image1 )
    image1 = image1.astype( myfloat )

    print('\nReading reference image:\n', args.image1)
    print('Image shape: ', image1.shape)


    image_list = []
    results = []

    
    
    ##  CASE OF SINGLE IMAGE TO ANALYZE
    if args.image2 is not None:
        if args.image2.find( ':' ) == -1:
            image_list.append( args.image2 )
            image2 = io.readImage( args.image2 )  # image2 --> image to analyze
            image2 = image2.astype(myfloat)
            num_img = 1

            print('\nReading image to analyze:\n', args.image2)
            print('Image shape: ', image2.shape)


            ## Get time in which the prgram starts to run
            time1 = time.time()      


            ##  Scale image to analyze with respect to the reference one
            if args.scaling is True:
                print('\nPerforming linear regression ....')
                image2 =  proc.linear_regression( image1 , image2 )


            ##  Register images
            if args.register is True:
                print('\nPerforming registration of the image to analize ....')
                image2 = proc.image_registration( image2 , image1 , 'ssd' )


            ##  Crop resolution circle of the images
            if args.resol_circle is True:
                print('\nSelecting the resolution circle')
                image1 = proc.select_resol_square( image1 )
                image2 = proc.select_resol_square( image2 )                

            ##  Crop images if enabled
            if args.roi is not None:
                roi = args.roi

                if roi.find( ':' ) != -1:
                    roi = roi.split(',')
                    p0 = [int(roi[0].split(':')[1]),int(roi[0].split(':')[0])]
                    p1 = [int(roi[1].split(':')[1]),int(roi[1].split(':')[0])]
                
                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')
                
                    image1 = proc.crop_image( image1 , p0 , p1 )
                    image2 = proc.crop_image( image2 , p0 , p1 )

                else:
                    print('\nUsing pixels specified in file:\n', roi) 
                    pixels = np.loadtxt( roi )
                    pixels = pixels.astype( int )
                    p0 = np.array([pixels[0,0],pixels[0,1]])
                    p1 = np.array([pixels[len(pixels)-1,0],pixels[len(pixels)-1,1]])       
                        
                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')
                
                    image1 = proc.crop_image( image1 , p0 , p1 )
                    image2 = proc.crop_image( image2 , p0 , p1 )


            ##  Compute the gradient of the images, if enabled
            if args.gradient is True:
                image1 = compute_gradient_image( image1 )
                image2 = compute_gradient_image( image2 )


            ##  Check whether the 2 images have the same shape
            if image1.shape != image2.shape:
                sys.error('\nERROR: The input images have different shapes!\n')


            ##  Plot to check whether the images have the same orientation
            if args.plot is True:
                print('\nPlotting images to check orientation ....')
                img_list = [ image1 , image2 ]
                title_list = [ 'Oracle image' , 'Image to analyze' ]
                dis.plot_multi( img_list , title_list , 'Check plot' )        


            ##  Get window size
            window_size = args.window
            print('\nSize of the computation window: ', window_size)
            
            if window_size % 2 != 0:
                window_size += 1
                print('Window size is even: window size changed to ', window_size)
            
            
            ##  Get sigma of the gaussian kernel
            sigma = SIGMA
            print('Sigma of the gaussian kernel: ', sigma)


            ## Calculate map of SSIM values
            map_ssim , MSSIM = compute_map_ssim( image1 , image2 , window_size , sigma )
            results.append( MSSIM )

            if args.plot is True:
                print('\nPlotting images + map of ssim ....')
                img_list = [ image1 , image2 , map_ssim ]
                title_list = [ 'Oracle image' , 'Image to analyze' , 'Map of SSIM' ]
                dis.plot_multi( img_list , title_list , 'Images and map of SSIM' , colorbar=True )

            
            ##  Save SSIM map 
            filename = args.image2[:len(args.image2)-4] + '_ssim_map.png'
            io.writeImage( filename , map_ssim )


        
        ##  CASE OF MULTIPLE SPECIFIC IMAGES
        else:
            image_list = args.image2.split(':')
            img_list = [ ]
            title_list = [ ]
            num_img = len( image_list )

            for im in range( num_img ):
                img_file = image_list[im]
                image1 = io.readImage( args.image1 )
                image2 = io.readImage( img_file )  # image2 --> image to analyze
                image2 = image2.astype(myfloat)
                print('\nReading image to analyze:\n', args.image2)
                print('Image shape: ', image2.shape)

                
                ##  Get time in which the prgram starts to run
                time1 = time.time()      


                ##  Scale image to analyze with respect to the reference one
                if args.scaling is True:
                    print('\nPerforming linear regression ....')
                    image2 =  proc.linear_regression( image1 , image2 )


                ##  Register images
                if args.register is True:
                    print('\nPerforming registration of the image to analize ....') 
                    image2 = proc.image_registration( image2 , image1 , 'ssd' ) 


                ##  Crop resolution circle of the images
                if args.resol_circle is True:
                    print('\nSelecting the resolution circle')
                    image1 = proc.select_resol_square( image1 )
                    image2 = proc.select_resol_square( image2 )

                
                ##  Crop images if enabled
                if args.roi is not None:
                    roi = args.roi

                    if args.roi.find(',') != -1:
                        roi = roi.split(',')
                        p0 = [int(roi[0].split(':')[1]),int(roi[0].split(':')[0])]
                        p1 = [int(roi[1].split(':')[1]),int(roi[1].split(':')[0])]
                
                        print('Cropping rectangular ROI with vertices:  ( ', \
                                p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')
                
                        image1 = proc.crop_image( image1 , p0 , p1 )
                        image2 = proc.crop_image( image2 , p0 , p1 )

                    else:
                        print('\nUsing pixels specified in file:\n', roi) 
                        pixels = np.loadtxt( roi )
                        pixels = pixels.astype( int )
                        p0 = np.array([pixels[0,0],pixels[0,1]])
                        p1 = np.array([pixels[len(pixels)-1,0],pixels[len(pixels)-1,1]])       
                        
                        print('Cropping rectangular ROI with vertices:  ( ', \
                                p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')
                
                        image1 = proc.crop_image( image1 , p0 , p1 )
                        image2 = proc.crop_image( image2 , p0 , p1 )     
                

                ##  Compute the gradient of the images, if enabled
                if args.gradient is True:
                    image1 = compute_gradient_image( image1 )
                    image2 = compute_gradient_image( image2 )


                ##  Check whether the 2 images have the same shape
                if image1.shape != image2.shape:
                    sys.exit('\nERROR: The input images have different shapes!\n')


                ##  Plot to check whether the images have the same orientation
                if args.plot is True:
                    print('\nPlotting images to check orientation ....')
                    img_list2 = [ image1 , image2 ]
                    title_list2 = [ 'Oracle image' , 'Image to analyze' ]
                    dis.plot_multi( img_list2 , title_list2 , 'Check plot' )   

                
                ##  Get window size
                window_size = args.window
                print('\nSize of the computation window: ', window_size)
                
                if window_size % 2 != 0:
                    window_size += 1
                    print('Window size is even: window size changed to ', window_size)
                
                
                ##  Get sigma of the gaussian kernel
                sigma = SIGMA
                print('Sigma of the gaussian kernel: ', sigma)


                ##  Calculate map of SSIM values
                map_ssim , MSSIM = compute_map_ssim( image1 , image2 , window_size , sigma )
                results.append( MSSIM )

                map_ssim[ map_ssim < 0 ] = 0.0

                if args.plot is True:
                    img_list.append( map_ssim )
                    title_list.append( 'SSIM map n.' + str( im + 1 ) )

                
                ##  Save SSIM map 
                filename = img_file[:len(img_file)-4] + '_ssim_map.png'
                io.writeImage( filename , map_ssim )
                
            if args.plot is True:
                print('\nPlotting images + map of ssim ....')
                dis.plot( img_list[0] )
                dis.plot( img_list[1] )
                dis.plot_multi_colorbar( img_list , title_list , 'Maps of SSIM' ) 



    ##  CASE OF BUNCH OF IMAGES TO ANALYZE 
    else:
        os.chdir(args.path)
        image_list = sorted( glob.glob('*') )
        num_images = len( image_list )
        img_list.append( image1 )
        title_list.append('Oracle image') 

        
        ##  Get time in which the prgram starts to run
        time1 = time.time()


        ##  Loop on all the images to analyze
        for i in range( num_img ):
            image1 = io.readImage( args.image1 ) 
            image2 = io.readImage( image_list[i] )
            image2 = image2.astype(myfloat)

            print('\n\n\nIMAGE TO ANALYZE NUMBER: ', i)
            print('\nReading image to analyze:\n', fileIn[i])
            print('Image shape: ', image2.shape)

            
            ##  Scale image to analyze with respect to the reference one
            if args.scaling is True:
                print('\nPerforming linear regression ....')  
                image2 = proc.linear_regression( image1 , image2 )


            ##  Register images
            if args.register is True:
                print('\nPerforming registration of the image to analize ....') 
                image2 = proc.image_registration( image2 , image1 , 'ssd' )


            ##  Crop resolution circle of the images
            if args.resol_circle is True:
                print('\nSelecting the resolution circle')
                image1 = proc.select_resol_square( image1 )
                image2 = proc.select_resol_square( image2 ) 


            ##  Crop images if enabled
            if args.roi is not None:
                roi = args.roi

                if args.roi.find(',') != -1:
                    roi = roi.split(',')
                    p0 = [int(roi[0].split(':')[1]),int(roi[0].split(':')[0])]
                    p1 = [int(roi[1].split(':')[1]),int(roi[1].split(':')[0])]
                
                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')
                
                    image1 = proc.crop_image( image1 , p0 , p1 )
                    image2 = proc.crop_image( image2 , p0 , p1 )

                else:
                    print('\nUsing pixels specified in file:\n', roi) 
                    pixels = np.loadtxt( roi )
                    pixels = pixels.astype( int )
                    p0 = np.array([pixels[0,0],pixels[0,1]])
                    p1 = np.array([pixels[len(pixels)-1,0],pixels[len(pixels)-1,1]])       
                        
                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')
                
                    image1 = proc.crop_image( image1 , p0 , p1 )
                    image2 = proc.crop_image( image2 , p0 , p1 )    


            ##  Compute the gradient of the images, if enabled
            if args.gradient is True:
                image1 = compute_gradient_image( image1 )
                image2 = compute_gradient_image( image2 )


            ##  Check whether the 2 images have the same shape
            if image1.shape != image2.shape and args.roi is None:
                sys.error('\nERROR: The input images have different shapes!\n')


            ##  Plot to check whether the images have the same orientation
            if args.plot is True:
                print('\nPlotting images to check orientation ....')
                img_list = [ image1 , image2 ]
                title_list = [ 'Oracle image' , 'Image to analyze' ]
                dis.plot_multi( img_list , title_list , 'Check plot' )    


            ##  Get window size
            window_size = args.window
            print('\nSize of the computation window: ', window_size)
            
            if window_size % 2 != 0:
                window_size += 1
                print('Window size is even: window size changed to ', window_size)
            
            
            ##  Get sigma of the gaussian kernel
            sigma = SIGMA
            print('Sigma of the gaussian kernel: ', sigma)


            ##  Calculate map of SSIM values
            map_ssim,MSSIM = compute_map_ssim( image1 , image2 , window_size , sigma )
            results.append( MSSIM )


            ##  Diplay map of SSIM
            if args.plot is True:
                fig = plt.figure()
                plt.title('Map of SSIM indeces')
                plt.imshow(map_ssim,cmap = cm.Greys_r)
                plt.colorbar()
                plt.show()


            ##  Save SSIM map
            filename = image_list[i][:len(image_list[i])-4] + '_ssim_map.png'
            io.writeImage( filename , map_ssim )
        os.chdir(currDir)



    ##  Summary print of the results
    print('\n\nSUMMARY OF THE RESULTS:\n')
    print('\nReference image:\n', args.image1)

    for i in range( num_img ):
        print('\nTest image number ', i,'\n', image_list[i])
        print('SSIM = ' , results[i])



    ##  Get time elapsed for the run of the program
    time2 = time.time() - time1
    print('\n\nTime elapsed for the calculation: ', time2)



    ##  Write log file
    write_log_file( args , image_list , results )


    print('\n\n')
예제 #31
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')
예제 #32
0
def create_dataset( args ):
    ##  Get input image
    image_ref = io.readImage( args.inputs )
    npix = image_ref.shape[0]


    ##  Create impulsed image
    nimp = int( np.floor( npix / nimp_factor ) )
    c = npix * 0.5
    ind_imp = np.zeros( ( nimp , 2 ) , dtype=int )
    i = 0

    print('\nSelecting impulse locations ...')

    while i < nimp:
        x = int( np.round( np.random.rand() * npix ) )
        y = int( np.round( np.random.rand() * npix ) )
        dist1 = np.ceil( np.sqrt( ( x - c )**2 + ( y - c )**2 ) )

        if dist1 < c:
            if i != 0:
                for j in range( i + 1 ):
                    x0 = ind_imp[j,0];  y0 = ind_imp[j,1]
                    dist2 = np.ceil( np.sqrt( ( x - x0 )**2 + ( y - y0 )**2 ) )
                    if dist2 <= r:
                        break
                    elif dist2 > r and j < i:
                        continue
                    elif dist2 > r and j == i:
                        ind_imp[i,0] = x;  ind_imp[i,1] = y
                        i += 1
            else:
                ind_imp[i,0] = x;  ind_imp[i,1] = y 
                i += 1

    print('... locations selected!')

    print('\nImpulse locations:')
    pp.printArray2D( ind_imp  )
    
    image_imp = image_ref.copy()
    imp_factor = args.imp_factor

    for i in range( len( ind_imp ) ):
        x0 = ind_imp[i][0];  y0 = ind_imp[i][1] 
        image_imp[x0,y0] += image_imp[x0,y0] * imp_factor


    ##  Create sinograms
    nang = int( np.ceil( npix * np.pi * 0.5 ) )
    angles = myfloat( np.arange( nang ) / myfloat( nang ) * 180.0 )
    image_ref = myfloat( image_ref );  image_imp = myfloat( image_imp )

    sino_ref = grid.forwproj( image_ref , angles )
    sino_imp = grid.forwproj( image_imp , angles )


    ##  Check plots
    if args.plot is True:
        image_list = [ image_ref , image_imp ]
        title_list = [ 'Reference image' , 'Impulsed image' ]
        dis.plot_multi( image_list , title_list )

        image_list = [ sino_ref , sino_imp ]
        title_list = [ 'Sinogram of reference image' , 'Sinogram of impulsed image' ]
        dis.plot_multi( image_list , title_list )


    ##  Write output files
    namebase = args.inputs
    
    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 output files ...')

    fileout = pathout + filename + '_lir.DMP'
    io.writeImage( fileout , image_imp )
    print( fileout )

    fileout = pathout + filename + '_sin.DMP'
    io.writeImage( fileout , sino_ref )
    print( fileout )
                         
    fileout = pathout + filename + '_lir_sin.DMP'
    io.writeImage( fileout , sino_imp )
    print( fileout )

    fileout = pathout + filename + '_lir.txt'
    np.savetxt( fileout , ind_imp , newline= '\n' )
    print( fileout )
    print('\n')
예제 #33
0
def main():
    print('\nRESCALE IMAGE\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[0] , imagein.shape[1]
        
        print('\nReading image:', filein)
        print('Image size: ', nrows,' X ', ncols)


        ##  Check plot
        if args.plot is True:
            dis.plot( imagein , 'Input image' )
        

        ##  Make image square
        if args.square is True:
            if nrows < ncols:
                imagein = imagein[:,:nrows]
            else:
                imagein = imagein[:ncols,:]    


        ##  Rescaled image
        if args.rescale is not None:
            rescale = args.rescale
            nrows_new = int( nrows * rescale )
            ncols_new = int( ncols * rescale )

        else:
            nrows_new = ncols_new = args.npix
            rescale = nrows_new / myfloat( nrows )

        image_rescale = rescale_image( imagein , rescale )

        print('\nRescaled factor: ', rescale)
        print('Rescaled-image size: ', image_rescale.shape)


        ##  Check plot
        if args.plot is True:
            dis.plot( image_rescale , 'Rescaled image -- factor = ' 
                                         + str( rescale ) ) 

            
        ##  Write noisy image to file
        fileout = filein[:len(filein)-4] + '_pix' 
        if nrows_new < 100:
            fileout += '00' + str( nrows_new ) + '.DMP'
        elif nrows_new < 1000:
            fileout += '0' + str( nrows_new ) + '.DMP'
        else:
            fileout += str( nrows_new ) + '.DMP' 

        io.writeImage( pathout + fileout , image_rescale )
        print('\nWriting rescaled image:', fileout)          


    
    ##  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[0] , imagein.shape[1]
            
            print('\nReading image:\n', files[i])
            print('\nImage size: ', nrows,' X ', ncols)


            ##  Make image square
            if args.square is True:
                if nrows < ncols:
                    imagein = imagein[:,:nrows]
                else:
                    imagein = imagein[:ncols,:]


            ##  Rescaled image
            if args.rescale is not None:
                rescale = args.rescale
                nrows_new = int( nrows * rescale )
                ncols_new = int( ncols * rescale )

            else:
                nrows_new = ncols_new = args.npix
                rescale = nrows_new / myfloat( nrows )

            image_rescale = rescale_image( imagein , rescale )

            print('\nRescaled factor: ', rescale)
            print('Rescaled-image size: ', image_rescale.shape)                   
                
            
            ##  Write noisy image to file
            fileout = files[i][:len(files[i])-4] + '_pix' 
            if nrows_new < 100:
                fileout += '00' + str( nrows_new ) + '.DMP'
            elif nrows_new < 1000:
                fileout += '0' + str( nrows_new ) + '.DMP'
            else:
                fileout += str( nrows_new ) + '.DMP' 

            io.writeImage( pathout + fileout , image_rescale )
            print('\nWriting rescaled image:', fileout)  
    
    print('\n\n')
예제 #34
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' )