예제 #1
0
파일: my_fft.py 프로젝트: arcaduf/analysis
def function2( files_real , files_imag , nz , ny , i ):
    im = complex( 0 , 1 )
    array2D = np.zeros( ( nz , ny ) , dtype=np.complex64 )

    for j in range( nz ):
        aux_real = io.readImage( files_real[j] )[i,:]
        aux_imag = io.readImage( files_imag[j] )[i,:]

        array2D[j,:] = aux_real + im * aux_imag
    
    return np.fft.fft( array2D , axis=0 )
예제 #2
0
def test2(abbr):
    ##  Read Shepp-Logan image in folder "../data/"
    image = io.readImage('../data/shepp_logan_pix0256.DMP')
    n = image.shape[0]

    ##  Create array of 200 angularly equispaced angles in [0,180) (degrees)
    nang = 200
    a = np.arange(nang) * 180.0 / nang

    ##  Compute forward projection
    if abbr != 'bsp':
        tp = cpr.projectors(n, a, oper=abbr, filt='ramp')
    else:
        a *= np.pi / 180.0
        tp = cpb.projectors(n,
                            a,
                            bspline_degree=3,
                            proj_support_y=4,
                            nsamples_y=2048,
                            radon_degree=0,
                            filt='ramp',
                            back=False)
    sino = tp.A(image)

    return sino
def reconstr_nnfbp( target_path , output_path , filein , angles , ctr , 
                    weights , offsets , minIn , maxIn , NHidden , filters ):  
    ##  Read low-quality sinogram
    sino = io.readImage( target_path + filein ).astype( myfloat )
    nang , npix = sino.shape
    
        
    ##  Allocate array for reconstruction
    reco = np.zeros( ( npix , npix ) , dtype=myfloat ) 
        
    
    ##  Do the required multiple reconstructions
    for i in xrange( NHidden ):
        filt = filters[i,0:filters.shape[1]]
        hidRec = utils.fbp( sino , angles , [ctr,0.0] , filt )
        reco += weights[i] * sigmoid( hidRec - offsets[i] )
        
        
    ##  Apply last sigmoid
    reco = sigmoid( reco - weights[-1] )

        
    ##  Adjust image range
    reco = 2 * ( reco - 0.25 ) * ( maxIn - minIn ) + minIn


    ##  Save reconstruction
    ext     = filein[len(filein)-4:]
    fileout = output_path + filein[:len(filein)-4] + '_nnreco' + ext
    io.writeImage( fileout , reco )
    print( '\nSaving NN-FBP reconstruction in:\n' , fileout )
    
    return
def main():
    print('\nADD 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
    filein = args.filein
    imagein = io.readImage(pathin + filein)
    nrows, ncols = imagein.shape

    print('\nReading image:\n', filein, '\n')
    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_blur = np.zeros((nrows, ncols), dtype=myfloat)

    ##  Get blurring radii
    if args.sigma_range is None:
        sigma_list = args.sigma_list
        sigma_arr = np.array(sigma_list.split(':'), dtype=myfloat)
        nimg = len(sigma_arr)
    else:
        sigma_list = args.sigma_range
        sigma_list = np.array(sigma_list.split('-'), dtype=myfloat)
        sigma_arr = np.linspace(sigma_list[0], sigma_list[1], sigma_list[2])
        nimg = len(sigma_arr)

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

        ##  Check noisy image
        if args.plot is True:
            dis.plot(image_blur,
                     'Blurred image -- sigma: ' + str(sigma_arr[im]))

        ##  Write noisy image to file
        write_output_file(pathout, filein, image_blur, sigma_arr[im])
def main():
    sino = io.readImage( sys.argv[1] )
    ctr = np.float32( sys.argv[2] )

    sino_new = proc.sino_correct_rot_axis( sino , ctr )

    filename = sys.argv[1][:len(sys.argv[1])-4] + '_interp.DMP'
    io.writeImage( filename , sino_new )
def multi_thread(pathin, pathout, filein, args, ii):
    sino = io.readImage(pathin + filein).astype(myfloat)
    nang, npix = sino.shape
    angles = utils.create_projection_angles(nang)
    tp = cpj.projectors(npix, angles, args=args)
    reco = tp.fbp(sino)
    if args.edge_pad:
        i1 = ii[0]
        i2 = ii[2]
        reco = reco[i1:i2, i1:i2]
    save_reconstruction(pathout, filein, args, reco)
def test2():
    ##  Read Shepp-Logan image in folder "../data/"
    image = io.readImage("../data/shepp_logan_pix0256.DMP")
    n = image.shape[0]

    ##  Create array of 200 angularly equispaced angles in [0,180) (degrees)
    nang = 402
    a = np.arange(nang) * 180.0 / nang

    ##  Compute forward projection
    tp = cpj.projectors(n, a, ctr=0.0)
    sino = tp.A(image)

    return sino
def main():
    print('\n')
    print('##############################################')
    print('##############################################')
    print('####                                      ####')
    print('####         DOWNSAMPLE SINOGRAM          ####')
    print('####                                      ####')
    print('##############################################')
    print('##############################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

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

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

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

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

    ##  Downsample sinogram
    angles_down = None

    if args.nproj is not None:
        sino_down, angles_down = downsample_sinogram_angles(sino, angles, args)

    elif args.factor is not None:
        sino_down = downsample_sinogram_pixels(sino, args)

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

    ##  Write image & angle list
    write_output_files(sino_down, angles_down, args, pathin, filename)

    print('\n')
def create_training_file( input_path , train_path , filein , angles , npix_train_slice , 
                          idx , nang_lq , ctr_hq , nfilt , filt_custom , filt , debug ):
    ##  Read high-quality sinogram
    sino_hq = io.readImage( input_path + filein ).astype( myfloat )
    
    ##  Reconstruct high-quality sinogram with standard filter
    params = utils.select_filter( ctr_hq , filt )
    reco_hq = utils.fbp( sino_hq , angles , params , None )

    ##  Debugging save high- and low-quality reconstructions
    if debug is True:
        filedbg = filein
        ext     = filedbg[len(filedbg)-4:]
        filedbg += '_hq' + ext
        io.writeImage( train_path + filedbg , reco_hq )
        
    ##  Create output training array
    train_data = np.zeros( ( npix_train_slice , nfilt+1 ) , dtype=myfloat ) 
        
    ##  Randomly select training pixels
    picked = utils.getPickedIndices( idx , npix_train_slice )
    
    ##  Save validation data
    train_data[:,-1] = reco_hq[picked]
        
    ##  Downsample sinogram
    sino_lq , angles_lq = utils.downsample_sinogram_angles( sino_hq , angles , nang_lq )
    
    ##  Reconstruct low-quality sinograms with customized filters
    for j in range( nfilt ):
        train_data[:,j] = reconstr_filter_custom( sino_lq , angles_lq , ctr_hq , filt_custom[j,:] , 
                                                  picked , debug , train_path , filein , j )

    ##  Save training data
    filename = filein
    fileout  = train_path + filename[:len(filename)-4] + '_train.npy'
    np.save( fileout , train_data )
    print( '\nTraining data saved in:\n', fileout )
예제 #10
0
def main():

    print('')
    print('######################################') 
    print('######################################')
    print('####                              ####')
    print('####  CALCULATE IMAGE COMPLEXITY  ####')
    print('####                              ####')   
    print('######################################')
    print('######################################') 


    ##  Get input arguments
    args = getArgs()


    ##  Read input image
    filein  = args.pathin + args.filein 
    image   = io.readImage( filein )
    nx , ny = image.shape
    
    print('\nReading input image:\n', filein)     
    print('Image size: ', nx, '  X  ', ny)
    
    if args.jpeg_compr <= 0 and args.jpeg_compr >= 100:
        args.jpeg_compr = 75    

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


    ##  Calculate image complexity index based on JPEG compression
    complexity_jpeg( image , args )


    ##  Calculate image complexity index based on spatial information (SI)
    complexity_struct_info( image )
예제 #11
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 = pyest.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 = pyest.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')
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('#############   REGRIDDING BACKPROJECTION  #############')
    print('########################################################')
    print('\n')

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

    ##  Get input arguments
    args = getArgs()

    ##  Get input/output directory
    pathin, pathout = utils.get_io_path(args)

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

    ##  Get input files
    file_list, file1, nimg, ext = utils.get_input(args, pathin)

    print('\nNumber of input files: ', nimg)
    print('Extension of the files: ', ext)

    ##  Read first sinogram
    sino = io.readImage(pathin + file1).astype(myfloat)
    nang, npix = sino.shape

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

    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 = utils.create_projection_angles(nang)

    else:
        print('\nReading list of projection angles:\n', pathin + args.geometry)
        angles = utils.create_projection_angles(textfile=pathin +
                                                args.geometry)

    ##  Set center of rotation axis
    if args.ctr == None:
        ctr = 0.0
        print('Center of rotation axis placed at pixel: ', npix * 0.5)
    else:
        if args.ctr == -1:
            ctr = proc.search_rot_ctr(sino, None, 'a')
            print('Center of rotation axis placed at pixel: ', ctr)
        else:
            ctr = args.ctr
            print('Center of rotation axis placed at pixel: ', ctr)
            if args.dbp is True:
                sino[:, :] = proc.sino_correct_rot_axis(sino, ctr)
                print('Center of rotation corrected')
                ctr = 0.0

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

        if ctr != 0.0:
            ctr += i1

        if args.plot is True:
            dis.plot(sino, 'Edge padded sinogram')
    else:
        i1 = 0
        i2 = npix

    ##  External sinogram filtering
    if args.filt == 'ramp-ext' or args.filt == 'conv-ext':
        if filt == 'ramp-ext':
            sino = fil.filter_fft(sino, 'ramp')

        elif filt == 'conv-ext':
            sino = fil.filter_convolve(sino)

        sino *= 4.0 / myfloat(npix)
        args.filt = 0

    ##  Differential sinogram fo DBP
    if args.dbp is True:
        print('\nDifferential backprojection enabled')
        print(
            'Computing differential sinogram by means of Savitzky-Golay method'
        )
        print('Savizky-Golay window length: ', args.sg)
        sino[:, :] = proc.diff_sino_savitzky_golay(sino, window_size=args.sg)

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

    ##  Initialize projectior class
    tp = cpj.projectors(npix, angles, ctr=ctr, args=args)

    ##  Apply forward projection operator
    time_rec1 = time.time()
    reco = tp.fbp(sino)
    time_rec2 = time.time()

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

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

    ##  Save reconstruction
    save_reconstruction(pathout, file1, args, reco)

    ##  Reconstruct sinograms from all the other images in the stack
    if args.filein is None:
        pool = mproc.Pool()
        for i in range(1, nimg):
            pool.apply_async(
                multi_thread,
                (pathin, pathout, file_list[0][i], args, [i1, i2]))
        pool.close()
        pool.join()
    time2 = time.time()

    print('\nTime elapsed to run the 1st backward gridrec: ',
          time_rec2 - time_rec1)
    print('Total time elapsed for the run of the program: ', time2 - time1)

    print('\n')
    print('##############################################')
    print('####   REGRIDDING BACKPROJECTION DONE !   ####')
    print('##############################################')
    print('\n')
예제 #13
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')

            ##  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.linearRegression(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.selectResolutionSquare(image1)
                    image2 = proc.selectResolutionSquare(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.linearRegression(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.selectResolutionSquare(image1)
                image2 = proc.selectResolutionSquare(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('\n\nTest image number ', i, '\n', image_list[i], '\n')
        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')
def main():
    ##  Initial print
    print('\n')
    print('##########################################################')
    print('##########################################################')
    print('#####                                                #####')
    print('#####          ADMM Iterative Reconstruction         #####')
    print('#####                                                #####')
    print('##########################################################')
    print('##########################################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

    ##  Get input and output paths
    pathin, pathout = utils.get_io_path(args)

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

    ##  Get input sinogram
    sino_list = []
    filein = []

    if args.filein is not None:
        sinoname = pathin + args.filein
        sino = io.readImage(sinoname).astype(myfloat)
        if args.angle_pi is True:
            sino = sino[:sino.shape[0] - 1, :]
        nang, npix = sino.shape
        nz = 1
        sino_list.append(sino)
        filein.append(args.filein)
        print('\nSinogram to reconstruct:\n', sinoname)

    else:
        print('\nReading stack of images\n')
        curr_dir = os.getcwd()
        os.chdir(pathin)

        for f in os.listdir('./'):
            if f.endswith('.DMP') is True:
                ext = '.DMP'
                break
            elif f.endswith('.tif') is True:
                ext = '.tif'
                break
            else:
                sys.exit('\nERROR: no .DMP or .tif file found in:\n' + pathin)

        filein.append(sorted(glob.glob('*' + ext)))
        nz = len(filein[0])
        os.chdir(curr_dir)

        print('Stack extension: ', ext)
        print('Number of slices: ', nz)

        print('\nLoading images .... ')
        for i in range(nz):
            if i == 0:
                sino = io.readImage(pathin + filein[0][i]).astype(myfloat)
                nang, npix = sino.shape
                sino_list.append(sino)
            else:
                sino_list.append(
                    io.readImage(pathin + filein[0][i]).astype(myfloat))
        print(' done! ')

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

    ##  Check plot
    if args.plot is True:
        if nz == 1:
            dis.plot(sino_list[0], 'Input sinogram')
        else:
            nzz = np.int(nz * 0.5)
            dis.plot(sino_list[nzz], 'Input sinogram')

    ##  Center of rotation axis
    if args.ctr == -1:
        ctr = npix * 0.5

    elif args.ctr != -1:
        ctr = args.ctr

    ##  Enable edge padding
    if args.lt is True:
        edf = 0.87
    elif args.lt is False and args.edge_padding != 0:
        edf = args.edge_padding
    else:
        edf = 0.0

    if edf:
        npix_old = npix
        for i in range(nz):
            sino_list[i] = proc.sino_edge_padding(sino_list[i], edf)
        npix = sino_list[0].shape[1]
        i1 = myint((npix - npix_old) * 0.5)
        i2 = i1 + npix_old
        ctr += i1

        print('\nEdge padding: ', edf)
        print('Number of edge-padded pixels: ', npix)
        print('Index start: ', i1, '   Index end: ', i2)
        print('Center of rotation axis new position: ', ctr)

        if args.plot is True:
            if nz == 1:
                dis.plot(sino_list[0], 'Sinogram with edge-padding')
            else:
                nzz = np.int(nz * 0.5)
                dis.plot(sino_list[nzz], 'Input sinogram')

    else:
        npix_old = npix
        i1 = 0
        i2 = npix

    ##  Compute differential sinogram if DBP option enabled
    if args.dbp is True:
        print('\nComputing differential sinogram ....')
        for i in range(nz):
            sino_list[i] = proc.diff_sino_savitzky_golay(sino_list[i],
                                                         window_size=args.sg)

        if args.plot is True:
            dis.plot(sino_list[0], 'Differential sinogram')

    ##  Correct for the center of rotation axis
    if args.ctr != -1:
        for i in range(nz):
            sino_list[i] = proc.sino_correct_rot_axis(sino_list[i], ctr)

    print('\nCenter of rotation axis position: ', ctr)
    print('Center of rotation corrected')

    ##  Get geometry
    if args.geometry == '0':
        angles = utils.create_projection_angles(nang)
    else:
        angles = utils.create_projection_angles(textfile=pathin +
                                                args.geometry)

    ##  Getting stopping criterion
    print('\nSetup of the iterative procedure:')

    if nz == 0:
        labelout = pathout + filein[0][:len(filein[0]) - 4]
    else:
        labelout = pathout + filein[0][0][:len(filein[0]) - 4]

    param = cap.admm_param(npix_old, nang, nz, ctr, labelout, args)

    print('Projectors enabled: ', args.projector)

    if args.dbp is True:
        print('DBP reconstruction enabled')

    if args.dpc is True:
        print('DPC reconstruction enabled')

    if args.n_iter is not None:
        print('Number of iterations: ', param.n_iter)

    if args.eps is not None:
        print('Stopping epsilon: ', param.eps)

    if args.n_iter_pcg is not None:
        print('Number of PCG iterations: ', param.n_iter_pcg)

    if args.plot is True:
        print('Interactive plot:', param.plot)

    if args.logfile is True:
        print('Interactive plot:', param.logfile)

    if param.reg is not None:
        if param.reg == 'cg':
            print('Conjugate gradient')
        if param.reg == 'lasso':
            print('Regularization type: Lasso L1')
        elif param.reg == 'lasso-tv':
            print('Regularization type: Lasso TV')
        elif param.reg == 'pp-breg':
            print('Regularization type: Plug and Play -- TV Bregman')
        elif param.reg == 'pp-chamb':
            print('Regularization type: Plug and Play -- TV Chambolle')
        elif param.reg == 'pp-nlmeans':
            print('Regularization type: Plug and Play -- Non Local Means')
        elif param.reg == 'pp-tgv':
            print(
                'Regularization type: Plug and Play -- Total generalized variation'
            )
        elif param.reg == 'pp-nltv':
            print(
                'Regularization type: Plug and Play -- Non-local total variation'
            )

        if param.reg != 'cg':
            print('\nLambda 1: ', param.lambd1)
            print('Lambda 2: ', param.lambd2)
            print('Mu:       ', param.mu)

    if args.init_object is True:
        print('\nInitialization with FBP reconstruction:', param.init_object)

    if param.mask is not None:
        print('\nObject support enabled')
        if param.plot is True:
            dis.plot(param.mask, 'Object support')

    if param.mask_add is not None:
        print('\nAdditional supports provided')
        if param.plot is True:
            if param.mask_add_n == 1:
                dis.plot(param.mask_add[0])
            else:
                dis.plot_multi(param.mask_add)

    if param.lt is True:
        print('\nLocal tomography mode enabled')

    ##  Iterative reconstruction
    print('\n\nReconstructing with ADMM ....')
    time1 = time.time()
    reco_list, info = admm(sino_list, angles, param)
    time2 = time.time()
    print('.... reconstruction done!')

    for i in range(nz):
        ##  Crop reconstruction if edge-padding enabled
        if edf != 0.0:
            reco = reco_list[i, i1:i2, i1:i2]
        else:
            reco = reco_list[i, :, :]

        ##  Show reconstruction
        if args.plot is True and nz == 1 and args.reg != 'cg':
            dis.plot(reco, 'Reconstruction')
            plot_convergence_curves(info)
        elif args.plot is True and i == nzz and args.reg != 'cg':
            nzz = np.int(nz * 0.5)
            dis.plot(reco_list[nzz, :, :],
                     'Reconstruction of slice ' + str(nzz))

        ##  Save reconstruction
        if nz == 1:
            save_reco(pathout, filein[0], args, param, reco)
        else:
            save_reco(pathout, filein[0][i], args, param, reco)

    ##  Time elapsed for the reconstruction
    time_tot = (time2 - time1) / 60.0
    print('\nTime elapsed for the reconstruction: ', time_tot)

    ##  Write log file
    if args.logfile is True:
        write_logfile(pathin, pathout, args, angles, ctr, param, time_tot,
                      info)

        write_info(pathout, filein[0], info, param, args)

    ##  Final print
    print('\n')
    print('\n')
    print('##########################################################')
    print('##########################################################')
    print('#####                                                #####')
    print('#####             ADMM Reconstruction done!          #####')
    print('#####                                                #####')
    print('##########################################################')
    print('##########################################################')
    print('\n')
예제 #15
0
def main():

    print('\n')
    print('#############################################################')
    print('############  FOURIER RING CORRELATION ANALYSIS  ############')
    print('#############################################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

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

    ##  Get number of pair of images
    image_string = args.images
    file_list = []

    if image_string.find(',') != -1:
        image_string = image_string.split(',')
        num_img_pair = len(image_string)

        for i in range(num_img_pair):
            file_list.append(image_string[i].split(':'))

    else:
        file_list.append(image_string.split(':'))
        num_img_pair = 1

    num_img = num_img_pair * 2

    print('Number of images to analyze: ', num_img)

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

    for i in range(num_img_pair):
        for j in range(2):
            ##  Read single image
            image_name = file_list[i][j]
            image = io.readImage(image_name)
            m, n = image.shape

            ##  Crop it as a square image
            npix = np.min((m, n))
            i1 = int(0.5 * (m - npix))
            i2 = int(0.5 * (n - npix))
            image = image[i1:i1 + npix, i2:i2 + npix]

            print('Reading image: ', image_name)

            ##  Select resolution square
            if args.resol_square is True:
                print('Calculation enabled in the resol square')
                image = proc.select_resol_square(image)

            ##  Apply hanning window
            if args.hanning is True:
                window = np.hanning(npix)
                window = np.outer(window, window)
                image *= window

            images.append(image)

        ##  Get common prefix
        prefix.append(common_string([file_list[i][0], file_list[i][1]]))

        ##  Check plot
        if args.plot is True:
            dis.plot_multi(
                [images[2 * i], images[2 * i + 1]],
                ['Input image ' + str(2 * i), 'Input image ' + str(2 * i + 1)])

    ##  Get labels for plots
    labels = None
    if args.labels is not (None):
        labels = args.labels
        labels = labels.split(':')

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

    ##  Fourier ring correlation analysis
    frc_curves = []

    for i in range(num_img_pair):
        print('\nCalculating FRC between:\n1)', file_list[i][0],'\n2)',\
                file_list[i][1])

        FRC, spatial_freq = analysis_frc(images[2 * i],
                                         images[2 * i + 1],
                                         args,
                                         pathout,
                                         prefix[i],
                                         file_list[i],
                                         labels=None)
        frc_curves.append(FRC)
    frc_curves = np.array(frc_curves).reshape(num_img_pair, len(spatial_freq))

    ##  Plot FRC curves
    if num_img_pair > 1:
        title = 'FRC - Comparison'
        prefix = 'comparison_curves'
        plot_frc_curves(frc_curves,
                        spatial_freq,
                        args,
                        pathout,
                        prefix,
                        title,
                        labels,
                        mode='multi')

    print('\n##########  FOURIER RING CORRELATION ANALYSIS END  ##########\n')
예제 #16
0
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('#############   REGRIDDING BACKPROJECTION  #############')
    print('########################################################')
    print('\n')


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



    ##  Get input arguments
    args = getArgs()


    
    ##  Get input and output 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!')

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

    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 projections distributed between 0 and'
                +' 180 degrees ---> [0,180)')
        angles = np.arange( nang ).astype( myfloat )
        angles[:] = ( angles * 180.0 )/myfloat( nang )

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

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


    
    ##  Choose filtering function
    filt_list = [ 'none' , 'ramp' , 'shlo' , 'hann' , 'hamm' , 'parz' , 'lanc' ]
    filt = args.filt

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

    print('\nSelected filter: ', filt)

    param = np.zeros( 3 )

    if filt == 'none':
        param[1] = 0
    elif filt == 'ramp':
        param[1] = 1 
    elif filt == 'shlo':
        param[1] = 2 
    elif filt == 'hann':
        param[1] = 3 
    elif filt == 'hamm':
        param[1] = 4 
    elif filt == 'lanc':
        param[1] = 5 
    elif filt == 'parz':
        param[1] = 6


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


    
    ##  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]
        ctr += i1
        
        if args.plot is True:
            dis.plot( sino , 'Edge padded sinogram' )

    param[0] = ctr
    print('Center of rotation axis placed at pixel: ', ctr) 



    ##  Reconstruction with regridding method
    time_rec1 = time.time()
    
    reco = grid.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]  


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


    
    ##  Save reconstruction
    saveReco( reco , pathin , pathout , 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('####   REGRIDDING BACKPROJECTION DONE !   ####')
    print('##############################################')
    print('\n')
예제 #17
0
def main():
    ##  Initial print
    print('\n')
    print('##########################################################')
    print('##########################################################')
    print('#####                                                #####')
    print('#####       STATISTICAL ITERATIVE RECONSTRUCTION     #####')
    print('#####                                                #####')
    print('##########################################################')
    print('##########################################################')
    print('\n')

    ##  Getting arguments
    args = getArgs()

    ##  Get input & output paths
    pathin, pathout = utils.get_io_path(args)

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

    ##  Get input sinogram
    sino_list = []
    filein = []

    if args.filein is not None:
        sinoname = pathin + args.filein
        sino = io.readImage(sinoname).astype(myfloat)
        nang, npix = sino.shape
        nz = 1
        sino_list.append(sino)
        filein.append(args.filein)
        print('\nSinogram to reconstruct:\n', sinoname)

    else:
        print('\nReading stack of images\n')
        curr_dir = os.getcwd()
        os.chdir(pathin)

        for f in os.listdir('./'):
            if f.endswith('.DMP') is True:
                ext = '.DMP'
                break
            elif f.endswith('.tif') is True:
                ext = '.tif'
                break
            else:
                sys.exit('\nERROR: no .DMP or .tif file found in:\n' + pathin)

        filein.append(sorted(glob.glob('*' + ext)))
        nz = len(filein[0])
        os.chdir(curr_dir)

        print('Stack extension: ', ext)
        print('Number of slices: ', nz)

        print('\nLoading images .... ')
        for i in range(nz):
            if i == 0:
                sino = io.readImage(pathin + filein[0][i]).astype(myfloat)
                nang, npix = sino.shape
                sino_list.append(sino)
            else:
                sino_list.append(
                    io.readImage(pathin + filein[0][i]).astype(myfloat))
        print(' done! ')

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

    ##  Check plot
    if args.plot is True:
        if nz == 1:
            dis.plot(sino_list[0], 'Input sinogram')
        else:
            nzz = np.int(0.5 * nz)
            dis.plot(sino_list[nzz], 'Input sinogram')

    ##  Center of rotation axis
    if args.ctr == -1:
        ctr = npix * 0.5

    elif args.ctr != -1:
        ctr = args.ctr

    ##  Enable edge padding
    if args.lt is True:
        edf = 0.87
    elif args.lt is False and args.edge_padding != 0:
        edf = args.edge_padding
    else:
        edf = 0.0

    if edf:
        npix_old = npix
        for i in range(nz):
            sino_list[i] = proc.sino_edge_padding(sino_list[i], edf)
        npix = sino_list[0].shape[1]
        i1 = myint((npix - npix_old) * 0.5)
        i2 = i1 + npix_old
        ctr += i1

        print('\nEdge padding: ', edf)
        print('Number of edge-padded pixels: ', npix)
        print('Index start: ', i1, '   Index end: ', i2)
        print('Center of rotation axis new position: ', ctr)

        if args.plot is True:
            dis.plot(sino_list[0], 'Sinogram with edge-padding')

    else:
        npix_old = npix
        i1 = 0
        i2 = npix

    ##  Correct for the center of rotation axis
    if args.ctr != -1:
        for i in range(nz):
            sino_list[i] = proc.sino_correct_rot_axis(sino_list[i], ctr)

    print('\nCenter of rotation axis position: ', ctr)
    print('Center of rotation corrected')

    ##  Get geometry
    if args.geometry == '0':
        angles = utils.create_projection_angles(nang)
    else:
        angles = utils.create_projection_angles(textfile=pathin +
                                                args.geometry)

    ##  Setup iterative procedure
    print('\nSetup of the iterative procedure:')

    if nz == 0:
        labelout = pathout + filein[0][:len(filein[0]) - 4]
    else:
        labelout = pathout + filein[0][0][:len(filein[0]) - 4]

    param = csp.sir_param(nang, npix_old, nz, ctr, labelout, args)

    print('Selected projector: ', args.projector)

    if args.eps is not None:
        print('Stopping threshold: ', param.eps)

    if args.n_iter is not None:
        print('Number of iterations: ', param.n_iter)

    if args.plot is True:
        print('Interactive plot:', param.plot)

    if args.logfile is True:
        print('Interactive plot:', param.logfile)

    if param.reg is not None:
        if param.reg == 'huber':
            print('Regularization type: Huber penalty')
            print('Huber constant ---> delta: ')
        elif param.reg == 'tikhonov':
            print('Regularization type: l2 penalty')
        elif param.reg == 'haar':
            print('Regularization type: l1 penalty')

        print('Regularization constant (beta): ', param.reg_cost)

    if args.init_object is True:
        print('Initialization with FBP reconstruction:', param.init_object)

    ##  Reconstruction
    print('\n\nPerforming STASTICAL ITERATIVE RECONSTRUCTION ....')
    time1 = time.time()
    reco_list, info = sir(sino_list, angles, param)
    time2 = time.time()
    print('.... reconstruction done!')

    for i in range(nz):
        ##  Crop reconstruction if edge-padding enabled
        if edf != 0.0:
            reco = reco_list[i, i1:i2, i1:i2]
        else:
            reco = reco_list[i, :, :]

        ##  Show reconstruction
        if args.plot is True and nz == 1:
            dis.plot(reco, 'Reconstruction')
        elif args.plot is True and i == nzz:
            dis.plot(reco, 'Reconstruction')

        ##  Save reconstruction
        if nz == 1:
            save_reco(pathout, filein[0], args, param, reco)
        else:
            save_reco(pathout, filein[0][i], args, param, reco)

    ##  Time elapsed for the reconstruction
    time_tot = (time2 - time1) / 60.0
    print('\nTime elapsed for the reconstruction: ', time_tot)

    ##  Write log file
    if args.logfile is True:
        write_logfile(pathin, pathout, args, angles, ctr, param, time_tot,
                      info)

        write_info(pathout, filein[0], info, param, args)

    ##  Final print
    print('\n')
    print('\n')
    print('##########################################################')
    print('##########################################################')
    print('#####                                                #####')
    print('#####   STATISTICAL ITERATIVE RECONSTRUCTION DONE!   #####')
    print('#####                                                #####')
    print('##########################################################')
    print('##########################################################')
    print('\n')
def multi_thread(pathin, pathout, filein, angles, args):
    image = io.readImage(pathin + filein).astype(myfloat)
    npix = image.shape[0]
    tp = cpj.projectors(npix, angles, args=args)
    sino = tp.A(image)
    save_sinogram(pathout, filein, angles, args, sino)
def main():
    ##  Initial print
    print('\n')
    print('###########################################################')
    print('#############   FORWARD REGRIDDING PROJECTOR  #############')
    print('###########################################################')
    print('\n')

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

    ##  Get input arguments
    args = getArgs()

    ##  Get input/output directory
    pathin, pathout = utils.get_io_path(args)

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

    ##  Get input files
    file_list, file1, nimg, ext = utils.get_input(args, pathin)

    print('\nNumber of input files: ', nimg)
    print('Extension of the files: ', ext)

    ##  Read first image
    image = io.readImage(pathin + file1).astype(myfloat)
    npix = image.shape[0]

    print('\nFirst image to forward project: ', file1)
    print('Number of pixels: ', npix)

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

    ##  Get projection angles
    if args.geometry == '0' or args.geometry == '1':
        nang = args.nang
        angle_type = myint(args.geometry)

        if args.angle_range.find(':') == -1 or args.geometry == -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])

        angles = utils.create_projection_angles(nang, angle_start, angle_end)

    else:
        angles = utils.create_projection_angles(pathin + args.geometry)

    nang = len(angles)

    print('\nNumber of views: ', nang)
    print('Selected angle range: [ ', angle_start, ' , ', angle_end, ' )')
    print('Angles:\n', angles)

    ##  Initialize projectior class
    tp = cpj.projectors(npix, angles, args=args)

    ##  Apply forward projection operator
    time_rec1 = time.time()
    sino = tp.A(image)
    time_rec2 = time.time()

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

    ##  Save sinogram
    save_sinogram(pathout, file1, angles, args, sino)

    ##  Create sinograms from all the other images in the stack
    if args.filein is None:
        pool = mproc.Pool()
        for i in range(1, nimg):
            pool.apply_async(multi_thread,
                             (pathin, pathout, file_list[0][i], angles, args))
        pool.close()
        pool.join()
    time2 = time.time()

    print('\nTime elapsed to run the 1st 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')
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')
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('####              CREATE VIRTUAL SINOGRAM           ####')
    print('########################################################')
    print('\n')  



    ##  Get arguments
    args = getArgs()



    ##  Get input/output directory
    pathin , pathout = utils.get_io_path( args )
    
    print('\nInput path:\n', pathin)
    print('\nOutput path:\n', pathout)



    ##  Get input files
    file_list , file1 , nimg , ext = utils.get_input( args , pathin )
    
    print('\nNumber of input files: ' , nimg)
    print('Extension of the files: ', ext)



    ##  Read first sinogram
    sino = io.readImage( pathin + file1 ).astype( myfloat )
    nang , npix = sino.shape

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

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



    ##  Set center of rotation axis
    if args.ctr == None:
        ctr = 0.0
        print('Center of rotation axis placed at pixel: ', npix * 0.5)  
    else:
        ctr = args.ctr
        print('Center of rotation axis placed at pixel: ', ctr)



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

        if ctr != 0.0:
            ctr += i1
        
        if args.plot is True:
            dis.plot( sino , 'Edge padded sinogram' )
    else:
        i1 = 0
        i2 = npix 



    ##  Prepare projectors
    ang = np.arange( nang ) * 180.0 / myfloat( nang )  
    tp = cpj.projectors( npix , ang , kernel='kb' , oversampl=2.32 , 
                         W=6.6 , errs=6.0e-6 , interp='lin' , 
                         radon_degree=0 , filt=args.filt , ctr=ctr ) 



    ##  Reconstruct
    reco = tp.fbp( sino )
    if args.plot is True:
        dis.plot( reco , 'Reconstruction' ) 
    #reco = reco[i1:i2,i1:i2]



    ##  Zero-out pixels outside resolution circle
    reco_new = reco.copy();  reco_new[:] = 0.0
    io.writeImage( 'reco.DMP' , reco[i1:i2,i1:i2] ) 
    reco_new[i1:i2,i1:i2] = utils.resol_circle_constr( reco[i1:i2,i1:i2] )
    reco[:] = reco_new[:]

    if args.plot is True:
        dis.plot( reco , 'Constrained reconstruction' )
    io.writeImage( 'reco_circle.DMP' , reco )



    ##  Background equalization
    reco[:] = background_equalization( reco )

    if args.plot is True:
        dis.plot( reco , 'Equalized reconstruction' )
    io.writeImage( 'reco_equaliz.DMP' , reco )



    ##  Forward projection
    nang_new = np.int( npix * np.pi / 2.0 )
    ang_new  = np.arange( nang_new ) * 180.0 / np.float32( nang_new )
    tp       = cpj.projectors( npix , ang_new , kernel='kb' , oversampl=2.32 , 
                               W=6.6 , errs=6.0e-6 , interp='lin' , 
                               radon_degree=0 ) 
    sino = tp.A( reco )
    #sino = sino[:,i1:i2]

    if args.plot is True:
        dis.plot( sino , 'Forward projection' )
    io.writeImage( 'sino_circle.DMP' , sino )



    ##  Save output file
    if args.fileout is None:
        filein    = args.filein
        extension = filein[len(filein)-4:]
        fileout   = filein[:len(filein)-4] + '_virt.tif'
    else:
        fileout = args.fileout
    io.writeImage( pathout + fileout , sino )
    print( '\nWritten output file:\n' , pathout + fileout )
def main():
    print('\n')
    print('#######################################')
    print('#######################################')
    print('###                                 ###')
    print('###         MEAN SQUARE ERROR       ###')
    print('###                                 ###')
    print('#######################################')
    print('#######################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

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

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

    image_list = []
    results = []

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

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

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

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

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

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

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

                if args.roi.find(',') != -1:
                    roi = roi.split(',')
                    p0 = [int(roi[0].split(':')[1]), int(roi[0].split(':')[0])]
                    p1 = [int(roi[1].split(':')[1]), int(roi[1].split(':')[0])]

                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                    image1 = proc.crop_image(image1, p0, p1)
                    image2 = proc.crop_image(image2, p0, p1)

                else:
                    print('\nUsing pixels specified in file:\n', roi)
                    file_roi = open(roi, 'r')
                    pixels = np.loadtxt(file_roi)
                    image1 = image1[pixels[:, 0], pixels[:, 1]]
                    image2 = image2[pixels[:, 0], pixels[:, 1]]
                    num_pix = len(image1)
                    fact = factors(num_pix)
                    image1 = image1.reshape(fact[0], int(num_pix / fact[0]))
                    image2 = image2.reshape(fact[0], int(num_pix / fact[0]))

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

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

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

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

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

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

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

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

                ## Scale image to analyze with respect to the reference one
                if args.scaling is True:
                    print('\nPerforming linear regression ....')
                    image2 = proc.linearRegression(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.selectResolutionSquare(image1)
                    image2 = proc.selectResolutionSquare(image2)

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

                    if args.roi.find(',') != -1:
                        roi = roi.split(',')
                        p0 = [
                            int(roi[0].split(':')[1]),
                            int(roi[0].split(':')[0])
                        ]
                        p1 = [
                            int(roi[1].split(':')[1]),
                            int(roi[1].split(':')[0])
                        ]

                        print('Cropping rectangular ROI with vertices:  ( ', \
                                p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                        image1 = proc.crop_image(image1, p0, p1)
                        image2 = proc.crop_image(image2, p0, p1)

                    else:
                        print('\nUsing pixels specified in file:\n', roi)
                        file_roi = open(roi, 'r')
                        pixels = np.loadtxt(file_roi)
                        pixels = pixels.astype(int)

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

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

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

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

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

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

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

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

        ## Loop on all the images to analyze
        for i in range(num_img):
            image1 = io.readImage(args.image1)
            image2 = io.readImage(image_list[i])
            image2 = image2.astype(myfloat)
            print('\n\n\nIMAGE TO ANALYZE NUMBER: ', i)
            print('\nReading image to analyze:\n', image_list[i])
            print('Image shape: ', image2.shape)

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

            ## Scale image to analyze with respect to the reference one
            if args.scaling is True:
                print('\nPerforming linear regression ....')
                image2 = proc.linearRegression(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.selectResolutionSquare(image1)
                image2 = proc.selectResolutionSquare(image2)

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

                if args.roi.find(',') != -1:
                    roi = roi.split(',')
                    p0 = [int(roi[0].split(':')[1]), int(roi[0].split(':')[0])]
                    p1 = [int(roi[1].split(':')[1]), int(roi[1].split(':')[0])]

                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                    image1 = proc.crop_image(image1, p0, p1)
                    image2 = proc.crop_image(image2, p0, p1)

                else:
                    print('\nUsing pixels specified in file:\n', roi)
                    file_roi = open(roi, 'r')
                    pixels = np.loadtxt(file_roi)
                    pixels = pixels.astype(int)

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

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

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

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

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

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

        os.chdir(currDir)

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

    for i in range(num_img):
        print('\n\nTest image number ', i, '\n', image_list[i], '\n')
        print('SNR = ', results[i][0])
        print('PSNR = ', results[i][1])
        print('MRSE = ', results[i][2])
        print('MAE = ', results[i][3])

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

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

    print('\n\n')
예제 #23
0
def main():
    print('###################################################')  
    print('######  SPLITTING SINOGRAM FOR FRC ANALYSIS  ######')
    print('###################################################') 

    
    
    ##  Get input arguments
    args = getArgs()

    
    
    ##  Get input and output paths
    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)



    ##  Case 1: one sinogram in input
    if args.sino is not None:
        ##  Handle sinograms
        print('\nReading sinogram: ',args.sino)
        sino = io.readImage( pathin + args.sino )
        nang = sino.shape[0]

        print('\nSplitting sinogram in the sinogram with odd- and with' +
              ' even-projections ....')      
        sino_odd , sino_even = split_sino( sino ) 

        sino_name = args.sino
        sino_name_odd = sino_name.replace( '.DMP' , '.proj_odd.DMP' )
        sino_name_even = sino_name.replace( '.DMP' , '.proj_even.DMP' )
        
        print('\nWriting ',sino_name_odd,' ....' )
        io.writeImage( pathout + sino_name_odd , sino_odd )
    
        print('Writing ',sino_name_even,' ....' )  
        io.writeImage( pathout + sino_name_even , sino_even ) 

        
        ##  Handle projection angle lists
        if args.geometry is not None:
            print('\nReading list of projection angles (degrees): ',args.geometry)
            angle_list = np.loadtxt( pathin + args.geometry )
            angle_list_odd , angle_list_even = split_angle_list( angle_list )


            list_name = args.geometry
            list_name_odd = list_name.replace( '.txt' , '.proj_odd.txt' )
            list_name_even = list_name.replace( '.txt' , '.proj_even.txt' )

        else:
            print('\nCreating lists of projection angles')
            angle_list_odd , angle_list_even = create_angle_list( nang )
            list_name_odd = sino_name.replace( '.DMP' , '.proj_odd.txt' )
            list_name_even = sino_name.replace( '.DMP' , '.proj_even.txt' )  

        
        print('Writing ',list_name_odd,' ....' )
        np.savetxt( pathout + list_name_odd , angle_list_odd )
    
        print('Writing ',list_name_even,' ....' )
        np.savetxt( pathout + list_name_even , angle_list_even )


    
    ##  Case 2: all sinogram in input folder
    elif args.allin is True:
        curr_dir = os.getcwd()
        os.chdir( pathin )

        sino_list = sorted( glob.glob( '*.DMP' ) )

        if args.geometry == 'a':
            angle_file_list = sorted( glob.glob( '*.txt' ) )

        os.chdir( curr_dir )

        nsino = len( sino_list )

        print('\nNumber of sinograms in input folder: ', nsino)

        for f in range( nsino ):
            print('\nReading sinogram: ', sino_list[f] )
            sino = io.readImage( pathin + sino_list[f] )
            nang = sino.shape[0]

            print('\nSplitting sinogram in the sinogram with odd- and with' +
                   ' even-projections ....')
            sino_odd , sino_even = split_sino( sino ) 

            sino_name = sino_list[f]
            sino_name_odd = sino_name.replace( '.DMP' , '.proj_odd.DMP' )
            sino_name_even = sino_name.replace( '.DMP' , '.proj_even.DMP' )

            print('\nWriting ',sino_name_odd,' ....' )            
            io.writeImage( pathout + sino_name_odd , sino_odd )
    
            print('Writing ',sino_name_even,' ....' )  
            io.writeImage( pathout + sino_name_even , sino_even )    

            
            if args.geometry == 'a':
                print('\nReading list of projection angles (degrees): ', angle_file_list[f])
                angle_list = np.loadtxt( pathin + angle_file_list[f] )

                print('\nSplitting angle lists between odd-indexed and with' +
                      ' even-indexed angles ....')      
                angle_list_odd , angle_list_even = split_angle_list( angle_list ) 

                list_name = angle_file_list[f]
                list_name_odd = list_name.replace( '.txt' , '.proj_odd.txt' )
                list_name_even = list_name.replace( '.txt' , '.proj_even.txt' )

            else:
                print('\nCreating lists of projection angles')
                angle_list_odd , angle_list_even = create_angle_list( nang )
                list_name_odd = sino_name.replace( '.DMP' , '.proj_odd.txt' )
                list_name_even = sino_name.replace( '.DMP' , '.proj_even.txt' )  

            print('Writing ',list_name_odd,' ....' )
            np.savetxt( pathout + list_name_odd , angle_list_odd )
    
            print('Writing ',list_name_even,' ....' )
            np.savetxt( pathout + list_name_even , angle_list_even )


    print('\n#######################################################\n')  
    print('\n######  END SPLITTING SINOGRAM FOR FRC ANALYSIS  ######\n')
    print('\n#######################################################\n')      
    def __init__(self, npix, nang, nz, ctr, labelout, args):
        ##  Entries with no check
        self.ctr = ctr
        self.nang = nang
        self.nz = nz
        self.n_iter = args.n_iter
        self.n_iter_pcg = args.n_iter_pcg
        self.eps = args.eps
        self.plot = args.plot
        self.logfile = args.logfile
        self.init_object = args.init_object
        self.pc = args.pc
        self.mask = []
        self.lt = args.lt
        self.num_cores = args.num_cores

        ##  Tomographic projectors
        self.projector = args.projector

        ##  Enable DPC reconstruction
        if args.dpc is True or args.dbp is True:
            self.radon_degree = 1
        else:
            self.radon_degree = 0

        ##  Check point
        if self.radon_degree == 1:
            if self.projector == 'pix-driv' or self.projector == 'ray-driv' \
               or self.projector == 'dist-driv':
                sys.exit( '\nERROR: selected projector ' + self.projector + \
                          ' cannot be used for differentiated tomography!!\n')

        ##  Handling regularization
        if args.reg is not None:
            self.reg = args.reg

        if args.param is None:
            if self.reg == 'lasso' or self.reg == 'lasso-tv':
                param = '1.0:1.0:1.0'
            elif self.reg == 'pp-breg':
                param = '1.0:100.0:1.0'
        elif self.reg != 'cg':
            param = args.param

        ##  Handling parameters
        if self.reg != 'cg':
            param = param.split(':')
            self.lambd1 = myfloat(param[0])
            self.lambd2 = myfloat(param[1])
            self.mu = myfloat(param[2])
            self.relax = 1.0
            self.z1 = args.inner_padding

        ##  Handling edge padding
        if args.lt is True:
            pad_factor = 0.87
        elif args.lt is False and args.edge_padding:
            pad_factor = args.edge_padding
        else:
            pad_factor = 0.0

        if pad_factor == 0:
            self.index_start = 0
            self.index_end = npix
            self.edge_padding = False
            self.npix_op = npix
        else:
            npad = int(pad_factor * npix)
            npix_new = npix + 2 * npad
            self.index_start = myint(0.5 * (npix_new - npix))
            self.index_end = self.index_start + npix
            self.edge_padding = True
            self.npix_op = npix_new

        ##  Output name root
        if self.reg != 'cg':
            root = '_admm'

            if self.reg == 'lasso':
                root += '_lasso'
            elif self.reg == 'lasso-tv':
                root += '_lassotv'
            elif self.reg == 'pp-breg':
                root += '_ppbreg'
            elif args.reg == 'pp-rof':
                root += '_pprof'
            elif args.reg == 'pp-breg':
                root += '_ppbreg'
            elif args.reg == 'pp-chamb':
                root += '_ppchamb'
            elif args.reg == 'pp-nlmeans':
                root += '_ppnlmeans'
            elif args.reg == 'pp-tgv':
                root += '_pptgv'
            elif args.reg == 'pp-nltv':
                root += '_ppnltv'

            string = '_lambd1_' + str( self.lambd1 ) + \
                     '_lambd2_' + str( self.lambd2 ) + \
                     '_mu_' + str( self.mu )
            root += string
        else:
            root = '_cgls'

        if self.projector == 'grid-kb':
            root += '_grid_kb'
        elif self.projector == 'grid-pswf':
            root += '_grid_pswf'
        elif self.projector == 'bspline':
            root += '_bspline'
        elif self.projector == 'radon':
            root += '_radon'
        elif self.projector == 'pix-driv':
            root += '_pd'
        elif self.projector == 'ray-driv':
            root += '_rd'
        elif self.projector == 'dist-driv':
            root += '_dd'

        self.root = root

        ##  Saving each iteration result for analysis
        if args.checkit is not None:
            self.checkit = True
            path_rmse = '_rmse_folder'
            path_rmse = args.checkit + path_rmse + '/'
            if not os.path.exists(path_rmse):
                os.makedirs(path_rmse)
            else:
                shutil.rmtree(path_rmse)
                os.makedirs(path_rmse)
            self.path_rmse = path_rmse
        else:
            self.checkit = False

        ##  Object support
        if args.mask is not None:
            self.mask = io.readImage(args.mask).astype(np.uint8)
        else:
            self.mask = None

        ##  Additional masks
        if args.mask_add is not None:
            if args.mask_add.find(',') != -1:
                files = args.mask_add.split(',')
                nfiles = len(files)
                self.mask_add = []
                for i in range(nfiles):
                    self.mask_add.append(
                        io.readImage(files[i]).astype(np.uint8))
                self.mask_add_n = nfiles
            else:
                files = args.mask_add
                nfiles = 1
                self.mask_add = []
                self.mask_add.append(io.readImage(files).astype(np.uint8))
                self.mask_add_n = nfiles
        else:
            self.mask_add = None
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('###                 NN-FBP RECONSTRUCTION            ###')
    print('########################################################')
    print('\n')

    
    
    ##  Read config file
    if len( sys.argv ) < 2:
        sys.exit( '\nERROR: Missing input config file .cfg!\n' )
    else:
        cfg_file = open( sys.argv[1] , 'r' )
        exec( cfg_file )
        cfg_file.close()
        
    
    ##  Get trained filters
    train_path = utils.analyze_path( train_path , mode='check' )
    ft = np.load( train_path + file_trained_filters )
    print( '\nRead file of trained filters:\n' , train_path + file_trained_filters )

    
    ##  Get low-quality sinograms
    cwd = os.getcwd()
    target_path = utils.analyze_path( target_path , mode='check' )
    
    os.chdir( target_path )    
    file_list = []
    file_list.append( sorted( glob.glob( '*' + input_files_lq + '*' ) ) )
    os.chdir( cwd )
    
    nfiles = len( file_list )
    if nfiles == 0:
        sys.exit( '\nERROR: No file *' + input_files_lq + '* found!\n' )
        
    
    ##  Check/create output path
    output_path = utils.analyze_path( output_path , mode='create' )
        

    ##  Read one sinogram
    sino = io.readImage( target_path + file_list[0][0] )
    nang , npix = sino.shape
    
    
    ##  Create angles
    angles = utils.create_projection_angles( nang=nang )

        
    ##  Create filters     
    fW      = ft['filters']
    weights = ft['weights']
    offsets = ft['offsets']
    minIn   = ft['minIn']
    maxIn   = ft['maxIn']           

    fsize = 2 * ( 2**int( np.ceil( np.log2( npix ) ) ) )
    basis = utils.generateFilterBasis( fsize , 2 ).astype( myfloat )
    
    NHidden = fW.shape[0]
    filters = np.zeros( ( NHidden , fsize ))
    for i in xrange( NHidden ):
        for j in xrange( basis.shape[0] ):
            filters[i] += basis[j] * fW[i,j]


    ##  Reconstruct low-quality sinograms
    print( '\nNN-FBP reconstruction ....' )
    ncores_avail = mproc.cpu_count
    if ncores > ncores_avail:
        ncores =  ncores_avail     

    pool = mproc.Pool( processes=ncores )
    for i in range( nfiles ):
        pool.apply_async( reconstr_nnfbp , ( target_path , output_path , file_list[0][i] , angles , ctr_lq , 
                                             weights , offsets , minIn , maxIn , NHidden , filters  ) )
    pool.close()
    pool.join() 
    
    #for i in range( nfiles ):
    #    reconstr_nnfbp( target_path , output_path , file_list[0][i] , angles , ctr_lq , 
    #                    weights , offsets , minIn , maxIn , NHidden , filters )

    print( '\n' )    
예제 #26
0
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('###              CREATING TRAINING DATASET           ###')
    print('########################################################')
    print('\n')

    ##  Read config file
    if len(sys.argv) < 2:
        sys.exit('\nERROR: Missing input config file .cfg!\n')
    else:
        cfg_file = open(sys.argv[1], 'r')
        exec(cfg_file)
        cfg_file.close()

    ##  Get list of input files
    cwd = os.getcwd()

    input_path = utils.analyze_path(input_path, mode='check')

    os.chdir(input_path)
    file_list = []
    file_list.append(sorted(glob.glob('*' + input_files_hq + '*')))
    os.chdir(cwd)

    nfiles = len(file_list[0])
    if nfiles == 0:
        sys.exit('\nERROR: No file *' + input_files_hq + '* found!\n')

    train_path = utils.analyze_path(train_path, mode='create')

    print('\nInput data folder:\n', input_path)
    print('\nTrain data folder:\n', train_path)
    print('\nInput high-quality sinograms: ', nfiles)

    ##  Read one file
    sino = io.readImage(input_path + file_list[0][0])
    nang, npix = sino.shape
    print('\nSinogram(s) with ', nang, ' views X ', npix, ' pixels')

    ##  Create array of projection angles
    angles = utils.create_projection_angles(nang=nang)

    ##  Compute number of views for low-quality training sinograms
    factor = nang / (nang_lq * 1.0)
    print('\nDownsampling factor for training sinograms: ', factor)

    ##  Create customized filters
    print('\nCreating customized filters ....')
    filt_size = 2 * (2**int(np.ceil(np.log2(npix))))
    filt_custom = utils.generateFilterBasis(filt_size, 2)
    nfilt = filt_custom.shape[0]

    ##  Region of interest to select training data
    idx = utils.getIDX(npix, roi_l, roi_r, roi_b, roi_t)
    nh = np.int(npix * 0.5)
    l = np.abs(roi_l)

    ##  Create training dataset
    print('\nCreating training dataset ....', end='')

    ncores_avail = mproc.cpu_count
    if ncores > ncores_avail:
        ncores = ncores_avail

    for i in range(nfiles):
        ##  Read high-quality sinogram
        sino_hq = io.readImage(input_path + file_list[0][i]).astype(myfloat)

        ##  Reconstruct high-quality sinogram with standard filter
        reco_hq = utils.fbp(sino_hq, angles, [ctr_hq, 1.0], None)

        ##  Create output training array
        train_data = np.zeros((npix_train_slice, nfilt + 1), dtype=myfloat)

        ##  Randomly select training pixels
        picked = utils.getPickedIndices(idx, npix_train_slice)

        ##  Save validation data
        #train_data[:,-1] = reco_hq[picked]
        train_data[:, -1] = reco_hq[nh - l:nh + l, nh - l:nh + l].reshape(-1)

        ##  Downsample sinogram
        sino_lq, angles_lq = utils.downsample_sinogram_angles(
            sino_hq, angles, nang_lq)

        ##  Reconstruct low-quality sinograms with customized filters
        #pool = mproc.Pool( processes=ncores )
        #results = [ pool.apply_async( reconstr_filter_custom ,
        #                              args=( sino_lq , angles_lq , ctr_hq , filt_custom[j,:] , picked ) ) \
        #                              for j in range( nfilt ) ]
        #train_data[:,:nfilt] = np.array( [ res.get() for res in results ] ).reshape( npix_train_slice , nfilt )
        #pool.close()
        #pool.join()

        for j in range(nfilt):
            train_data[:,
                       j] = reconstr_filter_custom(sino_lq, angles_lq, ctr_hq,
                                                   filt_custom[j, :], picked,
                                                   nh, l)

        ##  Save training data
        filename = file_list[0][i]
        fileout = train_path + filename[:len(filename) - 4] + '_train.npy'
        np.save(fileout, train_data)
        print('\nTraining data saved in:\n', fileout)

        #filename = file_list[0][i]
        #fileout  = train_path + filename[:len(filename)-4] + '_reco.DMP'
        #io.writeImage( fileout , reco_hq )

    print('\n')
def main():
    ##  Initial print
    print('\n')
    print('##################################################################')
    print('#############   TOMOGRAPHIC GRIDDING RECONSTRUCTION  #############')
    print('##################################################################')
    print('\n')

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

    ##  Get input arguments
    args = getArgs()

    ##  Get input/output directory
    pathin, pathout = utils.get_io_path(args)

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

    ##  Get input files
    file_list, file1, nimg, ext = utils.get_input(args, pathin)

    print('\nNumber of input files: ', nimg)
    print('Extension of the files: ', ext)

    ##  Read first sinogram
    sino = io.readImage(pathin + file1).astype(myfloat)
    nang, npix = sino.shape

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

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

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

        if ctr != 0.0:
            ctr += i1

        if args.plot is True:
            dis.plot(sino, 'Edge padded sinogram')
    else:
        i1 = 0
        i2 = npix
        ctr = args.ctr

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

    else:
        print('\nReading list of projection angles:\n', pathin + args.geometry)
        angles = utils.create_projection_angles(textfile=pathin +
                                                args.geometry)

    if args.plot is True:
        print('\nProjection angles:')
        pp.printArray(angles)

    ##  Enable object support calculation
    if args.object_support is True:
        print('\nObject support calculation enabled')
        mask = ob.object_support(sino)
        if args.plot is True:
            dis.plot(mask, 'Object support mask')

    ##  Differential sinogram fo DBP
    if args.dbp is True:
        print('\nDifferential backprojection enabled')
        print(
            'Computing differential sinogram by means of Savitzky-Golay method'
        )
        sino[:, :] = proc.diff_sino_savitzky_golay(sino, window_size=11)

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

    ##  Initialize projectior class
    tp = cpj.projectors(npix, angles, ctr=ctr, args=args)

    ##  Apply forward projection operator
    time_rec1 = time.time()
    reco = tp.fbp(sino)
    time_rec2 = time.time()

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

    ##  Apply object support mask
    if args.object_support is True:
        reco[mask == 0] = 0.0

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

    ##  Save reconstruction
    save_reconstruction(pathout, file1, args, reco)

    ##  Reconstruct sinograms from all the other images in the stack
    if args.filein is None:
        pool = mproc.Pool()
        for i in range(1, nimg):
            pool.apply_async(
                multi_thread,
                (pathin, pathout, file_list[0][i], args, [i1, i2]))
        pool.close()
        pool.join()
    time2 = time.time()

    print('\nTime elapsed to run the 1st backward gridrec: ',
          time_rec2 - time_rec1)
    print('Total time elapsed for the run of the program: ', time2 - time1)

    print('\n')
    print('##############################################')
    print('####    GRIDDING RECONSTRUCTION DONE !    ####')
    print('##############################################')
    print('\n')
def main():
    ##  Initial print
    print('\n')
    print('########################################################')
    print('###              CREATING TRAINING DATASET           ###')
    print('########################################################')
    print('\n')

    
    
    ##  Read config file
    if len( sys.argv ) < 2:
        sys.exit( '\nERROR: Missing input config file .cfg!\n' )
    else:
        cfg_file = open( sys.argv[1] , 'r' )
        exec( cfg_file )
        cfg_file.close()
        
    
    ##  Get list of input files
    cwd = os.getcwd()
    
    input_path = utils.analyze_path( input_path , mode='check' )
    
    os.chdir( input_path )
    file_list = []    
    file_list.append( sorted( glob.glob( '*' + input_files_hq + '*' ) ) )
    os.chdir( cwd )
    
    nfiles = len( file_list[0] )
    if nfiles == 0:
        sys.exit( '\nERROR: No file *' + input_files_hq + '* found!\n' )
    
    if train_path == input_path:
        train_path = utils.analyze_path( train_path , mode='check' )
    else:
        train_path = utils.analyze_path( train_path , mode='create_new' )    
        
    print( '\nInput data folder:\n' , input_path )
    print( '\nTrain data folder:\n' , train_path )
    print( '\nInput high-quality sinograms: ' , nfiles )
        
    
    ##  Read one file
    sino = io.readImage( input_path + file_list[0][0] )
    nang , npix = sino.shape
    print( '\nSinogram(s) with ' , nang ,' views X ' , npix, ' pixels' )
    
    
    ##  Create array of projection angles
    angles = utils.create_projection_angles( nang=nang )
    
     
    ##  Compute number of views for low-quality training sinograms
    factor = nang / ( nang_lq * 1.0 )
    print( '\nDownsampling factor for training sinograms: ' , factor )
    
    
    ##  Create customized filters
    print( '\nCreating customized filters ....' )
    filt_size   = 2 * ( 2**int( np.ceil( np.log2( npix ) ) ) )
    filt_custom = utils.generateFilterBasis( filt_size , 2 )
    nfilt       = filt_custom.shape[0]
    

    ##  Region of interest to select training data
    idx = utils.getIDX( npix , roi_l , roi_r , roi_b , roi_t )
    nh = np.int( npix * 0.5 );  l   = np.abs( roi_l )
    
    
    ##  Create training dataset 
    print( '\nCreating training dataset ....' ) 
    
    ncores_avail = mproc.cpu_count()
    if ncores > ncores_avail:
        ncores =  ncores_avail        
    print( 'Working with ncores: ' , ncores )

        
    if slice_ind_1 > 0 and slice_ind_1 <= nfiles:
        ind_1 = slice_ind_1
    else:
        ind_1 = 0
        
    if slice_ind_2 > 0 and slice_ind_2 <= nfiles:
        ind_2 = slice_ind_2
    else:
        ind_2 = nfiles
        
    if take_every <= 0 or take_every >= (ind_2-ind_1):
        take_every = 1
    print( 'Start slice index: ' , ind_1 )
    print( 'End slice index: ' , ind_2 )
    print( 'Use 1 slice every ', take_every,' slices' )
    
    pool = mproc.Pool( processes=ncores )
    for i in range( ind_1 , ind_2 , take_every ):
        pool.apply_async( create_training_file , 
                          ( input_path , train_path , file_list[0][i] , angles ,
                            npix_train_slice , idx , nang_lq , ctr_hq , nfilt ,
                            filt_custom , filt , debug ) 
                        )            
    pool.close()
    pool.join()
예제 #29
0
파일: fsc.py 프로젝트: arcaduf/analysis
def main():

    ##  Get input arguments
    args = get_args()
    
    
    
    ##  Start print
    if args.analysis == 'frc':
        print('\n')
        print('#############################################################')
        print('############  FOURIER RING CORRELATION ANALYSIS  ############')
        print('#############################################################')
        print('\n')

    else:
        print('\n')
        print('##############################################################')
        print('############  FOURIER SHELL CORRELATION ANALYSIS  ############')
        print('##############################################################')
        print('\n')    

    

    ##  Get input and output folder
    pathin = args.pathin
    if pathin[len(pathin)-1] != '/':
        pathin += '/'
        
    pathout = args.pathout
    if pathout[len(pathout)-1] != '/':
        pathout += '/'
    if os.path.exists( pathout ) is False:
        os.mkdir( pathout )


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



    ##  Check whether you are working with .tif or .DMP images
    extension = None
    for root, dirs, files in os.walk( pathin ):
        for file in files:
            if file.endswith( '.tif' ):
                extension = '.tif'
            elif file.endswith( '.DMP' ):
                extension = '.DMP'

    if extension is None:
        sys.exit( 'ERROR: No .tif or .DMP file found in:\n ' + pathin )
    else:
        print('\nWorking with ', extension,' images')



    ##  Get stack of input even and odd images
    files_even = sorted( glob.glob( pathin + '*even*' + extension ) )
    files_odd = sorted( glob.glob( pathin + '*odd*' + extension ) )

    if len( files_even ) != len( files_odd ):
        sys.exit( '\nNumber of "even" images (' + str( len( files_even ) ) + ')' \
                  ' the number od odd images (' + str( len( files_odd ) ) + ')' )
    else:
        n_img = len( files_even )
        #n_img = 1

    print('\nNumber of input image pair: ', n_img)

    stack_even = [];  stack_odd = []

    print('\nReading stacks of images ....')
    progress = pb.AnimatedProgressBar(end=n_img, width=50)
    for i in range( n_img ):
        stack_even.append( io.readImage( files_even[i] ).astype( myfloat ) )
        stack_odd.append( io.readImage( files_odd[i] ).astype( myfloat ) )
        progress + 1
        progress.show_progress()
    print('.... done!')

    nrows = stack_even[0].shape[0]
    ncols = stack_even[0].shape[1]

    print('\nNumber of input image pair: ', n_img)
    print('Size of each image: ', nrows,' X ', ncols )



    ##  Select resolution square for each image
    if args.resol_square is True:
        print('\nCalculation enabled in the resolution square')
        print('Cropping images ....')
        progress = pb.AnimatedProgressBar( end=n_img , width=50 )

        for i in range( n_img ):
            aux_even = stack_even[i]
            aux_odd = stack_odd[i]  

            aux_even = proc.selectResolutionSquare( aux_even )
            aux_odd = proc.selectResolutionSquare( aux_odd )

            stack_even[i] = aux_even
            stack_odd[i] = aux_odd

            progress + 1
            progress.show_progress()
        print('.... done!')



    ##  Select resolution square for each image
    if args.hanning is True:
        print('\nOption hanning pre-filter activated')

        progress = pb.AnimatedProgressBar( end=n_img , width=50 )

        window = np.hanning( stack_even[i].shape[0] )
        window = np.outer( window , window )

        for i in range( n_img ):
            aux_even = stack_even[i]
            aux_odd = stack_odd[i]  

            aux_even *= window
            aux_odd *= window

            stack_even[i] = aux_even
            stack_odd[i] = aux_odd   

            progress + 1
            progress.show_progress()



    ##  Do analysis
    print('\nAnalysis with ring thickness: ', args.width_ring)      
    
    if args.analysis == 'frc':
        prefix = sb.get_prefix( files_even , files_odd )
        
        pool = mproc.Pool()
        for i in range( n_img ):
            #pool.apply_async( analysis , ( stack_even[i] ,  stack_odd[i] ,
            #                               args , pathout , prefix[i] ) )
            analysis( stack_even[i] , stack_odd[i] , args , pathout , prefix[i] ) 
        pool.close()
        pool.join()


    elif args.analysis == 'fsc':
        prefix = sb.get_prefix_stack( files_even , files_odd ) 
        
        stack_even = np.array( stack_even )
        stack_odd = np.array( stack_odd )

        analysis( stack_even , stack_odd , args , pathout , prefix )



    ##  End print
    if args.analysis == 'frc':
        print('\n')
        print('#################################################################')
        print('############  FOURIER RING CORRELATION ANALYSIS END  ############')
        print('#################################################################')
        print('\n')

    else:
        print('\n')
        print('##################################################################')
        print('############  FOURIER SHELL CORRELATION ANALYSIS END  ############')
        print('##################################################################')
        print('\n') 
def main():
    print('\nADD 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, '\n')

        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
        if args.noise == 'gaussian':
            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)

        elif args.noise == 'poisson':
            nimg = 1

        else:
            sys.exit('\nERROR: Noise type "' + args.noise +
                     '" is not an option available with this routine!\n')

        ##  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'
                write_output_image(pathout,
                                   filein,
                                   image_noisy,
                                   label,
                                   sigma=sigma_list[im])

            elif args.noise == 'poisson':
                image_noisy = add_poisson_noise(imagein)
                label = 'poiss'
                write_output_image(pathout, filein, image_noisy, label)

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

    ##  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)
            if sigma == 0:
                sigma = 1.0

            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)

            ##  Add noise ##  Loop on each gaussian sigma
            if args.noise == 'gaussian':
                for im in range(nimg):
                    ##  Loop on each gaussian sigma
                    image_noisy = add_gaussian_noise(imagein, sigma_arr[im])
                    label = 'gauss'
                    write_output_file(pathout,
                                      files[i],
                                      image_noisy,
                                      label,
                                      sigma=sigma_arr[im])

            elif args.noise == 'poisson':
                image_noisy = add_poisson_noise(imagein)
                label = 'poiss'
                write_output_file(pathout, files[i], image_noisy, label)

    print('\n\n')