Exemplo n.º 1
0
def main():         
    ##  Input file 
    filein  = sys.argv[1]
    fileout = sys.argv[2]

    if len( sys.argv ) == 4:
        color = sys.argv[3]
    else:
        color = 'green'

    print('\nInput:\n', filein)
    print('\nOutput:\n', fileout)


    ##  Read files
    y = io.readImage( filein ).astype( np.float32 )
    #y = proc.select_resol_square( y )

    y[:] = ( y - np.min( y ) ) / ( np.max( y ) - np.min( y ) )

    dis.plot( y )


    ##  Plot 
    plot_histo( y.reshape(-1) , fileout , color )
Exemplo n.º 2
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')
Exemplo n.º 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')


    
    ##  Getting projection geometry  
    angles = create_projection_angles( args , nang )



    ##  Downsample in angles
    sino_down , angles_down = downsample_sinogram_angles( sino , angles , args )


    
    ##  Display check plot
    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 & angle list
    write_output_files( sino_down , angles_down , args , pathin , filename )
                 
    print('\n')
Exemplo n.º 4
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 )
Exemplo n.º 5
0
def main():
    path_rec = "/home/arcusfil/tomcat/Data/benchmark_gridrec_beatty/recs/"

    curr_dir = os.getcwd()

    os.chdir(path_rec)
    reco_list = sorted(glob.glob("*.DMP"))
    num_reco = len(reco_list)
    os.chdir(curr_dir)
    print("\nNumber of reconstructions: ", num_reco, "\n")

    count = 0
    for i in range(num_reco):
        image = io.readImage(path_rec + reco_list[i])
        mean = np.mean(image)
        if np.isnan(mean) == True:
            count += 1
        print("Analyzed images: %d" % i)

    print("\nNumber of Nan images: ", count)
Exemplo n.º 6
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 )
Exemplo n.º 7
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 )
Exemplo n.º 8
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)
Exemplo n.º 9
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')
Exemplo n.º 10
0
def main():
    print('\n')
    print('############################################################')  
    print('############################################################')
    print('####                                                    ####')
    print('####            RESOLUTION WITH ERROR FUNCTION          ####')
    print('####             FITTING OF THE LINE PROFILE            ####')
    print('####                                                    ####')  
    print('############################################################')  
    print('############################################################')



    ##  Get input arguments
    args = getArgs()



    ##  Get filenames
    filenames = args.images

    if filenames.find( ':' ) != -1:
        filenames = filenames.split( ':' )
        nimg = len( filenames )
    else:
        filenames = [ filenames , filenames ]
        nimg = 1

    print('\nNumber of input images: ', nimg)

    

    ##  Get delimiting points
    aux = args.delimiters.split( ',' )
    p1 = np.array( [ myint( aux[0].split( ':' )[0] ) , 
                     myint( aux[0].split( ':' )[1] ) ] )
    p2 = np.array( [ myint( aux[1].split( ':' )[0] ) , 
                     myint( aux[1].split( ':' )[1] ) ] )
    
    print('\nDelimiting points: (', p1[0],',', p1[1],')',' ', 
                               '(', p2[0],',', p2[1],')')

    num = myint( np.sqrt( ( p1[0] - p2[0] )**2 + ( p1[1] - p2[1] )**2 ) )
    x = np.linspace( p1[0] , p2[0] , num )
    y = np.linspace( p1[1] , p2[1] , num )


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



    ##  Calculate resolution with error function fitting
    for i in range( nimg ):
        print( '\n\nReading image:\n' , filenames[i] )
        
        if filenames[i].find( '/' ) != -1:
            prefix = filenames[i].split( '/' )
            prefix = prefix[len(prefix)-1]
            prefix = prefix[:len(prefix)-4]
        else:
            prefix = filenames[i][:len(filenames[i])-4] 

        image = io.readImage( filenames[i] )
        line_profile = image[ y.astype( myint ) , x.astype( myint ) ]

        if args.plot is True:
            dis.plot_line( image , line_profile , [ p1 , p2 ] )

        calc_resol( line_profile , filenames[i] , prefix , pathout , [ p1 , p2 ] , args )


    print('\n')
Exemplo n.º 11
0
def main():
    ##  Initial print
    print('\n')
    print('##############################################################')
    print('#############    KAISER-BESSEL RADON TRANSFORM   #############')
    print('##############################################################')
    print('\n')


    
    ##  Get the startimg time of the sinonstruction
    startTime = time.time()


    
    ##  Get input arguments
    args = getArgs()


    
    ##  Get path to input sino
    pathin = args.pathin


    
    ##  Get input image
    ##  You assume the image to be square
    image_name = pathin + args.image
    image = io.readImage( image_name )
    npix = image.shape[1]
    nang = args.nang

    print('\nInput image:\n', image_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)


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



    ##  Get projection geometry  
    ##  1) Case of equiangular projections distributed in [0,180)
    if args.geometry == '0':
        angles = np.arange( nang )
        angles = ( angles * np.pi )/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':
        print('\n\nDealing with equally-sloped projections in [0,180)')
  
        if nang % 4 != 0:
            print('\n\nERROR: in case of equally-sloped projections',
                  ' the number of angles has to be a multiple of 4')

        angles = createPseudoPolarAngles( nang )    

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



    ##  Get kaiser-bessel parameters
    kb_radius = args.kb_radius
    proj_support_y = 2.0 * kb_radius
    kb_degree = args.kb_degree
    print('\nKaiser-Bessel radius selected: ', kb_radius)
    print('\nKaiser-Bessel degree selected: ', kb_degree)  



    ##  Flag to specify whether you want to perform the
    ##  radon transform or its adjoint
    flag_adj = 0



    ##  Direct transformation on the pixel image into
    ##  ita B-spline image
    #kb_image = pixel_basis_to_kaiser_bessel( image , 0 )
    kb_image = image.copy()


    
    ##  Precalculate look-up-table for B-spline
    nsamples_y = args.lut_size
    LUT = init_lut_kaiser_bessel( nsamples_y , nang , kb_radius , kb_radius )

    if args.plot is True:
        dis.plot( LUT , 'Look-up-table' )



    ##  Perform B-spline radon transform
    LUT = LUT.astype( np.float32 ) 
    angles = angles.astype( np.float32 )
    sino = np.zeros( ( nang , npix ) , dtype=np.float32 )
    exit = grt.radon( sino , kb_image , flag_adj , LUT , LUT.shape[1] ,
                      npix , angles , nang , proj_support_y )
    sino[:,:] = np.roll( sino[:,::-1] , 1 , axis=1 )   



    ##  Convert sinogram from kaiser-bessel basis to the pixel one
    #sino = kaiser_bessel_basis_to_pixel( sino , kb_radius )



    ##  Show sino     
    if args.plot is True:
        dis.plot( sino , 'Sinogram' )    


    
    ##  Save sino
    saveSino( sino , angles , args )

    
    
    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('\n\nTime elapsed: ', (endTime-startTime)/60.0)
    print('\n')
Exemplo n.º 12
0
def main():
    ##  Initial print
    print('\n')
    print('#######################################')
    print('#############    PY-FBP   #############')
    print('#######################################')
    print('\n')

    ##  Get the startimg time of the reconstruction
    startTime = time.time()

    ##  Get input arguments
    args = getArgs()

    ##  Get path to input reco
    pathin = args.pathin

    ##  Get input reco
    ##  You assume the reco to be square
    sino_name = pathin + args.sino
    sino = io.readImage(sino_name).astype(myfloat)
    npix = sino.shape[1]
    nang = sino.shape[0]

    print('\nInput sino:\n', sino_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)

    ##  Show reco
    if args.plot is True:
        dis.plot(sino, 'Sinogram')

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

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

    print('Number of projection angles: ', nang)
    print('\nAngles:\n', angles)

    ##  Get center of rotation
    print('\nCenter of rotation placed at pixel: ', args.ctr)

    if args.ctr is None:
        ctr = npix * 0.5 + 1
    else:
        ctr = args.ctr

    sino = proc.sino_correct_rot_axis(sino, ctr)
    ctr = npix * 0.5

    ##  Enable edge padding
    if args.edge_padding is True:
        npix_old = sino.shape[1]
        sino = proc.sino_edge_padding(sino, 0.5)
        npix = sino.shape[1]
        i1 = int((npix - npix_old) * 0.5)
        i2 = i1 + npix_old
        ctr += i1

    ##  Get filter type
    filt = args.filt
    print('\nSelected filter: ', filt)

    ##  Get B-Spline setting
    bspline_degree = args.bspline_degree
    nsamples_y = args.lut_size
    proj_support_y = bspline_degree + 1

    if args.dpc is False:
        rt_degree = 0
    else:
        rt_degree = 1

    print('\nB-Spline degree selected: ', bspline_degree)
    print('LUT density: ', nsamples_y)
    print('B-Spline support: ', proj_support_y)
    print('Radon transform degree: ', rt_degree)

    ##  Compute iradon transform
    print('\nPerforming Filtered Backprojection ....\n')
    reco = fbp_bspline(sino[:, ::-1], angles, filt, bspline_degree, rt_degree,
                       args.plot)

    ##  Remove edge padding
    if args.edge_padding is True:
        reco = reco[i1:i2, i1:i2]

    ##  Show sino
    if args.plot is True:
        dis.plot(reco, 'Reconstruction')

    ##  Save sino
    save_reco(reco, args)

    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('\n\nTime elapsed: ', (endTime - startTime) / 60.0)
    print('\n')
Exemplo n.º 13
0
def main():
    ##  Initial print
    print('\n')
    print('########################################')
    print('#############    PY-SART   #############')
    print('########################################')
    print('\n')


    ##  Get the startimg time of the reconstruction
    startTime = time.time()


    ##  Get input arguments
    args = getArgs()


    ##  Get path to input reco
    pathin = args.pathin

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


    ##  Get input reco
    ##  You assume the reco to be square
    sino_name = pathin + args.sino
    sino = io.readImage( sino_name )
    npix = sino.shape[1]
    nang = sino.shape[0]

    print('\nInput sino:\n', sino_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)


    ##  Show reco
    if args.plot is True:
        checkPlot( sino , 'Sinogram' )


    ##  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 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)

    print('Number of projection angles: ', nang)


    ##  Get center of rotation
    if args.ctr is None:
        ctr = npix * 0.5
    else:
        ctr = args.ctr

    print('\nCenter of rotation placed at pixel: ', ctr)



    ##  Apply edge padding
    if args.edgepad != 0:
        npix_old = npix
        sino = edgepad( sino , args.edgepad )
        sino = sino.astype( myFloat )
        npix = sino.shape[1]
        print('\nEdge padded sinogram size: ', sino.shape[0],' X ', sino.shape[1])



    ##  Compute iradon transform
    print('\nPerforming SART iradon ....\n')
    niter = args.niter
    print('\nNumber of iterations:', niter)

    print('\nIter number  1 ....')
    reco = iradon_sart( np.rot90( sino ).astype(np.float64) , 
                        angles.astype(np.float64) )
    
    for i in range( niter - 1 ):
        print('\nIter number ', i +2,' ....')
        reco[:,:] = iradon_sart( np.rot90( sino ).astype(np.float64) ,
                                 angles.astype(np.float64) ,
                                 image=reco ) 


    
    ##  Crop image 
    if args.edgepad:
        i1 = int( 0.5 * ( npix - npix_old ))
        i2 = i1 + npix_old
        reco = reco[i1:i2,i1:i2]    

    
    
    ##  Show sino     
    if args.plot is True:
        checkPlot( reco , 'SART reconstruction' )


    ##  Save sino
    saveReco( reco , args )

    
    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('\n\nTime elapsed: ', (endTime-startTime)/60.0,' min')
    print('\n')
Exemplo n.º 14
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')
Exemplo n.º 15
0
def main():
    ##  Initial print
    print('\n')
    print('#######################################')
    print('#############    PY-FBP   #############')
    print('#######################################')
    print('\n')

    ##  Get the startimg time of the reconstruction
    startTime = time.time()

    ##  Get input arguments
    args = getArgs()

    ##  Get path to input reco
    pathin = args.pathin

    ##  Get input reco
    ##  You assume the reco to be square
    sino_name = pathin + args.sino
    sino = io.readImage(sino_name).astype(myfloat)
    npix = sino.shape[1]
    nang = sino.shape[0]

    print('\nInput sino:\n', sino_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)

    if args.plot is True:
        dis.plot(sino, 'Sinogram')

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

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

    print('Number of projection angles: ', nang)

    ##  DPC reconstruction
    dpc = args.dpc
    print('DPC reconstruction: ', dpc)

    ##  DPC reconstruction
    if args.dbp is True:
        dpc = args.dbp
        sino[:, :] = proc.diff_sino(sino)
        if args.plot is True:
            dis.plot(sino, 'Differential sinogram')
    print('DBP reconstruction: ', dpc)

    ##  Get center of rotation
    print('\nCenter of rotation placed at pixel: ', args.ctr)

    if args.ctr is None:
        ctr = npix * 0.5
    else:
        ctr = args.ctr
        sino = proc.sino_correct_rot_axis(sino, ctr)
        ctr = npix * 0.5

    ##  Enable edge padding
    if args.edge_padding is True:
        npix_old = sino.shape[1]
        sino = proc.sino_edge_padding(sino, 0.5)
        npix = sino.shape[1]
        i1 = int((npix - npix_old) * 0.5)
        i2 = i1 + npix_old
        ctr += i1

    ##  Get filter type
    filt = args.filt
    print('Selected filter: ', filt)

    ##  Get interpolation scheme
    interp = args.interp
    if interp == 'nn':
        print('\nSelected interpolation scheme: nearest neighbour')
    elif interp == 'lin':
        print('\nSelected interpolation scheme: linear interpolation')

    ##  Compute iradon transform
    print('\nPerforming Filtered Backprojection ....\n')
    reco = np.zeros((npix, npix), dtype=myfloat)
    reco[:, :] = iradon(sino[:, ::-1], npix, angles, ctr, filt, interp, dpc,
                        args)

    ##  Remove edge padding
    if args.edge_padding is True:
        reco = reco[i1:i2, i1:i2]

    ##  Show reconstruction
    if args.plot is True:
        dis.plot(reco, 'Reconstruction')

    ##  Save sino
    save_reco(reco, args)

    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('\n\nTime elapsed: ', (endTime - startTime) / 60.0)
    print('\n')
Exemplo n.º 16
0
def main():
    ##  Initial print
    print('\n')
    print('##############################################')
    print('#############   RADON TRANSFORM  #############')
    print('##############################################')
    print('\n')


    ##  Get the startimg time of the reconstruction
    startTime = time.time()


    ##  Get input arguments
    args = getArgs()


    ##  Get path to input reco
    pathin = args.pathin


    ##  Get input reco
    ##  You assume the reco to be square
    sino_name = pathin + args.sino
    sino = io.readImage( sino_name )
    npix = sino.shape[1]
    nang = sino.shape[0]

    print('\nInput sino:\n', sino_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)


    ##  Show reco
    if args.plot is True:
        checkPlot( sino , 'Sinogram' )


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

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

    print('Number of projection angles: ', nang)


    ##  Get interpolation scheme
    interp = args.interp
    if interp == 'nn':
        print('\nSelected interpolation scheme: nearest neighbour')
    elif interp == 'lin':
        print('\nSelected interpolation scheme: linear interpolation')
    else:
        print('''\nWARNING: ', interp,' does not correspond to any available
                  interpolation scheme; nearest neighbour interpolation will
                  be adopted''')
        interp = 'nn'



    ##  Get center of rotation
    if args.ctr is None:
        ctr = npix * 0.5
    else:
        ctr = args.ctr

    print('\nCenter of rotation placed at pixel: ', ctr)



    ##  Apply edge padding
    if args.edgepad != 0:
        npix_old = npix
        sino = edgepad( sino , args.edgepad )
        sino = sino.astype( myFloat )
        npix = sino.shape[1]
        ctr += int( 0.5 * ( npix - npix_old ))  
        print('\nEdge padded sinogram size: ', sino.shape[0],' X ', sino.shape[1])   




    ##  Compute radon transform
    reco = np.zeros( ( npix , npix ) , dtype=myFloat )
    reco[:,:] = iradonTransform( sino , angles , interp )


    
    ##  Crop image 
    if args.edgepad != 0:
        i1 = int( 0.5 * ( npix - npix_old ))
        i2 = i1 + npix_old
        print('\nnpix = ', npix,'  npix_old = ', npix_old,'  i1 = ', i1,
                '  i2 = ', i2)
        reco = reco[i1:i2,i1:i2]        

    
    
    ##  Show sino     
    if args.plot is True:
        checkPlot( reco , 'Sinogram' )


    
    ##  Save sino
    saveReco( reco , args )

    
    
    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('Time elapsed: ', (endTime-startTime)/60.0)
    print('\n')
Exemplo n.º 17
0
def main():
    print('\n')
    print('###############################################')
    print('###############################################')
    print('####                                       ####')
    print('####  RUN ANALYSIS OF THE RECONSTRUCTIONS  ####')
    print('####                                       ####')      
    print('###############################################')
    print('###############################################')  
    print('\n') 


    
    ##  Get input arguments
    args = getArgs()


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


        
    ##  Get analisys type
    analisys = args.analisys
    print('\nSelected analisys: ', analisys)


    ##  Get roi files
    if analisys == 'snr':
        roi_file = args.roi_fiji

        if roi_file.find(':') != -1:
            sys.exit('\nERROR: for the SNR analisys only 1 roi file is needed!')

        else:
            #fd = open( roi_file , 'r' )
            print('\nReading ROI file:\n', roi_file)
            pixels = np.loadtxt( roi_file )

            x = pixels[:,1].astype( np.int )
            y = pixels[:,0].astype( np.int )


    elif analisys == 'cnr':
        roi_file = args.roi_fiji

        if roi_file.find(':') == -1:
            sys.exit('\nERROR: for the CNR analisys 2 roi files are needed!')

        else:
            #fd = open( roi_file , 'r' )
            roi_file = roi_file.split(':')
            print('\nReading ROI file:\n', roi_file[0])
            pixels = np.loadtxt( roi_file[0] )
            
            x1 = pixels[:,1].astype( np.int )
            y1 = pixels[:,0].astype( np.int ) 

            print('\nReading ROI file:\n', roi_file[1])
            pixels = np.loadtxt( roi_file[1] )

            x2 = pixels[:,1].astype( np.int )
            y2 = pixels[:,0].astype( np.int ) 

   
   
    ##  Get reconstruction files
    label = args.label

    curr_dir = os.getcwd()
    os.chdir( pathin )

    rec_file_list = sorted( glob.glob( '*' + label + '*' ) )
    num_files = len( rec_file_list )

    os.chdir( curr_dir )

    if num_files == 0:
        sys.exit('\nNo file labelled with ', label ,' found in the folder:\n',
                  pathin)
    else:
        print('\nNumber of input files: ', num_files)


    
    ##  Organize input files
    plot_axis = args.plot_axis
    axes = []
    file_label = []
    
    
    if plot_axis.find(',') == -1:
        plot_axis_aux = args.plot_axis
        plot_axis_aux = plot_axis_aux.split(':')
        file_label.append( plot_axis_aux[0] )

        for j in range( 1 , len( plot_axis_aux ) ):
            axes.append( plot_axis_aux[j] )         
        
        print('\nPlot 2D selected using file label: ', file_label)
        print('Axis x values: ', axes )

    
    xlen = len( axes )
    xaxis = np.array( axes ).astype( myFloat )
    result = np.zeros( xlen , dtype=myFloat )

    axis_label = args.axis_label


    
    ##  Perform analisys  
    f = 0

    for i in range( xlen ):
        filein = rec_file_list[f]
        imagein = io.readImage( pathin + filein )
        print('\nInput image:\n', filein)

            
        ##  Perform analysis
        if analisys == 'snr':
            snr = an.snr_roi( imagein , x , y )
            
            if args.check_plot is True:
                imagein[x[:],y[:]] = 2.0
                plt.imshow( imagein , cmap=cm.Greys_r ); plt.show()

            result[i] = snr
            print('SNR = ', snr)


        if analisys == 'cnr':
            cnr = an.cnr_roi( imagein , x1 , y1  , x2 , y2 )

            if args.check_plot is True:
                imagein[x1[:],y1[:]] = 2.0
                imagein[x2[:],y2[:]] = -2.0 
                plt.imshow( imagein , cmap=cm.Greys_r ); plt.show() 
            
            result[i] = cnr
            print('CNR = ', cnr) 

        
        f += 1



    ##  Write output file
    fileout = args.fileout
    
    if os.path.isfile( fileout ) is True:
        sys.exit('\nERROR: output file:\n' + fileout + '\nalready exists!')

    print('\nWriting data for bar plot 3D to file:\n', fileout)
    fout = open( args.fileout , 'w' )

    fout.write('x:' + axis_label.upper() + ':' + str( len( xaxis ) ) )
    for i in range( len( xaxis ) ):
        fout.write('\n%4f' % xaxis[i])

    fout.write('\ny:' + analisys.upper() + ':' + str( len( result ) ) )
    for i in range( len( result ) ):
        fout.write('\n%4f' % result[i])

    fout.close()


    #print( xaxis )
    #print( result )



    ##  Check plot
    fig = plt.figure()
    plt.plot( xaxis , result , linewidth=3.0 )
    plt.xlabel( 'Number of views' , fontsize=18 )
    plt.ylabel( analisys.upper() , fontsize=18 ) 
    plt.show()
    
    
    print('\n')
Exemplo n.º 18
0
def main():
    ##  Initial print
    print('\n')
    print('##############################################')
    print('#############   RADON TRANSFORM  #############')
    print('##############################################')
    print('\n')

    ##  Get the startimg time of the reconstruction
    startTime = time.time()

    ##  Get input arguments
    args = getArgs()

    ##  Get path to input image
    pathin = args.pathin

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

    ##  Get input image
    ##  You assume the image to be square
    image_name = pathin + args.image
    image = io.readImage(image_name)
    npix = image.shape[0]

    if image.shape[1] != image.shape[0]:
        sys.exit('\nERROR: input image is not square!\n')

    print('\nInput image:\n', image_name)
    print('Number of pixels: ', npix)

    ##  Show image
    if args.plot is True:
        dis.plot(image, 'Image')

    ##  Get projection geometry
    ##  1) Case of equiangular projections distributed in [0,180)
    if args.geometry == '0':
        nang = args.nang
        angles = np.arange(nang)
        angles = (angles * np.pi) / 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':
        nang = args.nang
        angles = create_pseudo_polar_angles(nang)
        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")
        angles *= np.pi / 180.0
        nang = len(angles)
        print('\nReading list of projection angles: ', geometryfile)

    print('Number of projection angles: ', nang)

    ##  Get interpolation scheme
    interp = args.interp
    if interp == 'nn':
        print('\nSelected interpolation scheme: nearest neighbour')
    elif interp == 'lin':
        print('\nSelected interpolation scheme: linear interpolation')
    else:
        print('''\nWARNING: ', interp,' does not correspond to any available
                  interpolation scheme; nearest neighbour interpolation will
                  be adopted''')
        interp = 'nn'

    ##  Compute radon transform
    sinogram = radon_transform(np.rot90(image), angles, interp)

    ##  Show sinogram
    if args.plot is True:
        dis.plot(sinogram, 'Sinogram')

    ##  Save sinogram
    save_sinogram(sinogram, angles, args)

    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('Time elapsed: ', (endTime - startTime) / 60.0)
    print('\n')
Exemplo n.º 19
0
def main():
    print('\n')
    print('###############################################')
    print('###############################################')
    print('####                                       ####')
    print('####  RUN ANALYSIS OF THE RECONSTRUCTIONS  ####')
    print('####                                       ####')      
    print('###############################################')
    print('###############################################')  
    print('\n') 


    
    ##  Get input arguments
    args = getArgs()


    
    ##  Get input path
    pathin = args.pathin
    
    if pathin.find(':') == -1:
        sys.exit('\nERROR: path to input reconstructions with odd indeces' +
                 ' must be separated with a ":" from the reconstructions with' +
                 ' even indeces')
    
    else:
        pathin = pathin.split(':')
        if pathin[0][len(pathin[0])-1] != '/':
            pathin[0] += '/'
        if pathin[1][len(pathin[1])-1] != '/':
            pathin[1] += '/' 
    
    print('\nInput paths:\n', pathin[0],'\n', pathin[1])


        
    ##  Get reconstruction files
    label = args.label

    curr_dir = os.getcwd()
    os.chdir( pathin[0] )

    rec_list1 = sorted( glob.glob( '*' + label + '*' ) )
    num_files1 = len( rec_list1 )

    os.chdir( curr_dir )
    os.chdir( pathin[1] )

    rec_list2 = sorted( glob.glob( '*' + label + '*' ) )
    num_files2 = len( rec_list2 )

    os.chdir( curr_dir ) 


    if num_files1 != num_files2:
        sys.exit('\nERROR: number of files in path1 = ' + str( num_files1 ) 
                  + ' differ from number of files in path2 = ' + str( num_files2 ) )
    else:
        num_files = num_files1
        print('\nNumber of input files in both paths: ', num_files)



    ##  Organize input files
    plot_axes = args.plot_axes
    axes = []
    file_label = []
    
    
    if plot_axes.find(',') == -1:
        flag_plot3d = 0
        
        plot_axes_aux = plot_axes_aux.split(':')
        file_label.append( plot_axes_aux[0] )

        for j in range( 1 , len( plot_axes_aux ) ):
            axes.append( plot_axes_aux[j] )         
        
        print('\nPlot 2D selected using file label: ', file_label)
        print('Axis x values: ', axes )

    else:
        plot_axes = plot_axes.split(',')
        flag_plt3d = 1

        for i in range( len( plot_axes ) ):
            plot_axes_aux = plot_axes[i]
            plot_axes_aux = plot_axes_aux.split(':')
            file_label.append( plot_axes_aux[0] )

            axes_values = []
            for j in range( 1 , len( plot_axes_aux ) ):
                axes_values.append( plot_axes_aux[j] )
            axes.append( axes_values )
        
        print('\nPlot 3D selected using file labels: ', file_label)
        print('Axis x values: ', axes[0])
        print('Axis y values: ', axes[1])

    xlen = len( axes[0] )
    ylen = len( axes[1] )
    x = np.array( axes[0] ).astype( myFloat )
    y = np.array( axes[1] ).astype( myFloat ) 
    result = np.zeros( ( xlen , ylen ) , dtype=myFloat )

    axes_label = args.axes_label
    if axes_label.find(':') == -1:
        flag_plot3d = 0
        print('\nPlot 2D selected using file label: ', axes_label)
    else:
        flag_plot3d = 1
        axes_label = axes_label.split(':')
        print('\nPlot 3D selected using file labels: ', axes_label)



    ##  Perform analisys
    if args.resol_square is True:
        print('Enabled analisys inside resolution square')

    print('\n\n')

    
    f = 0

    for i in range( xlen ):
        for j in range( ylen ):

            filein = rec_list1[f]
            image1 = io.readImage( pathin[0] + filein )
            print('\n\nInput image 1:\n', filein)

            filein = rec_list2[f]
            image2 = io.readImage( pathin[1] + filein )
            print('\nInput image 2:\n', filein)

            print('\n')


            ##  Preprocess input image and oracle
            if args.resol_square is True:
                image1 = an.select_resolution_square( image1 )
                image2 = an.select_resolution_square( image2 ) 


            ##  Perform analysis
            frc , resol  = an.fourier_ring_corr( image1 , image2 ) 
            result[i,j] = resol
            #x = np.arange( len( frc ) )
            #plt.plot( x , frc )
            #plt.show()

            f += 1



    ##  Write data for bar plot 3D to text file
    if  result.shape[0] * result.shape[1] != len( x ) * len( y ):
        sys.exit('\nERROR: number of results = ' + str( len( result ) ) +
                 ' does not match the product between number of x values = '
                 + str( len( x ) ) + ' and the number of the y values = '
                 + str( len( y ) ) + '\n')


    fileout = args.fileout
    
    if os.path.isfile( fileout ) is True:
        sys.exit('\nERROR: output file:\n' + fileout + '\nalready exists!')

    print('\nWriting data for bar plot 3D to file:\n', fileout)
    fout = open( args.fileout , 'w' )

    fout.write('x:' + axes_label[0].upper() + ':' + str( len( x ) ) )
    for i in range( len( x ) ):
        fout.write('\n%4f' % x[i])

    fout.write('\ny:' + axes_label[1].upper() + ':' + str( len( y ) ) )
    for i in range( len( y ) ):
        fout.write('\n%4f' % y[i])

    fout.write('\nz:FRC:' + str( len( result.flatten() ) ) )
    for j in range( result.shape[1] ):
        for i in range( result.shape[0] ): 
            fout.write('\n%4f' % result[i,j])

    fout.close()


    #print( x )
    #print( y )
    #print( result )


    from mpl_toolkits.mplot3d import Axes3D

    fig = plt.figure()
    ax = Axes3D(fig)    

    lx= len(result[0])            # Work out matrix dimensions
    ly= len(result[:,0])
    xpos = np.arange(0,lx,1)    # Set up a mesh of positions
    ypos = np.arange(0,ly,1)
    xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)

    xpos = xpos.flatten()   # Convert positions to 1D array
    ypos = ypos.flatten()
    zpos = np.zeros(lx*ly)

    dx = 0.5 * np.ones_like(zpos)
    dy = dx.copy()
    dz = result.flatten()
    ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color='b', alpha=0.8)    
    column_names = axes[1]
    row_names = axes[0]
    ax.w_xaxis.set_ticklabels(column_names)
    ax.w_yaxis.set_ticklabels(row_names)
    ax.set_xlabel( axes_label[1].upper() )
    ax.set_ylabel( axes_label[0].upper() )
    ax.set_zlabel( 'FRC' )     
    plt.show()

    
    print('\n')
Exemplo n.º 20
0
def main():
    ##  Initial print
    print('\n')
    print('############################################################')
    print('#############   FORWARD HIERACHICAL PROJECTOR  #############')
    print('############################################################')
    print('\n')


    
    ##  Get the startimg time of the reconstruction
    time1 = time.time()



    ##  Get input arguments
    args = getArgs()



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

    if os.path.exists( pathin ) is False:
        sys.exit('\nERROR: input directory ', pathin,' does not exist!')

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



    ##  Get input image and number of views
    imgfile = args.image
    image = io.readImage( pathin + imgfile )
    npix = image.shape[0]

    print('\nSinogram to reconstruct:\n', imgfile)
    print('Number of pixels: ', npix)


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



    ##  Get projection angle range
    if args.geometry == '0' or args.geometry == '1':
        if args.angle_range.find( ':' ) == -1:
            angle_start = myfloat( args.angle_range )
            angle_end = angle_start + 180.0

        else:
            angle_aux = args.angle_range.find( ':' )
            angle_start = myfloat( angle_aux[0] )
            angle_end = myfloat( angle_aux[1] )

        print( '\nSelected angle range: [ ', angle_start,' , ', angle_end,' ]' )



    ##  Get projection geometry  
    print( 'args.geometry = ', args.geometry)
    if args.geometry == '0':
        nang = args.nang  
        print('\nDealing with equiangular projections distributed between 0 and'
                +' 180 degrees ---> [0,180)')
        angles = create_equally_spaced_angles( nang , angle_start , angle_end )

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

    else:
        geometryfile = pathin + args.geometry
        print('\nReading list of projection angles: ', geometryfile)
        angles = np.fromfile( geometryfile , sep="\t" )

    nang = len( angles )

    print('Number of projection angles: ', nang)   

    if args.plot is True:
        print('\nProjection angles:\n', angles)

    

    ##  Pad image to reach number of required sinogram pixels
    if args.npix_s is not None:
        npix_s = args.npix_s
    else:
        npix_s = npix

    if args.base_size == 0:
        base_size = npix 
    else:
        base_size = args.base_size

    if args.down_size == 0:
        down_size = npix 
    else:
        down_size = args.down_size  



    ##  Set parameters
    print( '\nFHBP parameter setting:' )
    print( 'Number sinogram pixels: ' , npix_s )
    print( 'Base size: ' , base_size )
    print( 'Downsampling size: ' , down_size )
    print( 'Ratio sinogram / image sampling: ' , args.sampl_ratio )

    param = np.array( [ npix_s , base_size , down_size , 
                        args.sampl_ratio ] ) 


    
    ##  Apply forward projection operator
    time_rec1 = time.time()
    sino = fhbp.forwproj( image.astype( myfloat ) , angles.astype( myfloat ) ,
                          param.astype( myfloat ) )

    time_rec2 = time.time()

    

    ##  Crop sinogram
    if args.crop is True and npix_s > npix:
        print( 'Sinogram cropping enabled')
        i1 = int( 0.5 * ( npix_s - npix ) )
        i2 = i1 + npix
        sino = sino[::-1,i1:i2]



    ##  Display sinogram     
    if args.plot is True:
        dis.plot( sino , 'Sinogram' )



    ##  Save sinogram
    write_sinogram( sino , pathin , angles , args )

    
    
    ##  Time elapsed to run the code
    time2 = time.time()
    print('\nTime elapsed to run the forward gridrec: ', time_rec2-time_rec1)
    print('Total time elapsed for the run of the program: ', time2-time1)


    print('\n')
    print('#######################################')
    print('####    FORWARD PROJECTION DONE !  ####')
    print('#######################################')
    print('\n')
Exemplo n.º 21
0
def main():
    ##  Initial print
    print('\n')
    print('##############################################')
    print('#############   RADON TRANSFORM  #############')
    print('##############################################')
    print('\n')


    ##  Get the startimg time of the reconstruction
    startTime = time.time()


    ##  Get input arguments
    args = getArgs()


    ##  Get path to input image
    pathin = args.pathin

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


    ##  Get input image
    ##  You assume the image to be square
    image_name = pathin + args.image
    image = io.readImage( image_name )
    npix = image.shape[0]

    if image.shape[1] != image.shape[0]:
        sys.exit('\nERROR: input image is not square!\n')

    print('\nInput image:\n', image_name)
    print('Number of pixels: ', npix)


    ##  Show image
    if args.plot is True:
        dis.plot( image , 'Image' )


    ##  Get projection geometry  
    ##  1) Case of equiangular projections distributed in [0,180)
    if args.geometry == '0':
        nang = args.nang
        angles = np.arange( nang )
        angles = ( angles * np.pi )/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':
        nang = args.nang
        angles = create_pseudo_polar_angles( nang )
        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" )
        angles *= np.pi/180.0
        nang = len( angles )
        print('\nReading list of projection angles: ', geometryfile)

    print('Number of projection angles: ', nang)


    ##  Get interpolation scheme
    interp = args.interp
    if interp == 'nn':
        print('\nSelected interpolation scheme: nearest neighbour')
    elif interp == 'lin':
        print('\nSelected interpolation scheme: linear interpolation')
    else:
        print('''\nWARNING: ', interp,' does not correspond to any available
                  interpolation scheme; nearest neighbour interpolation will
                  be adopted''')
        interp = 'nn'


    ##  Compute radon transform
    sinogram = radon_transform( np.rot90( image ) , angles , interp )

    
    ##  Show sinogram     
    if args.plot is True:
        dis.plot( sinogram , 'Sinogram' )


    ##  Save sinogram
    save_sinogram( sinogram , angles , args )


    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('Time elapsed: ', (endTime-startTime)/60.0)
    print('\n')
Exemplo n.º 22
0
def main():
    
    print('\n')
    print('#############################################')
    print('############  SPECTRUM ANALYSIS  ############')
    print('#############################################')
    print('\n')

    

    ##  Get input arguments
    args = getArgs()


    
    ##  Get number of pair of images
    image_string = args.images
    
    file_list = []
    
    if image_string.find(':') != -1:
        file_list = image_string.split(':')

        num_img = len( file_list )

    else:
        file_list.append( image_string )
        num_img = 1
    
    print('Number of images to analyze: ', num_img)
    print(file_list)


    
    ##  Read input images and display them as check
    images = []

    
    for i in range(num_img):
        image_name = file_list[i]
        print('Reading image: ', image_name)

        if args.resol_square :
            print('Calculation enabled in the resol square')
            images.append( proc.selectResolutionSquare( io.readImage( image_name ) ) )
        else:
            print('Calculation enabled on the whole image square')
            images.append( io.readImage( image_name ) )

        ##  Check plot
        if args.plot is True:
            dis.plot( images[i] , 'Input image ' + str( i ) ) 
    
    '''
    images.append( np.arange( 64 ).reshape( 8 , 8 ) )
    images.append( np.arange( 64 ).reshape( 8 , 8 ) )

    print( '\n\nInput images:\n', images[0] )
    '''
    
    ##  Get labels for plots
    labels = None
    if args.labels is not(None):
        labels = args.labels
        labels = labels.split(':')

        if ( len(labels) ) != num_img:
            sys.exit('\nERROR: Number of labels is not half number of input images!\n')

    
    
    ##  Fourier ring correlation analysis
    spectrum_curves = []
    label_curves = []
    resol_point_list = []

    for i in range(num_img):
        if args.labels is None:
            label_curves.append('Spectrum image ' + str( i ) )
            label = 'Spectrum analysis image ' + str( i )
        else:
            label_curves.append(labels[i])
            label = 'Spectrum analysis image ' + labels[i] 
        
        print('\nCalculating ring-spectrum of image:\n', file_list[i])
        
        spectrum , spatial_freq = analysis_spectrum( images[i] , args , i ,
                                                     'image '+ str(i) , label )
        spectrum_curves.append( spectrum )
    
    spectrum_curves = np.array( spectrum_curves ).reshape( num_img , len( spatial_freq ) )



    ##  Plot FRC curves
    title = 'Spectrum - comparison'
    plot_name = 'spectrum_comparison_curves'
    point = None
    style = 'lines'
    plot_spectrum_curves( spectrum_curves, spatial_freq, args, label_curves, title,
                          point, style ) 



    ##   Write log file
    if args.fileout is not None:
        fileout = args.fileout
        fout = open(fileout,'w')

        print('Writing data in ',fileout,' ....')

        today = datetime.datetime.now()
        fout.write('########  SPECTRUM RESOLUTION ANALYSIS  ########\n')
        fout.write('Calculation performed on the ' + str(today))
        fout.write('\nResults of images inside:\n '+str(path))    

        if args.resol_square :
            fout.write('\nCalculation enabled in the resol square')
        else:
            fout.write('\nCalculation enabled on the whole image square')

        fout.write('\nCalculation enabled on the whole image square')   

        for im in range( num_img ):
            fout.write('\n\nSpectrum analysis performed for:\n')  
            fout.write( file_list[i] )
            fout.write( file_list[i] )
            
            if args.pixsize is None:
                fout.write('Resolution = ' + str(resol_point_list[im] )+' (pixels)\n\n')
            
            else:
                fout.write('Resolution = ' + str( resol_point_list[im] )+' micro_meters\n\n') 
        
        fout.write('\n##########  SPECTRUM ANALYSIS END  ##########\n')        
        fout.close()


    print('\n##########  SPECTRUM ANALYSIS END  ##########\n')
Exemplo n.º 23
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')
Exemplo n.º 24
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()
Exemplo n.º 25
0
def main():
    ##  Initial print
    print('\n')
    print('#####################################')
    print('#####################################')
    print('####                             ####')
    print('####   RADON TRANSFORM BASED ON  ####')
    print('####    A CUBIC B-SPLINE BASIS   ####')
    print('####                             ####')
    print('#####################################')
    print('#####################################')
    print('\n')

    ##  Get the startimg time of the sinonstruction
    time1 = time.time()

    ##  Get input arguments
    args = getArgs()

    ##  Get path to input sino
    pathin = args.pathin

    ##  Get input image
    ##  You assume the image to be square
    image_name = pathin + args.image
    image = io.readImage(image_name).astype(myfloat)
    npix = image.shape[1]
    nang = args.nang

    print('\nInput image:\n', image_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)

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

    ##  Get projection geometry
    angles = np.arange(nang)
    angles = (angles * np.pi) / myfloat(nang)
    print('\nDealing with equally angularly spaced projections in [0,180)')

    ##  Create projector class
    if args.dpc is False:
        rd = 0
    else:
        rd = 1

    deg = args.bspline_degree
    sup = deg + 1

    print('\nSelected B-spline degree: ', deg)
    print('Selected Radon degree: ', rd)

    tp = cpb.projectors(npix,
                        angles,
                        bspline_degree=deg,
                        proj_support_y=sup,
                        nsamples_y=2048,
                        radon_degree=rd,
                        filt='ramp',
                        back=False,
                        plot=True)

    image[:] = image[::-1, ::-1]
    sino = tp.A(image)

    ##  Show sino
    if args.plot is True:
        dis.plot(sino, 'Sinogram')

    ##  Save sino
    save_sino(sino, angles, args)

    ##  Time elapsed for the computation of the radon transform
    time2 = time.time()
    print('\n\nTime elapsed to run the radon: ', (time2 - time1) / 60.0,
          ' min.')
    print('Time elapsed to run the radon: ', time2 - time1, ' sec.')
    print('\n')
Exemplo n.º 26
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')
Exemplo n.º 27
0
def calcResol(path,nameImage,startPoint,endPoint,args,indexIm):
    # get number of lines around the reference line to use for computing
    # the fourier spectrum; this number shoud be even to have the same
    # number of lines before and after the reference line
    nLines = args.nLines
    if nLines % 2 != 2:
        nLines += 1
    
    # open image
    imarray = myImageIO.readImage(path+nameImage)
    imarray = imarray.astype(myFloat)

    # check image before starting the analysis of the Fourier spectrum
    checkPlot_images(nameImage,imarray,[startPoint,endPoint],args) 

    # get image dimensions
    width,height = imarray.shape

    # check if the line points define a line inside the image and if
    # the line is horizontal or vertical and which point comes before
    # and which after
    flag,first,last = checkLinePoints(startPoint,endPoint,width,height)

    # initialize array aimed at storing the line profile 
    lineLength = ((startPoint[0]-endPoint[0])**2+(startPoint[1]-endPoint[1])**2)**0.5
    numFreq = int(np.ceil(lineLength))
    lineProfile = np.zeros(numFreq,dtype=myComplex)
    fourierSpectrum = np.zeros(numFreq,dtype=myComplex)  

    # compute the fourier spectrum of the reference line and of the
    # other nLines lines around it and then compute the mean fourier
    # spectrum
    for n in range(nLines):
        # case of vertical lines
        if flag == 'v':
            line = int(startPoint[0]+n-nLines/2.0)
            if line >= 0 and line < height:
                lineProfile[:] = imarray[line,first:last]
                lineProfile[:] = np.abs(np.fft.fft(lineProfile))
                fourierSpectrum += lineProfile*lineProfile/float(nLines)
            else:
                print("Warning: discarded line number ",n," , because it is out of the image")
        # case of horizontal lines
        elif flag == 'h':
            line = startPoint[1]+n
            if line >= 0 and line < height:
                lineProfile[:] = imarray[line,first:last]
                lineProfile[:] = np.abs(np.fft.fft(lineProfile))
                fourierSpectrum += lineProfile*lineProfile/float(nLines)
            else:
                print("Warning: discarded line number ",n," , because it is out of the image")

    # center the component at frequency null
    fourierSpectrum[:] = np.fft.fftshift(fourierSpectrum)

    # convert the spectrum values to log10 scale and add min value
    # of the converted spectrum to go on working with positive values
    fourierSpectrumTmp = np.empty(numFreq,dtype=myFloat)
    for freq in range(numFreq):
        fourierSpectrumTmp[freq] = math.log(np.real(fourierSpectrum[freq]),10)
    fourierSpectrum = fourierSpectrumTmp + np.abs(np.min(fourierSpectrumTmp))

    # get horizontal stripe along the fourier spectrum, representing
    # the contribution of the noise to the signal; "thres" establishes
    # the width of this stripe
    thres = args.thres
    baseLineMean = 6*np.sum(fourierSpectrum[int(5*numFreq/6.0):])/myFloat(numFreq)
    baseLineSigma = np.sqrt(6.0/myFloat(numFreq)*np.sum((fourierSpectrum[int(5*numFreq/6.0):]-\
                    baseLineMean)*(fourierSpectrum[int(5*numFreq/6.0):]-baseLineMean)))
    thresMin = baseLineMean - baseLineSigma 
    thresMax = baseLineMean + baseLineSigma

    # get noise spectrum height 
    indexAux1 = np.asarray(np.where(fourierSpectrum>=thresMin)).reshape(-1)
    indexAux2 = np.asarray(np.where(fourierSpectrum<=thresMax)).reshape(-1)
    indexArr = np.sort(list(set(indexAux1) & set(indexAux2)))
    baseLine = np.sum(fourierSpectrum[indexArr])
    baseLine /= float(len(indexArr))
    noiseHeight = min(thresMax-baseLine,baseLine-thresMin)+baseLine

    # subtract noise spectrum to the line profile spectrum
    fourierSpectrumNew = fourierSpectrum-noiseHeight

    # find indeces where the signal spectrum is positive and choose the
    # the first occurence above the abscissa of the half spectrum
    indexResol = None
    aboveThres = args.aboveThres 
    boolArr = fourierSpectrumNew>=0
    frequencies = np.fft.fftshift(np.fft.fftfreq(numFreq))
    index = None
    for freq in range(int(numFreq/2.0),numFreq):
        if boolArr[freq]:
            if index is not(None):
                indexResol = index
                if np.abs(freq-index) > 1:
                    break
            index = freq

    # correct the resolution estimation manually with a list
    # of preciser spatial frequencies corresponding to the 
    # searched intersection point.
    if args.correct is not(None):
        fixSpatialFreq = np.loadtxt(args.correct)
        if fixSpatialFreq[indexIm] != -1:
            minDist = 10000
            for freq in range(numFreq):
                if(minDist > np.abs(fixSpatialFreq[indexIm]-frequencies[freq])):
                    indexResol = freq
                    minDist = np.abs(fixSpatialFreq[indexIm]-frequencies[freq])

    # check fourier spectrum in case indexResol is not found
    if indexResol == None:
        checkPlot_fourierSpectrum(nameImage,fourierSpectrum,numFreq,thresMin,thresMax,baseLine,
                                    noiseHeight,indexResol,indexIm,args)
        raise Exception('Spatial frequency of resolution not found!')

    # resolution in pixels or in units
    if args.pixsize is None:
        resol = numFreq/float(indexResol-1)
        print('Resolution: ', resol,' pixel')
    else:
        resol = numFreq/float(indexResol-1)*args.pixsize
        print('Resolution: ', resol,' micro_meters')  

    # plot to check whether the fourier spectrum, the thresholding lines and the
    # position of the "resolution point" are reasonable
    if args.plot:
        checkPlot_fourierSpectrum(nameImage,fourierSpectrum,numFreq,thresMin,thresMax,baseLine,
                                    noiseHeight,indexResol,indexIm,args)
                
    return resol
Exemplo n.º 28
0
def main():
    print('\n')
    print('#######################################')
    print('#######################################') 
    print('###                                 ###')
    print('###         MEAN SQUARE ERROR       ###')
    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 = 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 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)
                    file_roi = open( roi , 'r' )
                    pixels = np.loadtxt( file_roi )
                    image1 = image1[pixels[:,0],pixels[:,1]]
                    image2 = image2[pixels[:,0],pixels[:,1]]
                    num_pix = len( image1 )
                    fact = factors( num_pix )
                    image1 = image1.reshape( fact[0] , int( num_pix/fact[0] ) )
                    image2 = image2.reshape( fact[0] , int( num_pix/fact[0] ) )   


            ##  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' )    


            ##  Compute figures of merit
            SNR = calc_snr( image1 , image2 )
            PSNR = calc_psnr( image1 , image2 )
            RMSE = calc_rmse( image1 , image2 )
            MAE = calc_rmse( image1 , image2 ) 

            results.append( np.array( [ SNR , PSNR , RMSE , MAE ] ) )



        ##  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) 
                        file_roi = open( roi , 'r' )
                        pixels = np.loadtxt( file_roi )
                        pixels = pixels.astype( int )

                        image1 = image1[pixels[:,0],pixels[:,1]]
                        image2 = image2[pixels[:,0],pixels[:,1]]
                        num_pix = len( image1 )
                        fact = factors( num_pix )
                        image1 = image1.reshape( fact[0] , int( num_pix/fact[0] ) )
                        image2 = image2.reshape( fact[0] , int( num_pix/fact[0] ) )       


                ##  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' )


                ##  Compute figures of merit
                SNR = calc_snr( image1 , image2 )
                PSNR = calc_psnr( image1 , image2 )
                RMSE = calc_rmse( image1 , image2 )
                MAE = calc_rmse( image1 , image2 )

                results.append( np.array( [ SNR , PSNR , RMSE , MAE ] ) )                                  



    ##  CASE OF BUNCH OF IMAGES TO ANALYZE 
    else:
        os.chdir(args.path)
        image_list = sorted(glob.glob('*'))
        num_img = len(fileIn)

        ## 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', image_list[i])
            print('Image shape: ', image2.shape)

            if args.fileout is not None:
                fileout.write('\nReading image to analyze:\n' + fileIn[i])    


            ## 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) 
                    file_roi = open( roi , 'r' )
                    pixels = np.loadtxt( file_roi )
                    pixels = pixels.astype( int )

                    image1 = image1[pixels[:,0],pixels[:,1]]
                    image2 = image2[pixels[:,0],pixels[:,1]]
                    num_pix = len( image1 )
                    fact = factors( num_pix )
                    image1 = image1.reshape( fact[0] , int( num_pix/fact[0] ) )
                    image2 = image2.reshape( fact[0] , int( num_pix/fact[0] ) ) 


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


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


            ##  Plot to check whether the images have the same orientation
            if args.plot is True and args.roi.find(',') != -1:
                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' )       


            ##  Compute figures of merit
            SNR = calc_snr( image1 , image2 )
            PSNR = calc_psnr( image1 , image2 )
            RMSE = calc_rmse( image1 , image2 )
            MAE = calc_rmse( image1 , image2 )

            results.append( np.array( [ SNR , PSNR , RMSE , MAE ] ) )  


        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('SNR = ' , results[i][0])
        print('PSNR = ' , results[i][1])   
        print('MRSE = ' , results[i][2])   
        print('MAE = ' , results[i][3])   



    ##  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') 
Exemplo n.º 29
0
def main():
    ##  Initial print
    print('\n')
    print('#####################################')  
    print('#####################################')
    print('####                             ####') 
    print('####   RADON TRANSFORM BASED ON  ####') 
    print('####    A CUBIC B-SPLINE BASIS   ####')
    print('####                             ####')    
    print('#####################################')
    print('#####################################')      
    print('\n')


    
    ##  Get the startimg time of the sinonstruction
    time1 = time.time()


    
    ##  Get input arguments
    args = getArgs()


    
    ##  Get path to input sino
    pathin = args.pathin


    
    ##  Get input image
    ##  You assume the image to be square
    image_name = pathin + args.image
    image = io.readImage( image_name ).astype( myfloat )
    npix = image.shape[1]
    nang = args.nang

    print('\nInput image:\n', image_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)


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



    ##  Get projection geometry  
    angles = np.arange( nang )
    angles = ( angles * np.pi )/myfloat( nang )
    print('\nDealing with equally angularly spaced projections in [0,180)')


    
    ##  Create projector class
    if args.dpc is False:
        rd = 0
    else:
        rd = 1

    deg = args.bspline_degree
    sup = deg + 1

    print('\nSelected B-spline degree: ', deg)
    print('Selected Radon degree: ', rd )

    tp = cpb.projectors( npix , angles , bspline_degree=deg , proj_support_y=sup ,
                         nsamples_y=2048 , radon_degree=rd , filt='ramp' , 
                         back = False , plot=True  )

    image[:] = image[::-1,::-1]
    sino     = tp.A( image )



    ##  Show sino     
    if args.plot is True:
        dis.plot( sino , 'Sinogram' )    


    
    ##  Save sino
    save_sino( sino , angles , args )

    
    
    ##  Time elapsed for the computation of the radon transform
    time2 = time.time()
    print('\n\nTime elapsed to run the radon: ', (time2-time1)/60.0,' min.')
    print('Time elapsed to run the radon: ', time2-time1,' sec.') 
    print('\n')
Exemplo n.º 30
0
def main():
    ##  Initial print
    print('\n')
    print('##############################################')
    print('#############   RADON TRANSFORM  #############')
    print('##############################################')
    print('\n')

    ##  Get the startimg time of the reconstruction
    startTime = time.time()

    ##  Get input arguments
    args = getArgs()

    ##  Get path to input reco
    pathin = args.pathin

    ##  Get input reco
    ##  You assume the reco to be square
    sino_name = pathin + args.sino
    sino = io.readImage(sino_name)
    npix = sino.shape[1]
    nang = sino.shape[0]

    print('\nInput sino:\n', sino_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)

    ##  Show reco
    if args.plot is True:
        checkPlot(sino, 'Sinogram')

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

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

    print('Number of projection angles: ', nang)

    ##  Get interpolation scheme
    interp = args.interp
    if interp == 'nn':
        print('\nSelected interpolation scheme: nearest neighbour')
    elif interp == 'lin':
        print('\nSelected interpolation scheme: linear interpolation')
    else:
        print('''\nWARNING: ', interp,' does not correspond to any available
                  interpolation scheme; nearest neighbour interpolation will
                  be adopted''')
        interp = 'nn'

    ##  Get center of rotation
    if args.ctr is None:
        ctr = npix * 0.5
    else:
        ctr = args.ctr

    print('\nCenter of rotation placed at pixel: ', ctr)

    ##  Apply edge padding
    if args.edgepad != 0:
        npix_old = npix
        sino = edgepad(sino, args.edgepad)
        sino = sino.astype(myFloat)
        npix = sino.shape[1]
        ctr += int(0.5 * (npix - npix_old))
        print('\nEdge padded sinogram size: ', sino.shape[0], ' X ',
              sino.shape[1])

    ##  Compute radon transform
    reco = np.zeros((npix, npix), dtype=myFloat)
    reco[:, :] = iradonTransform(sino, angles, interp)

    ##  Crop image
    if args.edgepad != 0:
        i1 = int(0.5 * (npix - npix_old))
        i2 = i1 + npix_old
        print('\nnpix = ', npix, '  npix_old = ', npix_old, '  i1 = ', i1,
              '  i2 = ', i2)
        reco = reco[i1:i2, i1:i2]

    ##  Show sino
    if args.plot is True:
        checkPlot(reco, 'Sinogram')

    ##  Save sino
    saveReco(reco, args)

    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('Time elapsed: ', (endTime - startTime) / 60.0)
    print('\n')
Exemplo n.º 31
0
def main():
    ##  Initial print
    print("\n")
    print("##########################################################")
    print("#############   HIERARCHICAL BACKPROJECTION  #############")
    print("##########################################################")
    print("\n")

    ##  Get the startimg time of the reconstruction
    time1 = time.time()

    ##  Get input arguments
    args = getArgs()

    ##  Get input directory
    pathin = args.pathin

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

    if os.path.exists(pathin) is False:
        sys.exit("\nERROR: input directory ", pathin, " does not exist!")

    print("\nInput directory:\n", pathin)

    ##  Get input sinogram
    sinofile = pathin + args.sino
    sino = io.readImage(sinofile)
    nang, npix = sino.shape

    print("\nSinogram to reconstruct:\n", sinofile)
    print("Number of projection angles: ", nang)
    print("Number of pixels: ", npix)

    ##  Display sinogram
    if args.plot is True:
        dis.plot(sino, "Input sinogram")

    ##  Getting projection geometry
    if args.geometry == "0":
        print("\nDealing with equiangular projections distributed between 0 and" + " 180 degrees ---> [0,180)")
        angles = np.arange(nang).astype(myfloat)
        angles[:] = (angles * 180.0) / myfloat(nang)

    else:
        geometryfile = pathin + args.geometry
        print("\nReading list of projection angles: ", geometryfile)
        angles = np.fromfile(geometryfile, sep="\t")

    if args.plot is True:
        print("\nProjection angles:\n", angles)

    ##  Enable edge padding
    if args.edge_pad is True:
        sino = proc.edgePadding(sino, 0.5)
        i1 = int((sino.shape[1] - npix) * 0.5)
        i2 = i1 + npix
        npix = sino.shape[1]

        if args.plot is True:
            dis.plot(sino, "Edge padded sinogram")

    ##  Set center of rotation axis
    if args.ctr == -1:
        ctr = proc.searchCtrRot(sino, None, "a")
    elif args.ctr == 0:
        ctr = 0.5 * npix
    else:
        ctr = args.ctr
    sino[:, :] = proc.sinoRotAxisCorrect(sino, ctr)

    print("Center of rotation axis placed at pixel: ", ctr)
    print("Center of rotation correction done! ")

    if args.edge_pad is True and ctr != 0.0:
        ctr += i1

    ##  External sinogram filtering
    filt = args.filt

    if filt not in filt_list:
        print(
            "\nERROR: filter named: ', filt,' does not exist!\n \
               Use one of the following available filters:\n \
               'none' , 'ramp' , 'shlo' , 'hann' , 'hamm' , \n \
               'parz' , 'lancz' "
        )

    print("\nSelected filter: ", filt)

    if filt == "none":
        filter_name = "none"
    elif filt == "ramp":
        filter_name = "ramp"
    elif filt == "hann":
        filter_name = "hanning"
    elif filt == "hamm":
        filter_name = "hamming"

    sino = fil.filter_fft(sino, filter_name, 0)
    sino *= 4.0 / myfloat(npix)

    if args.plot is True:
        dis.plot(sino, "Filtered sinogram")

    ##  Set number of pixels of the reconstructed image
    if args.npix_im is None:
        npix_im = npix
    else:
        npix_im = args.npix_im

    if args.base_size == 0:
        base_size = npix
    else:
        base_size = args.base_size

    if args.down_size == 0:
        down_size = npix
    else:
        down_size = args.down_size

    ##  Set parameters
    print("\nFHBP parameter setting:")
    print("Number image pixels: ", npix_im)
    print("Base size: ", base_size)
    print("Downsampling size: ", down_size)
    print("Ratio sinogram / image sampling: ", args.sampl_ratio)

    param = np.array([npix_im, base_size, down_size, args.sampl_ratio])

    ##  Reconstruction with regridding method
    time_rec1 = time.time()
    reco = fhbp.backproj(sino.astype(myfloat), angles.astype(myfloat), param.astype(myfloat))
    time_rec2 = time.time()

    ##  Crop reconstruction
    if args.edge_pad:
        reco = reco[i1:i2, i1:i2]

    ##  Rotate and flip reconstruction
    reco[:, :] = reco[:, ::-1]

    ##  Display reconstruction
    if args.plot is True:
        dis.plot(reco, "Reconstruction")

    ##  Save reconstruction
    write_reconstruction(reco, pathin, args)

    ##  Time elapsed and memory usage for the reconstruction
    time2 = time.time()
    print("\nTime elapsed for the back-projection: ", time_rec2 - time_rec1, " s")
    print("Total time elapsed: ", time2 - time1, " s")

    print("\n")
    print("########################################")
    print("####   FHBP BACKPROJECTION DONE !   ####")
    print("########################################")
    print("\n")
Exemplo n.º 32
0
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('#############    SKIMAGE RADON TRANSFORM   #############')
    print('########################################################')
    print('\n')

    ##  Get the startimg time of the sinonstruction
    startTime = time.time()

    ##  Get input arguments
    args = getArgs()

    ##  Get path to input sino
    pathin = args.pathin

    ##  Get input image
    ##  You assume the image to be square
    image_name = pathin + args.image
    image = io.readImage(image_name)
    npix = image.shape[1]
    nang = args.nang

    print('\nInput image:\n', image_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)

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

    ##  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':
        print('\n\nDealing with equally-sloped projections in [0,180)')

        if nang % 4 != 0:
            print('\n\nERROR: in case of equally-sloped projections',
                  ' the number of angles has to be a multiple of 4')

        angles = createPseudoPolarAngles(nang) * 180.0 / np.pi

    ##  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)

    ##  Get interpolation scheme
    interp = args.interp
    if interp == 'nn':
        print('\nSelected interpolation scheme: nearest neighbour')
    elif interp == 'lin':
        print('\nSelected interpolation scheme: linear interpolation')
    else:
        print('''\nWARNING: ', interp,' does not correspond to any available
                  interpolation scheme; nearest neighbour interpolation will
                  be adopted''')
        interp = 'lin'

    ##  Center of rotation axis
    ctr = 0.5 * npix

    ##  Enable zero-padding
    if args.padding is True:
        npix_old = npix
        image = proc.zeroPaddingImg(image, 2)
        npix = image.shape[0]
        dis.plot(image, 'Image zero-padded')

    ##  Compute iradon transform
    print('\nPerforming Skimage Radon Transform ....\n')
    sino = radon(image[:, ::-1], npix, angles, ctr, interp)

    ##  Rotate sinogram
    sino = np.rot90(sino)

    ##  Remove edge_padding
    if args.padding is True:
        i1 = int((npix - npix_old) * 0.5)
        i2 = i1 + npix_old
        sino = sino[:, i1:i2]

    ##  Show sino
    if args.plot is True:
        dis.plot(sino, 'Sinogram')

    ##  Save sino
    saveSino(sino, angles, args)

    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('\n\nTime elapsed: ', (endTime - startTime) / 60.0)
    print('\n')
Exemplo n.º 33
0
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('#############   EQUALLY SLOPED TOMOGRAPHY  #############')
    print('########################################################')
    print('\n')


    ##  Get the startimg time of the reconstruction
    time1 = time.time()



    ##  Get input arguments
    args = getArgs()


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

    if os.path.exists( pathin ) is False:
        sys.exit('\nERROR: input directory ', pathin,' does not exist!')

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



    ##  Get input sinogram
    sinofile = pathin + args.sino
    sino = io.readImage( sinofile )
    nang, npix = sino.shape

    print('\nSinogram to reconstruct:\n', sinofile)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)



    ##  Display sinogram
    if args.plot is True:
        dis.plot( sino , 'Input sinogram' )



    ##  Getting projection geometry  
    ##  Case of equiangular projections distributed in [0,180)
    if args.geometry == '0':
        print('\nDealing with equiangular views distributed in [0,180)')
        angles = np.arange( nang ).astype( myfloat )
        angles[:] = ( angles * 180.0 )/myfloat( nang )

    ##  Case of pseudo polar views
    elif args.geometry == '1':
        print('\nDealing with equally sloped views in [0,180)')
        angles , dump1 , dum2 = create_est_views( nang )
        angles *= 180.0 / np.pi

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

    print('\nProjection angles:\n', angles)



    ##  Set center of rotation axis
    if args.ctr == None:
        ctr = 0.0
        print('\nCenter of rotation axis placed at pixel: ', npix * 0.5)  
    elif args.ctr == -1:
        ctr = proc.searchCtrRot( sino , None , 'a' )
        print('\nCenter of rotation axis placed at pixel: ', ctr)
        sino = proc.sinoRotAxisCorrect( sino , ctr )
    else:
        ctr = args.ctr
        print('\nCenter of rotation axis placed at pixel: ', ctr)
        sino = proc.sinoRotAxisCorrect( sino , ctr ) 



    ##  Get inverse procedure
    if args.reco_proc == 1:
        proc = args.reco_proc
        print('\nSelected inverse procedure: PCG-IPPFT')

    elif args.reco_proc == 2:
        proc = args.reco_proc
        print('\nSelected inverse procedure: iterative procedure with constraints')   



    ##  Reconstruction with EQUALLY SLOPED TOMOGRAPHY
    print('\nPerforming EST reconstruction ....')
    time_rec1 = time.time()
    reco = est_tomo( sino , angles , proc )
    time_rec2 = time.time()
    print('\n.... reconstruction done!')



    ##  Display reconstruction    
    dis.plot( reco , 'Reconstruction' )


    
    ##  Save reconstruction
    saveReco( reco , pathin , args )

    
    
    ##  Time elapsed for the reconstruction
    time2 = time.time()
    print('\nTime elapsed for the back-projection: ', time_rec2-time_rec1 )
    print('Total time elapsed: ', time2-time1 )


    
    print('\n')
    print('##############################################')
    print('####   EQUALLY SLOPED TOMOGRAPHY DONE !   ####')
    print('##############################################')
    print('\n')
Exemplo n.º 34
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')
Exemplo n.º 35
0
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('#############    SKIMAGE RADON TRANSFORM   #############')
    print('########################################################')
    print('\n')


    
    ##  Get the startimg time of the sinonstruction
    startTime = time.time()


    
    ##  Get input arguments
    args = getArgs()


    
    ##  Get path to input sino
    pathin = args.pathin


    
    ##  Get input image
    ##  You assume the image to be square
    image_name = pathin + args.image
    image = io.readImage( image_name )
    npix = image.shape[1]
    nang = args.nang

    print('\nInput image:\n', image_name)
    print('Number of projection angles: ', nang)
    print('Number of pixels: ', npix)


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



    ##  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':
        print('\n\nDealing with equally-sloped projections in [0,180)')
  
        if nang % 4 != 0:
            print('\n\nERROR: in case of equally-sloped projections',
                  ' the number of angles has to be a multiple of 4')

        angles = createPseudoPolarAngles( nang ) * 180.0 / np.pi    

    
    ##  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)



    ##  Get interpolation scheme
    interp = args.interp
    if interp == 'nn':
        print('\nSelected interpolation scheme: nearest neighbour')
    elif interp == 'lin':
        print('\nSelected interpolation scheme: linear interpolation')
    else:
        print('''\nWARNING: ', interp,' does not correspond to any available
                  interpolation scheme; nearest neighbour interpolation will
                  be adopted''')
        interp = 'lin'  



    ##  Center of rotation axis
    ctr = 0.5 * npix



    ##  Enable zero-padding
    if args.padding is True:
        npix_old = npix
        image = proc.zeroPaddingImg( image , 2 )
        npix = image.shape[0]
        dis.plot( image , 'Image zero-padded' )



    ##  Compute iradon transform
    print('\nPerforming Skimage Radon Transform ....\n')
    sino = radon( image[:,::-1] , npix , angles , ctr , interp )



    ##  Rotate sinogram
    sino = np.rot90( sino )

    

    ##  Remove edge_padding
    if args.padding is True:
        i1 = int( ( npix - npix_old ) * 0.5 )
        i2 = i1 + npix_old
        sino = sino[:,i1:i2]



    ##  Show sino     
    if args.plot is True:
        dis.plot( sino , 'Sinogram' )    


    
    ##  Save sino
    saveSino( sino , angles , args )

    
    
    ##  Time elapsed for the computation of the radon transform
    endTime = time.time()
    print('\n\nTime elapsed: ', (endTime-startTime)/60.0)
    print('\n')
Exemplo n.º 36
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')
Exemplo n.º 37
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')
Exemplo n.º 38
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' )
Exemplo n.º 39
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')
Exemplo n.º 40
0
def main():
    print('\n')
    print('###############################################')
    print('###############################################')
    print('####                                       ####')
    print('####  RUN ANALYSIS OF THE RECONSTRUCTIONS  ####')
    print('####                                       ####')      
    print('###############################################')
    print('###############################################')  
    print('\n') 


    
    ##  Get input arguments
    args = getArgs()


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


        
    ##  Get reconstruction files
    if args.imagein is not None:
        imagein = args.imagein
        image_file1 = imagein.split(':')[0]
        image_file2 = imagein.split(':')[1]
        num_pair = 1

    
    elif args.allin:
        curr_dir = os.getcwd()
        os.chdir( pathin )

        image_file1 = sorted( glob.glob( '*odd*' ) )
        image_file2 = sorted( glob.glob( '*even*' ) )

        if len( image_file1 ) != len( image_file2 ):
            sys.exit('\nERROR: number of labelled "odd" = ' + str( len( image_file1 ) )
                     + ' dies not correspond to the number of labelled "even" = ' 
                     + str( len( image_file1 ) ) )
        
        num_pair = len( image_file1 )



    ##  Create output names
    if num_pair == 1:
        fileout = args.fileout

    else:
        aux_out = args.fileout
        aux_out = aux_out.split(':')
        pathout = aux_out[0]
        if pathout[len(pathout)-1] != '/':
            pathout += '/'
        alg = aux_out[1]
        nproj = aux_out[2:]
        base_name = 'data_plot2d_frc_' + alg + '_proj_'
        if len( nproj ) != num_pair:
            sys.exit('\nERROR: number of image pair = ' + str( num_pair ) 
                     + ' does not match with number of labels = ' + 
                     + str( nproj ) )


    ##  Perform analisys
    if args.resol_square is True:
        print('Enabled analisys inside resolution square')

    print('\n\n')



    for i in range( num_pair ):
        ##  Read images
        if num_pair == 1:
            image1 = io.readImage( pathin + image_file1 )
            print('\n\nInput image 1:\n', image_file1 )

            image2 = io.readImage( pathin + image_file2 )
            print('\nInput image 2:\n', image_file2 )

        else:
            image1 = io.readImage( pathin + image_file1[i] )
            print('\n\nInput image 1:\n', image_file1[i] )

            image2 = io.readImage( pathin + image_file2[i] )
            print('\nInput image 2:\n', image_file2[i] )

        print('\n') 


        ##  Preprocess input image and oracle
        if args.resol_square is True:
            image1 = an.select_resolution_square( image1 )
            image2 = an.select_resolution_square( image2 ) 


        ##  Perform analysis
        frc , resol , x  = an.fourier_ring_corr( image1 , image2 )


        ##  Write output file
        if num_pair > 1:
            fileout = pathout + base_name + nproj[i] + '.txt'
    
        if os.path.isfile( fileout ) is True:
            sys.exit('\nERROR: output file:\n' + fileout + '\nalready exists!')

        print('\nWriting data for bar plot 3D to file:\n', fileout)
        fout = open( fileout , 'w' )

        fout.write('x:' +  ':' + str( len( x ) ) )
        for i in range( len( x ) ):
            fout.write('\n%4f' % x[i])

        fout.write('\ny:FRC:' + str( len( frc ) ) )
        for i in range( len( frc ) ): 
            fout.write('\n%4f' % frc[i])

        fout.close()


        #print( x )
        #print( resol )
        #print( frc )



        ##  Plot FRC curve
        if num_pair == 1:
            fig = plt.figure() 
            plt.plot( x , frc ,  'o' , color='b' , markersize=12 )
            plt.xlabel( 'Spatial frequencies' , fontsize=20 , position=(0.5,-0.2) )    
            plt.ylabel( 'FRC' , fontsize=20 , position=(0.5,0.5) )      
            plt.show()

    
    print('\n')