Ejemplo 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 )
Ejemplo n.º 2
0
    def __init__( self , npix , angles , ctr=0.0 , bspline_degree = 3 , proj_support_y=4 ,
                  nsamples_y=2048 , radon_degree=0 , filt='ramp' , back='False', plot=False ):
    
        ##  Compute regridding look-up-table and deapodizer
        self.plot = plot
        nang      = len( angles )
        angles    = np.arange( nang )
        angles    = ( angles * 180.0 )/myfloat( nang )
        if back is False:
            rd = radon_degree
        else:
            rd = 0
        lut = bfun.init_lut_bspline( nsamples_y , angles , 
                                     bspline_degree ,
                                     rd , 
                                     proj_support_y )
        
       
        if plot is True:
            dis.plot( lut , 'Look-up-table' )          



        ##  Assign parameters
        self.lut            = lut.astype( myfloat )
        self.angles         = angles.astype( myfloat )
        self.nang           = nang
        self.bspline_degree = bspline_degree
        self.param_spline   = np.array( [ lut.shape[1] , proj_support_y ] , dtype=myfloat )
        self.filt           = filt
        self.radon_degree   = radon_degree
Ejemplo n.º 3
0
    def fbp( self , x ):
        ##  Option DPC
        if self.radon_degree == 0:
            dpc = False
        else:
            dpc = True

        
        ##  Filtering projection
        x[:] = fil.filter_proj( x , ftype=self.filt , dpc=dpc )
        if self.plot is True:
            dis.plot( x , 'Filtered sinogram' )
    
        
        ##  Backprojection
        reco = gr.backproj( x.astype( myfloat ) , self.angles , self.lut , self.param_spline )


        ##  Normalization
        if dpc is True:
            reco *= np.pi / ( 1.0 * self.nang )
        else:
            reco *= np.pi / ( 2.0 * self.nang )         

        return reco
Ejemplo n.º 4
0
def main():
    print('\n')
    print('#########################################################')
    print('#########################################################')
    print('###                                                   ###')
    print('###             ANALYTICAL RADON TRANSFORM OF         ###')
    print('###             RADIALLY SYMMETRIC FUNCTIONS          ###')
    print('###                                                   ###')
    print('#########################################################')
    print('#########################################################')
    print('\n')

    ##  Get arguments
    args = getArgs()

    ##  Get input parameters
    npix = args.npix
    nang = args.nang
    deg = args.degree
    dpc = args.dpc

    print('\nNumber of pixels: ', npix)
    print('Number of views: ', nang)
    print('Function degree: ', deg)
    print('Option DPC: ', dpc)

    ##  Create LUT for the radially symmetric functions
    lut = create_lut(npix)

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

    ##  Write phantom
    write_output_file(phantom, 'image', args)

    ##  Plot phantom
    if args.plot is True:
        dis.plot(phantom, 'Radially symm. phantom  npix=' + str(npix))

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

        sinogram = radon_transform_analytical(lut, npix, nang, deg, dpc)
        if args.dpc is False:
            sinogram[:, :] = sinogram[:, ::-1]
        sinogram[:, :] = np.roll(sinogram, 1, axis=1)

        ##  Write sinogram
        write_output_file(sinogram, 'sinogram', args)

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

    print('\n\n')
Ejemplo n.º 5
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 )
Ejemplo n.º 6
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)
Ejemplo 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 )
Ejemplo n.º 8
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')
Ejemplo n.º 9
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')
Ejemplo n.º 10
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')
Ejemplo n.º 11
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')
Ejemplo n.º 12
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')
Ejemplo n.º 13
0
def iradon(sino, npix, angles, ctr, filt, interp, dpc, args):
    ##  Get number of angles
    nang = len(angles)

    ##  Pre-calculate sin and cos values
    cos = np.cos(angles)
    sin = np.sin(angles)

    ##  Create grid of coordinates for the reconstruction
    x = np.arange(-(npix * 0.5 - 1), npix * 0.5 + 1)
    x = np.kron(np.ones((npix, 1)), x)
    y = np.rot90(x)

    ##  Filter projections
    if filt is not None:
        sino[:] = fil.filter_proj(sino, ftype=filt, dpc=dpc)

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

    ##  Zero-pad projections to fit with the dimension of the
    ##  reoconstructing grid diagonal
    img_diag = 2 * int(np.ceil(npix / np.sqrt(2))) + 1

    if npix < img_diag:
        pad = 0.5 * (img_diag - npix)
        i1 = int(np.ceil(pad))
        i2 = npix + int(np.floor(pad))
        sino_op = np.zeros((nang, i1 + i2), dtype=myfloat)
        sino_op[:, i1:i1 + npix] = sino[:, :]
        ctr += i1

    else:
        sino_op = np.zeros((nang, npix), dtype=myfloat)
        sino_op[:, :] = sino[:, :]

    ctr = int(ctr)

    ##  Allocate memory for the reconstruction
    reco = np.zeros((npix, npix), dtype=myfloat)

    ##  Enable movie
    if args.movie is True:
        py.ion()
        im = py.imshow(x, animated=True, cmap=cm.Greys_r)

        folder = 'fbp_movie/'

        if not os.path.exists(folder):
            os.makedirs(folder)
        else:
            import shutil
            shutil.rmtree(folder)
            os.makedirs(folder)

    ##  Filtered Backprojection
    if interp == 'spl':
        points = np.arange(i1 + i2) - ctr + 1

    for i in range(nang):
        sys.stdout.write('Backprojecting projection number %d\r' % (i + 1, ))
        sys.stdout.flush()

        t = x * cos[i] + y * sin[i]

        if interp == 'nn':
            t = np.round(t).astype(int)
            reco += sino_op[i, t + ctr - 1]

        elif interp == 'lin':
            a = np.floor(t).astype(int)
            reco += ( t - a ) * sino_op[ i , a + ctr ] + \
                    ( a + 1 - t ) * sino_op[ i , a + ctr - 1 ]

        if args.movie is True:
            py.imshow(reco[::-1, :], animated=True, cmap=cm.Greys_r)
            py.draw()

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

            sci.misc.imsave(folder + 'reco_' + num_proj + '.jpg',
                            reco[::-1, :])

    if dpc is False:
        reco *= np.pi / (2.0 * nang)
    else:
        reco *= np.pi / (1.0 * nang)

    return reco
Ejemplo n.º 14
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')
Ejemplo n.º 15
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')
Ejemplo n.º 16
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')
Ejemplo n.º 17
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')
Ejemplo n.º 18
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")
Ejemplo n.º 19
0
def main():
    print('\n')
    print('#########################################################')
    print('#########################################################')
    print('###                                                   ###')
    print('###     ANALYTICAL RADON TRANSFORM OF SHEPP-LOGAN     ###')
    print('###                                                   ###')
    print('#########################################################')
    print('#########################################################')
    print('\n')

    ##  Get arguments
    args = getArgs()

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

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

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

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

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

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

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

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

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

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

    filename += common + args.file_format

    io.writeImage(filename, phantom)

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

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

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

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

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

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

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

        io.writeImage(filename, sinogram)

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

    print('\n\n')
Ejemplo n.º 20
0
def main():
    print('\n')
    print('#########################################################')
    print('#########################################################')
    print('###                                                   ###')
    print('###             ANALYTICAL RADON TRANSFORM OF         ###')
    print('###             RADIALLY SYMMETRIC FUNCTIONS          ###')  
    print('###                                                   ###')     
    print('#########################################################')
    print('#########################################################') 
    print('\n')


    ##  Get arguments
    args = getArgs()


    ##  Get input parameters
    npix = args.npix
    nang = args.nang
    deg  = args.degree
    dpc  = args.dpc
    
    print('\nNumber of pixels: ', npix)
    print('Number of views: ', nang)
    print('Function degree: ', deg)
    print('Option DPC: ', dpc)


    ##  Create LUT for the radially symmetric functions
    lut = create_lut( npix )


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

    
    ##  Write phantom
    write_output_file( phantom , 'image' , args )


    ##  Plot phantom
    if args.plot is True:
        dis.plot( phantom , 'Radially symm. phantom  npix=' + str( npix ) )

    

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

        sinogram = radon_transform_analytical( lut , npix , nang , deg , dpc )
        if args.dpc is False:
            sinogram[:,:] = sinogram[:,::-1]
        sinogram[:,:] = np.roll( sinogram , 1 , axis=1 )


        ##  Write sinogram
        write_output_file( sinogram , 'sinogram' , args )


        ##  Plot Shepp-Logan phantom
        if args.plot is True:
            dis.plot( sinogram , 'Sinogram  ' + str( nang ) + ' nang X ' + str( npix ) + ' npix' )
    
    print('\n\n')
Ejemplo n.º 21
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')
Ejemplo n.º 22
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')
Ejemplo n.º 23
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')
Ejemplo n.º 24
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')
Ejemplo n.º 25
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')
Ejemplo n.º 26
0
def main():
    print('\n')
    print('#########################################################')
    print('#########################################################')
    print('###                                                   ###')
    print('###     ANALYTICAL RADON TRANSFORM OF SHEPP-LOGAN     ###')        
    print('###                                                   ###')     
    print('#########################################################')
    print('#########################################################') 
    print('\n')


    
    ##  Get arguments
    args = getArgs()


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

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

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

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


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

    

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

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

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

    filename += common + args.file_format

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


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

    

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


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


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

        if nang < 10:
            filename += '000' + str( nang ) + '_rt_anal_sino' + '.DMP'
        elif nang < 100:
            filename += '00' + str( nang ) + '_rt_anal_sino' + '.DMP'
        elif nang < 1000:
            filename += '0' + str( nang ) + '_rt_anal_sino' + '.DMP'
        else:
            filename += str( nang ) + '_rt_anal_sino' + args.file_format  
        
        io.writeImage( filename , sinogram )
   
        print('\nWriting sinogram in:\n', filename)      
    
    
    print('\n\n')
Ejemplo n.º 27
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')
Ejemplo n.º 28
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' )
Ejemplo n.º 29
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')
Ejemplo 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 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')