def save_sinogram(pathout, filein, angles, args, sino):
    nang = len(angles)

    if args.fileout is None or args.filein is None:
        filename = filein
        extension = filename[len(filename) - 4:]
        filename = filename[:len(filename) - 4]

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

        filename += '_ang' + str_nang

        if args.dpc is True:
            filename += '_dpc'

        if args.full_output is True:
            if args.geometry == '0':
                filename += '_polar'
            elif args.geometry == '1':
                filename += '_pseudo'
            else:
                filename += '_text'
            filename += '_' + args.kernel + '_' + args.kernel_interp
            oversampl = int(np.round(args.zero_pad * 1000))
            filename += '_oversampl' + str(oversampl)
        filename += '_sino' + extension

    else:
        filename = args.fileout

    filename = pathout + filename

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

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

        print('\nWriting list of projection angles:\n', listang)
        fd = open(listang, 'w')
        for i in range(len(angles)):
            fd.write('%.8f\n' % angles[i])
        fd.close()
def save_sinogram(pathout, filein, angles, args, sino):
    nang = len(angles)

    if args.fileout is None or args.filein is None:
        filename = filein
        extension = filename[len(filename) - 4:]
        filename = filename[:len(filename) - 4]

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

        filename += "_ang" + str_nang

        if args.dpc is True:
            filename += "_dpc"

        if args.full_output is True:
            if args.geometry == "0":
                filename += "_polar"
            else:
                filename += "_text"
            filename += "_" + args.kernel + "_" + args.kernel_interp
            oversampl = int(np.round(args.zero_pad * 1000))
            filename += "_oversampl" + str(oversampl)
        filename += "_sino" + extension

    else:
        filename = args.fileout

    filename = pathout + filename

    print("\nWriting sinogram in:\n", filename)
    io.writeImage(filename, sino)

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

        print("\nWriting list of projection angles:\n", listang)
        fd = open(listang, "w")
        for i in range(len(angles)):
            fd.write("%.8f\n" % angles[i])
        fd.close()
def write_output_file(pathout, filein, image_blur, sigma):
    ext = filein[len(filein) - 4:]
    fileout = filein[:len(filein) - 4] + '_blur'

    if sigma < 10:
        fileout += '00' + str(int(sigma))
    elif sigma < 100:
        fileout += '0' + str(int(sigma))
    else:
        fileout += str(int(sigma_arr[im]))

    fileout = pathout + fileout + ext
    io.writeImage(fileout, image_blur)
    print('\nOutput image written in:\n', fileout, '\n')
Пример #4
0
def function1( array2D , n_slice , path ):
    fft_array = np.fft.fft2( array2D )
         
    if n_slice < 10:
        string = '000' + str( n_slice )
    elif n_slice < 100:
        string = '00' + str( n_slice )
    elif n_slice < 1000:
        string = '0' + str( n_slice )
    else:
        string = str( n_slice )

    io.writeImage( path + string + '_real.DMP' , np.real( fft_array ) )
    io.writeImage( path + string + '_imag.DMP' , np.imag( fft_array ) )  
def save_reco(pathout, filein, args, param, reco):
    if args.reco is not None:
        filename = pathout + args.reco

    else:
        filename = filein
        extension = filename[len(filename) - 4:]
        filename = filename[:len(filename) - 4]
        filename += param.root
        filename += extension
        filename = pathout + filename

    io.writeImage(filename, reco)

    print('\nReconstruction saved in:\n', filename)
Пример #6
0
def saveReco( reco , pathin , pathout , args ):
    ##  Get output directory
    if os.path.exists( pathout ) is False:
        print('\nOutput directory ', pathout,' does not exist  --->  created!')
        os.makedirs( pathout )

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


    ##  Save output file
    filename = args.sino
    filename = filename[:len(filename)-4]
    filename += '_grid_rec.DMP'
    filename = pathout + filename
    io.writeImage( filename , reco )
def write_output_image(pathout, filein, image_noisy, label, sigma=None):
    ext = filein[len(filein) - 4:]
    fileout = filein[:len(filein) - 4] + '_noise_' + label

    if label == 'gaussian':
        if sigma < 1:
            fileout += '000' + str(int(sigma * 10))
        elif sigma < 10:
            fileout += '00' + str(int(sigma * 10)) + '0'
        elif sigma < 100:
            fileout += '0' + str(int(sigma * 10)) + '0'
        else:
            fileout += str(int(sigma * 10)) + '0'

    fileout += ext
    fileout = pathout + fileout

    io.writeImage(fileout, image_noisy)
    print('\nOutput image written in:\n', fileout)
Пример #8
0
def saveReco( reco , pathin , args ):
    ##  Get output directory
    if args.pathout is None:
        pathout = pathin
    else:
        pathout = args.pathout

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

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


    ##  Save output file
    filename = args.sino
    filename = filename[:len(filename)-4]
    filename += '_est_rec.DMP'
    filename = pathout + filename
    io.writeImage( filename , reco )
def reconstr_filter_custom( sino , angles , ctr , filt_custom , picked , 
                            debug , train_path , filein , ind ):
    ##  Prepare filter
    n         = len( filt_custom )
    nh        = np.int( 0.5 * n )
    filt      = np.zeros( len( filt_custom ) , dtype=myfloat )
    filt[::2] = filt_custom[:nh]
      
    ##  Reconstruction
    reco = utils.fbp( sino , angles , [ctr,0.0] , filt )
    
    ##  Debugging save high- and low-quality reconstructions
    if debug is True:
        filedbg = filein
        ext     = filedbg[len(filedbg)-4:]
        filedbg += '_lq0' + str( ind ) + ext
        io.writeImage( train_path + filedbg , reco )    
    
    ##  Pick up only selected pixels
    reco = reco[ picked ]  
    
    return reco
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 )
def save_reconstruction(pathout, filein, args, reco):
    if args.fileout is None:
        filename = filein
        extension = filename[len(filename) - 4:]
        filename = filename[:len(filename) - 4]

        if args.full_output is True:
            filename += '_' + args.kernel + '_' + args.kernel_interp
            oversampl = int(np.round(args.zero_pad * 1000))
            filename += '_oversampl' + str(oversampl)

        if args.dbp is True:
            filename += '_dbp'

        filename += '_reco' + extension

    else:
        filename = args.fileout

    filename = pathout + filename

    print('\nWriting reconstruction in:\n', filename)
    io.writeImage(filename, reco)
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 )
Пример #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 write_output_file(array, mode, args):
    ##  Get path
    path = args.path
    if path[len(path) - 1] != '/':
        path += '/'

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

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

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

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

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

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

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

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

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

        filename += string + str_deg + args.file_format

        io.writeImage(filename, array)
        print('\nWriting sinogram in:\n', filename)
def plug_and_play(x, b, tp, param):
    ##  Parameters
    n = param.npix_op
    nz = param.nz
    lambd1 = param.lambd1
    lambd2 = param.lambd2
    mu = param.mu
    n2 = param.n_iter_pcg
    it = 0
    err = 1e20
    info = []

    ##  Set stopping criterion
    if param.eps is None:
        eps = 1e-10
    else:
        eps = param.eps

    if param.n_iter is None:
        n1 = 200
    else:
        n1 = param.n_iter

    ##  Reconstruction indices
    if param.edge_padding != 0.0:
        i1 = param.index_start
        i2 = param.index_end
    else:
        i1 = 0
        i2 = n

    u = np.zeros((nz, n, n), dtype=myfloat)

    ##  Initialize plot
    if param.plot is True:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        if nz == 1:
            Ln = ax.imshow(x[0, i2:i1:-1, i1:i2],
                           animated=True,
                           cmap=cm.Greys_r)
        else:
            nzz = np.int(nz * 0.5)
            Ln = ax.imshow(x[nzz, i2:i1:-1, i1:i2],
                           animated=True,
                           cmap=cm.Greys_r)
        plt.ion()

    ##  Start main loop
    while it < n1 and err > eps:
        print('\nADMM-PP --- iteraz. n.: ', it)

        #  --- step 0
        if it == 0:
            #u = np.zeros( ( nz , n , n ) , dtype=myfloat )
            alpha = u.copy()
            x_old = x.copy()

        ##  --- step 1
        x_old[:] = x.copy()

        if param.num_cores == -1:
            pool = mproc.Pool()
        else:
            pool = mproc.Pool(param.num_cores)
        results = [ pool.apply_async( cg.cg_plug_and_play , args=( x[i,:,:] , b[i,:,:] , tp , n2 ,
                                                                   ( u - alpha )[i,:,:] , lambd1 , mu , i , ) ) \
                                      for i in range( nz ) ]
        x[:] = np.array([res.get() for res in results])
        pool.close()
        pool.join()

        if param.mask is True:
            for i in range(nz):
                x[i, param.mask[i] == 0.0] = 0.0

        elif param.pc >= 0.0:
            if param.pc >= 0.0:
                if param.pc == 1.0:
                    x[:, i1:i2,
                      i1:i2] = utils.phys_constr(x[:, i1:i2, i1:i2], 0.0)
                    x[:, i1:i2, i1:i2] = utils.resol_circle_constr(x[:, i1:i2,
                                                                     i1:i2])
                if param.pc == 2.0:
                    x[:, i1:i2, i1:i2] = utils.resol_circle_constr(x[:, i1:i2,
                                                                     i1:i2])
                else:
                    x[:, i1:i2,
                      i1:i2] = utils.phys_constr(x[:, i1:i2, i1:i2], param.pc)

        ##  --- step 2
        if nz > 1:
            if param.reg == 'pp-breg':
                u[:, i1:i2, i1:i2] = den.tv_breg(
                    x[:, i1:i2, i1:i2] + alpha[:, i1:i2, i1:i2], lambd2 / mu)
            elif param.reg == 'pp-chamb':
                u[:, i1:i2, i1:i2] = den.tv_chamb(
                    x[:, i1:i2, i1:i2] + alpha[:, i1:i2, i1:i2], lambd2 / mu)
            elif param.reg == 'pp-nlmeans':
                u[:, i1:i2, i1:i2] = den.nl_means(
                    x[:, i1:i2, i1:i2] + alpha[:, i1:i2, i1:i2], lambd2 / mu)
            elif param.reg == 'pp-tgv':
                x_aux = x + alpha
                param1 = lambd2 / mu
                param2 = beta = lambd2 / mu
                if param.num_cores == -1:
                    pool = mproc.Pool()
                else:
                    pool = mproc.Pool(param.num_cores)
                results = [ pool.apply_async( plug_and_play_tgv_fast , args=( x_aux[i,:,:] , param1 , param2 ) ) \
                                      for i in range( nz ) ]
                x[:] = np.array([res.get() for res in results])
                pool.close()
                pool.join()
            elif param.reg == 'pp-nltv':
                x_aux = x + alpha
                if param.num_cores == -1:
                    pool = mproc.Pool()
                else:
                    pool = mproc.Pool(param.num_cores)
                results = [ pool.apply_async( plug_and_play_nltv , args=( x_aux[i,:,:] , lambd2 , mu ) ) \
                                      for i in range( nz ) ]
                x[:] = np.array([res.get() for res in results])
                pool.close()
                pool.join()

        elif nz == 1:
            if param.reg == 'pp-breg':
                u[0, i1:i2, i1:i2] = den.tv_breg((x + alpha)[0, i1:i2, i1:i2],
                                                 lambd2 / mu)
            elif param.reg == 'pp-chamb':
                u[0, i1:i2, i1:i2] = den.tv_chamb((x + alpha)[0, i1:i2, i1:i2],
                                                  lambd2 / mu)
            elif param.reg == 'pp-nlmeans':
                u[0, i1:i2, i1:i2] = den.nl_means((x + alpha)[0, i1:i2, i1:i2],
                                                  h=lambd2 / mu)
            elif param.reg == 'pp-tgv':
                u[0, i1:i2, i1:i2] = den.tgv_fast((x + alpha)[0, i1:i2, i1:i2],
                                                  alpha=lambd2 / mu,
                                                  beta=lambd2 / mu,
                                                  niter=5)
            elif param.reg == 'pp-nltv':
                u[0, i1:i2, i1:i2] = den.nltv_sb((x + alpha)[0, i1:i2, i1:i2],
                                                 lambd=1.0,
                                                 ps=5,
                                                 ws=11,
                                                 h=lambd2 / mu,
                                                 nn=10,
                                                 icn=1,
                                                 mu=1.0,
                                                 niter1=4,
                                                 niter2=2)

        ##  --- step 3
        r = x - u
        diff = x - x_old
        alpha += r

        ##  --- step 4
        diff = np.linalg.norm(x[0, :, :] - x_old[0, :, :])
        err = np.linalg.norm(r)
        tmp = np.sqrt(cg.G(x[0, :, :])[0]**2 + cg.G(x[0, :, :])[1]**2)
        obj_0 = np.linalg.norm(tmp.reshape(-1), 0)
        obj_1 = np.linalg.norm(tp.A(x[0, :, :]) - b[0, :, :])**2
        obj_2 = np.linalg.norm(x[0, :, :])
        obj_3 = np.linalg.norm(tmp, 1)
        obj = 0.5 * obj_1 + 0.5 * lambd1 * obj_2 + lambd2 * obj_3

        if param.checkit is True:
            if param.projector == 'grid-pswf' or param.projector == 'grid-kb':
                x_aux = x[0, i1:i2, i1:i2].copy()
            elif param.projector == 'radon':
                x_aux = x[0, i2:i1:-1, i2:i1:-1].copy()
            elif param.projector == 'bspline':
                x_aux = bfun.convert_from_bspline_to_pixel_basis(
                    x[0, i2:i1:-1, i2:i1:-1], 3)
            if it < 10:
                niter = '00' + str(it)
            elif it < 100:
                niter = '0' + str(it)
            else:
                niter = str(it)
            io.writeImage(param.path_rmse + 'reco_iter' + niter + '.DMP',
                          x_aux)

        info.append([err, diff, obj])

        print('Multiplier update:   %.4e' % err)
        print('Relative difference: %.4e' % diff)
        print('Fidelity term: %.4e' % obj_1, '   Second term: %.4e' % obj_2,
              '   TV term: %.4e' % obj_3, '   || G(x) ||_{0}: %.4e' % obj_0)
        print('Function score:      %.4e' % obj)

        ##  Plot intermediate reconstruction as check
        if param.plot is True:
            if nz == 1:
                ax.imshow(x[0, i2:i1:-1, i1:i2],
                          animated=True,
                          cmap=cm.Greys_r)
            else:
                nzz = np.int(nz * 0.5)
                ax.imshow(x[nzz, i2:i1:-1, i1:i2],
                          animated=True,
                          cmap=cm.Greys_r)
            plt.draw()
            plt.pause(1)

        it += 1

    if param.plot is True:
        py.ioff()

    return x, info
def lasso_tv(x, b, tp, param):
    ##  Parameters
    n = param.npix_op
    nz = param.nz
    lambd1 = param.lambd1
    lambd2 = param.lambd2
    mu = param.mu
    n2 = param.n_iter_pcg
    it = 0
    err = 1e20
    info = []

    ##  Set stopping criterion
    if param.eps is None:
        eps = 1e-10
    else:
        eps = param.eps

    if param.n_iter is None:
        n1 = 200
    else:
        n1 = param.n_iter

    ##  Reconstruction indices
    if param.edge_padding != 0.0:
        i1 = param.index_start
        i2 = param.index_end
    else:
        i1 = 0
        i2 = n

    ##  Initialize plot
    if param.plot is True:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        if nz == 1:
            Ln = ax.imshow(x[0, i2:i1:-1, i1:i2],
                           animated=True,
                           cmap=cm.Greys_r)
        else:
            nzz = np.int(nz * 0.5)
            Ln = ax.imshow(x[nzz, i2:i1:-1, i1:i2],
                           animated=True,
                           cmap=cm.Greys_r)
        plt.ion()

    ##  Start main loop
    while it < n1 and err > eps:
        print('\nADMM Lasso TV --- iteraz. n.: ', it)

        #  --- step 0
        if it == 0:
            u = np.zeros((nz, 2, n, n), dtype=myfloat)
            alpha = u.copy()
            x_old = x.copy()

        ##  --- step 1
        x_old[:] = x.copy()

        if param.num_cores == -1:
            pool = mproc.Pool()
        else:
            pool = mproc.Pool(param.num_cores)
        results = [ pool.apply_async( cg.cg_lasso_tv , args=( x[i,:,:] , b[i,:,:] , tp , n2 ,
                                                              mu * u[i,:,:] - alpha[i,:,:] ,
                                                              lambd1 , mu , i , ) ) \
                                      for i in range( nz ) ]
        x[:] = np.array([res.get() for res in results])
        pool.close()
        pool.join()

        if param.mask is not None:
            for i in range(nz):
                x[i, i1:i2, i1:i2] = utils.supp_constr(x[i, i1:i2, i1:i2],
                                                       param.mask)

        if param.mask_add is not None:
            for i in range(nz):
                aux = x[i, i1:i2, i1:i2].copy()
                for j in range(param.mask_add_n):
                    aux[:] = utils.mask_constr(aux, param.mask_add[j])
                x[i, i1:i2, i1:i2] = aux

        if param.pc >= 0.0:
            if param.pc >= 0.0:
                if param.pc == 1.0:
                    x[:, i1:i2,
                      i1:i2] = utils.phys_constr(x[:, i1:i2, i1:i2], 0.0)
                    x[:, i1:i2, i1:i2] = utils.resol_circle_constr(x[:, i1:i2,
                                                                     i1:i2])
                if param.pc == 2.0:
                    x[:, i1:i2, i1:i2] = utils.resol_circle_constr(x[:, i1:i2,
                                                                     i1:i2])
                else:
                    x[:, i1:i2,
                      i1:i2] = utils.phys_constr(x[:, i1:i2, i1:i2], param.pc)

        ##  --- step 2
        if param.num_cores == -1:
            pool = mproc.Pool()
        else:
            pool = mproc.Pool(param.num_cores)
        results = [ pool.apply_async( hard_thres_multi , args=( x[i,:,:] , alpha[i,:,:,:] , lambd2 , mu ) ) \
                                      for i in range( nz ) ]
        u[:] = np.array([res.get() for res in results])
        pool.close()
        pool.join()

        ##  --- step 3
        r = u.copy()
        if param.num_cores == -1:
            pool = mproc.Pool()
        else:
            pool = mproc.Pool(param.num_cores)
        results = [ pool.apply_async( update_lasso_tv , args=( x[i,:,:] , u[i,:,:,:] ) ) \
                                      for i in range( nz ) ]
        r[:] = np.array([res.get() for res in results])
        pool.close()
        pool.join()

        diff = x - x_old
        alpha += r

        ##  --- step 4
        diff = np.linalg.norm(x[0, :, :] - x_old[0, :, :])
        err = np.linalg.norm(r)
        tmp = np.sqrt(cg.G(x[0, :, :])[0]**2 + cg.G(x[0, :, :])[1]**2)
        obj_0 = np.linalg.norm(tmp.reshape(-1), 0)
        obj_1 = np.linalg.norm(tp.A(x[0, :, :]) - b[0, :, :])**2
        obj_2 = np.linalg.norm(x[0, :, :])
        obj_3 = np.linalg.norm(tmp, 1)
        obj = 0.5 * obj_1 + 0.5 * lambd1 * obj_2 + lambd2 * obj_3

        if param.checkit is True:
            if param.projector == 'grid-pswf' or param.projector == 'grid-kb':
                x_aux = x[0, i1:i2, i1:i2].copy()
            elif param.projector == 'radon':
                x_aux = x[0, i2:i1:-1, i2:i1:-1].copy()
            elif param.projector == 'bspline':
                x_aux = bfun.convert_from_bspline_to_pixel_basis(
                    x[0, i2:i1:-1, i2:i1:-1], 3)
            if it < 10:
                niter = '00' + str(it)
            elif it < 100:
                niter = '0' + str(it)
            else:
                niter = str(it)
            io.writeImage(param.path_rmse + 'reco_iter' + niter + '.DMP',
                          x_aux)

        info.append([err, diff, obj])

        print('Multiplier update:   %.4e' % err)
        print('Relative difference: %.4e' % diff)
        print('Fidelity term: %.4e' % obj_1, '   Second term: %.4e' % obj_2,
              '   TV term: %.4e' % obj_3, '   || G(x) ||_{0}: %.4e' % obj_0)
        print('Function score:      %.4e' % obj)

        ##  Plot intermediate reconstruction as check
        if param.plot is True:
            if nz == 1:
                ax.imshow(x[0, i2:i1:-1, i1:i2],
                          animated=True,
                          cmap=cm.Greys_r)
            else:
                nzz = np.int(nz * 0.5)
                ax.imshow(x[nzz, i2:i1:-1, i1:i2],
                          animated=True,
                          cmap=cm.Greys_r)
            plt.draw()
            plt.pause(1)

        it += 1

    if param.plot is True:
        py.ioff()

    return x, info
Пример #17
0
def main():
    print('\n')
    print('#########################################################')
    print('#########################################################')
    print('###                                                   ###')
    print('###  CREATE SHEPP-LOGAN AND ITS ANALYTICAL SINOGRAM   ###')        
    print('###                                                   ###')     
    print('#########################################################')
    print('#########################################################') 
    print('\n')


    
    ##  Get arguments
    args = getArgs()


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

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

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

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


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

    

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

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

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

    filename += common + args.file_format

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


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

    

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


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


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

        if nang < 10:
            filename += '000' + str( nang ) + '_rt_anal_sino' + args.file_format
        elif nang < 100:
            filename += '00' + str( nang ) + '_rt_anal_sino' + args.file_format
        elif nang < 1000:
            filename += '0' + str( nang ) + '_rt_anal_sino' + args.file_format
        else:
            filename += str( nang ) + '_rt_anal_sino' + args.file_format  
        
        io.writeImage( filename , sinogram )
   
        print('\nWriting sinogram in:\n', filename)      
    
    
    print('\n\n')
Пример #18
0
def sps(x, b, tp, param):
    ##  Get number pixels, views, ctr, stopping criterion
    nz, m, n = b.shape
    eps = param.eps
    n_iter = param.n_iter
    b = b.astype(myfloat)

    ##  Regularization parameters
    beta = param.reg_cost

    if param.reg == 'huber':
        delta = param.huber_cost

    ##  Pre-compute weights
    b_max = np.max(b)
    b_den = np.sum(b**2)
    w = np.exp(-b / b_max).astype(myfloat)

    ##  Pre-compute deninator:
    ##  d = ( y * gamma )^{T} * A
    aux = tp.A(np.ones((n, n), dtype=myfloat))
    aux = w * np.kron(np.ones((nz, 1, 1), dtype=myfloat), aux)

    if param.num_cores == -1:
        pool = mproc.Pool()
    else:
        pool = mproc.Pool(param.num_cores)
    results = [ pool.apply_async( backward , args=( tp , aux[i,:,:] ) ) \
                for i in range( nz ) ]
    den = np.array([res.get() for res in results])
    pool.close()
    pool.join()

    ##  Initialize useful arrays
    b_diff = b.copy()
    num = den.copy()
    R_num = np.zeros((nz, n, n), dtype=myfloat)
    R_den = np.zeros((nz, n, n), dtype=myfloat)
    g = np.zeros((nz, n, n), dtype=myfloat)
    err_list = []

    ##  Reconstruction indices
    if param.edge_padding != 0.0:
        i1 = param.index_start
        i2 = param.index_end
    else:
        i1 = 0
        i2 = n

    ##  Initialize plot
    if nz == 1:
        nzz = 0
    else:
        nzz = np.int(nz * 0.5)

    if param.plot is True:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        Ln = ax.imshow(x[nzz, i2:i1:-1, i1:i2], animated=True, cmap=cm.Greys_r)
        plt.ion()

    ##  Start reconstruction loop
    it = 0
    err = 1e20
    b_aux = b.copy()

    while it < n_iter and err > eps:
        ##  Compute forward projection of new iterate
        if param.num_cores == -1:
            pool = mproc.Pool()
        else:
            pool = mproc.Pool(param.num_cores)
        results = [ pool.apply_async( forward , args=( tp , x[i,:,:] ) ) \
                    for i in range( nz ) ]
        b_aux[:] = np.array([res.get() for res in results])
        pool.close()
        pool.join()

        b_diff[:] = b_aux - b

        ##  Compute numerator
        b_diff *= w

        if param.num_cores == -1:
            pool = mproc.Pool()
        else:
            pool = mproc.Pool(param.num_cores)
        results = [ pool.apply_async( backward , args=( tp , b_diff[i,:,:] ) ) \
                    for i in range( nz ) ]
        num[:] = np.array([res.get() for res in results])
        pool.close()
        pool.join()

        ##  Regularization
        gamma = 0
        if param.reg == 'huber':
            if param.num_cores == -1:
                pool = mproc.Pool()
            else:
                pool = mproc.Pool(param.num_cores)
            results = [ pool.apply_async( sobel , args=( x[i,:,:] , gamma ) ) \
                        for i in range( nz ) ]
            g[:] = np.array([res.get() for res in results])
            pool.close()
            pool.join()

            if param.num_cores == -1:
                pool = mproc.Pool()
            else:
                pool = mproc.Pool(param.num_cores)
            results = [ pool.apply_async( reg.huber_num , args=( g[i,:,:] , delta ) ) \
                        for i in range( nz ) ]
            R_num[:] = np.array([res.get() for res in results])
            pool.close()
            pool.join()

            if param.num_cores == -1:
                pool = mproc.Pool()
            else:
                pool = mproc.Pool(param.num_cores)
            results = [ pool.apply_async( reg.huber_den , args=( g[i,:,:] , delta ) ) \
                        for i in range( nz ) ]
            R_den[:] = np.array([res.get() for res in results])
            pool.close()
            pool.join()

        elif param.reg == 'tikhonov':
            if param.num_cores == -1:
                pool = mproc.Pool()
            else:
                pool = mproc.Pool(param.num_cores)
            results = [ pool.apply_async( reg.tikhonov_num , args=( x[i,:,:] , gamma ) ) \
                        for i in range( nz ) ]
            R_num[:] = np.array([res.get() for res in results])
            pool.close()
            pool.join()

            if param.num_cores == -1:
                pool = mproc.Pool()
            else:
                pool = mproc.Pool(param.num_cores)
            results = [ pool.apply_async( reg.tikhonov_den , args=( x[i,:,:] , gamma ) ) \
                        for i in range( nz ) ]
            R_den[:] = np.array([res.get() for res in results])
            pool.close()
            pool.join()

        elif param.reg == 'haar':
            if param.num_cores == -1:
                pool = mproc.Pool()
            else:
                pool = mproc.Pool(param.num_cores)
            results = [ pool.apply_async( reg.haar_num , args=( x[i,:,:] , gamma ) ) \
                        for i in range( nz ) ]
            R_num[:] = np.array([res.get() for res in results])
            pool.close()
            pool.join()

            if param.num_cores == -1:
                pool = mproc.Pool()
            else:
                pool = mproc.Pool(param.num_cores)
            results = [ pool.apply_async( reg.haar_den , args=( x[i,:,:] , gamma ) ) \
                        for i in range( nz ) ]
            R_den[:] = np.array([res.get() for res in results])
            pool.close()
            pool.join()

        ##  Update reconstruction
        x_old = x.copy()
        x[:] -= (num + beta * R_num) / (den + beta * R_den + np.spacing(1))

        ##  Enforce positivity
        if param.edge_padding is False:
            x[:] = np.clip(x, 0, np.max(x))

        ##  Compute step improvement
        if param.reg == 'huber':
            gc = g[0, :, :].copy()
            R = gc.copy()
            R[gc <= delta] = 0.5 * gc[gc <= delta]**2
            R[gc > delta] = delta * gc[gc > delta] - 0.5 * delta**2
            R = np.sum(R)
        elif param.reg == 'tikhonov':
            R = np.linalg.norm(x[0, :, :])**2
        else:
            R = 0

        err = np.sum((b_diff[nzz, :, :])**2) / b_den
        err1 = np.linalg.norm(x[nzz, :, :] - x_old[nzz, :, :])
        err2 = 0.5 * np.linalg.norm(tp.A(x[nzz, :, :]) -
                                    b[nzz, :, :]) + beta * R
        err_list.append([err1, err2])
        it += 1

        print('\nSPS-iteration: ', it, '   error: ', err)

        ##  Plot intermediate reconstruction as check
        if param.plot is True:
            ax.imshow(x[nzz, i2:i1:-1, i1:i2], animated=True, cmap=cm.Greys_r)
            plt.draw()
            plt.pause(1)

        ##  Write iterate for further analysis of the algorithm
        if param.checkit is True:
            if param.projector == 'grid-pswf' or param.projector == 'grid-kb':
                x_aux = x[0, i1:i2, i1:i2].copy()
            elif param.projector == 'radon':
                x_aux = x[0, i2:i1:-1, i2:i1:-1].copy()
            elif param.projector == 'bspline':
                x_aux = bfun.convert_from_bspline_to_pixel_basis(
                    x[0, i2:i1:-1, i2:i1:-1], 3)
            if it < 10:
                niter = '00' + str(it)
            elif it < 100:
                niter = '0' + str(it)
            else:
                niter = str(it)
            io.writeImage(param.path_rmse + 'reco_iter' + niter + '.DMP',
                          x_aux)

    ##  Conversion for bspline reconstruction and rotate
    if param.projector == 'bspline':
        for i in range(nz):
            x[i, :, :] = bfun.convert_from_bspline_to_pixel_basis(
                x[i, :, :], 3)
        x[:, :, :] = x[:, ::-1, ::-1]

    info = np.array(err_list)

    if param.plot is True:
        py.ioff()

    return x, info
Пример #19
0
def em(x, b, tp, param):
    ##  Get number pixels, views, ctr, stopping criterion
    nz, m, n = b.shape
    eps = param.eps
    n_iter = param.n_iter
    b = b.astype(myfloat)

    ##  Pre-compute constant part of the denominator
    ##  ( A^{T} 1 )^{T}
    ones = np.ones((m, n), dtype=myfloat)
    d_cost = tp.At(ones)
    d_cost[d_cost == 0] = d_cost[d_cost == 0] + 1e-10

    ##  Initialize useful arrays
    b_new = b.copy()
    err_list = []

    ##  Reconstruction indices
    if param.edge_padding != 0.0:
        i1 = param.index_start
        i2 = param.index_end
    else:
        i1 = 0
        i2 = n

    ##  Initialize plot
    if nz == 1:
        nzz = 0
    else:
        nzz = np.int(nz * 0.5)

    if param.plot is True:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        Ln = ax.imshow(x[nzz, i2:i1:-1, i1:i2], animated=True, cmap=cm.Greys_r)
        plt.ion()

    ##  Start reconstruction loop
    it = 0
    err = 1e20
    x_aux = x.copy()

    while it < n_iter and err > eps:
        ##  Compute forward projection of new iterate
        x_old = x.copy()

        if param.num_cores == -1:
            pool = mproc.Pool()
        else:
            pool = mproc.Pool(param.num_cores)
        results = [ pool.apply_async( forward , args=( tp , x[i,:,:] ) ) \
                    for i in range( nz ) ]
        b_new[:] = np.array([res.get() for res in results])
        pool.close()
        pool.join()

        b_new[b_new == 0] = b_new[b_new == 0] + np.spacing(1)
        b_aux = b / b_new

        if param.num_cores == -1:
            pool = mproc.Pool()
        else:
            pool = mproc.Pool(param.num_cores)
        results = [ pool.apply_async( backward , args=( tp , b_aux[i,:,:] ) ) \
                    for i in range( nz ) ]
        x_aux[:] = np.array([res.get() for res in results])
        pool.close()
        pool.join()

        x[:] *= (1.0 / d_cost) * x_aux

        ##  Compute step improvement
        err = np.sum(
            (b_new[nzz, :, :] - b[nzz, :, :])**2) / np.sum(b[nzz, :, :]**2)
        err1 = np.linalg.norm(x[nzz, :, :] - x_old[nzz, :, :])
        err2 = 0.5 * np.linalg.norm(tp.A(x[nzz, :, :]) - b[nzz, :, :])
        err_list.append([err1, err2])
        it += 1

        print('\nEM-iteration: ', it, '   error: ', err)

        ##  Plot intermediate reconstruction as check
        if param.plot is True:
            ax.imshow(x[nzz, i2:i1:-1, i1:i2], animated=True, cmap=cm.Greys_r)
            py.draw()
            plt.pause(1)

        ##  Write iterate for further analysis of the algorithm
        if param.checkit is True:
            if param.projector == 'grid-pswf' or param.projector == 'grid-kb' or param.projector == 'pix-driv':
                x_aux = x[nzz, i1:i2, i1:i2].copy()
            elif param.projector == 'radon':
                x_aux = x[nzz, i2:i1:-1, i2:i1:-1].copy()
            elif param.projector == 'bspline':
                x_aux = bfun.convert_from_bspline_to_pixel_basis(
                    x[nzz, i2:i1:-1, i2:i1:-1], 3)
            if it < 10:
                niter = '00' + str(it)
            elif it < 100:
                niter = '0' + str(it)
            else:
                niter = str(it)
            io.writeImage(param.path_rmse + 'reco_iter' + niter + '.DMP',
                          x_aux)

    info = np.array(err_list)

    if param.plot is True:
        py.ioff()

    return x, info
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')

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

    ##  Use anti-alising filter
    if args.anti_alias is not None:
        if args.anti_alias == 'hlsf' or args.anti_alias == 'lhsf':
            print('\nAnti-aliasing HLSF filter enabled')
            sino = lhsf.anti_alias_filt(sino)
            nang, npix = sino.shape
            print('New number of projection angles: ', nang)
            sino = sino.astype(myfloat)

        elif args.anti_alias == 'cubic':
            print('\nAnti-aliasing cubic interpolation enabled')
            sino = extrap.anti_alias_filt(sino, op='cubic')
            nang, npix = sino.shape
            print('New number of projection angles: ', nang)
            sino = sino.astype(myfloat)

        elif args.anti_alias == 'telea':
            print('\nAnti-aliasing telea inpainting enabled')
            sino = extrap.anti_alias_filt(sino, op='telea', radius=2)
            nang, npix = sino.shape
            print('New number of projection angles: ', nang)
            sino = sino.astype(myfloat)

        else:
            print('\nWarning: anti-aliasing method ', args.anti_alias,
                  ' not found!')
            print('No anti-aliasing filtering applied!\n')

        if args.plot is True:
            dis.plot(sino, 'Sinogram with double number of views')
        io.writeImage('sino.DMP', sino)

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

    ##  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')
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')
Пример #22
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')