Example #1
0
def reconstruct(proj_fn_template, layers, theta, console_out, outdir="recon"):
    """proj_fn_template: projection filename tempate
    layers: list of integers for layers to be reconstructed
    theta: sample rotation angle in radian
    """
    import tomopy
    proj = tomopy.read_tiff_stack(proj_fn_template % layers[0], layers, digit=5)
    proj = np.swapaxes(proj, 0,1)
    Y,X = proj[0].shape
    # reconstruct
    console_out.write("tomopy.reconstruct..."); console_out.flush()
    rec = tomopy.recon(
        proj,
        theta=theta, center=X/2.,
        algorithm='gridrec', emission=False,
        ncore = 1,
    )
    console_out.write("done\n"); console_out.flush()
    # output
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    console_out.write("tomopy.write_tiff_stack..."); console_out.flush()
    tomopy.write_tiff_stack(
        rec, fname=os.path.join(outdir, 'recon'), axis=0, overwrite=True)
    console_out.write("done\n"); console_out.flush()
    return
Example #2
0
def project(ct_series, outdir, console_out):
    """convert ct image series to projection series"""
    if os.path.exists(outdir):
        msg = "%s existed, assume projection has already been done. skip this\n" % (
            outdir,)
        console_out.write(msg)
        return
    import tomopy
    data = []; N = len(ct_series.identifiers)
    prefix = "Read ct series"
    for i,angle in enumerate(ct_series.identifiers):
        # if i%3 != 0: continue
        data1 = ct_series.getImage(angle).getData()
        # data[data<=0] = 1.
        data1 = data1[100:-100, 100:-100]
        data.append(data1)
        console_out.write("\r%s: %2.0f%%" % (prefix, (i+1)*100./N))
        console_out.flush()
        continue
    console_out.write("\n"); console_out.flush()
    # project
    console_out.write("tomopy.normalize_bg..."); console_out.flush()
    proj = tomopy.normalize_bg(data) # , ncore=ncore)
    console_out.write("done\n"); console_out.flush()
    del data
    # remove negative intensities
    proj[proj<0] = 0
    # output
    console_out.write("tomopy.write_tiff_stack..."); console_out.flush()
    tomopy.write_tiff_stack(
        proj, fname=os.path.join(outdir, 'proj'), axis=1, overwrite=False)
    console_out.write("done\n"); console_out.flush()
    return
def srxfftomo_recon(corrected_proj_tiff=None,
                    proj=None,
                    rot_center=None,
                    recon_algorithm='art',
                    recon_section=None,
                    outpath=None,
                    recon_outpath='recon',
                    samplename=None,
                    starting_angle=0,
                    last_angle=180):
    '''
    input needs to be either 
    1) corrected_proj_tiff, provided as a file path and name, 
    e.g. '/home/xf05id1/localdata/TomoCommissioning/testsample_01/testsample_01_corrected.tiff'
    it is a stack of tiff generated by srxfftomo_correction, where background and stage round out have been corrected
    2) projection numpy array, returned from srxfftomo_correction
    
    The 'proj' array assignment has priority. If it is None, proj was be read from corrected_proj_tiff 
    
    recon_section is a list of upper and lower bounds for y range, e.g. [380, 420]
    
    '''

    if proj is None:
        print('proj is not asigned, load corrected projection from:',
              corrected_proj_tiff)
        proj = tifffile.imread(corrected_proj_tiff)
    else:
        print('proj array is not None, use it as is')

    print('running reconstruction')

    if recon_section is not None:
        proj = proj[:, recon_section[0]:recon_section[1], :]

    theta = tomopy.angles(proj.shape[0], ang1=starting_angle, ang2=last_angle)
    print(proj.shape, theta.shape)
    proj = tomopy.remove_stripe_ti(proj)
    rec = tomopy.recon(proj,
                       theta,
                       center=rot_center,
                       algorithm=recon_algorithm)

    print('saving reconstruction into')
    recon_outfile = outpath + '/' + samplename + '/' + recon_outpath + '/' + samplename + '_recon'
    tomopy.write_tiff_stack(rec, fname=recon_outfile)

    return rec
Example #4
0
    def refineShift(self, orig, num_iter=1, fname="./2ms_full/", saveok=False):
        num_loop = 0
        mat = zeros(orig.shape, dtype=np.float32)
        mat[...] = orig[...]
        while num_loop < num_iter:

            recon = tomopy.recon(mat,
                                 self.thetaArray * np.pi / 180,
                                 algorithm="mlem",
                                 reg_par=np.array([1, 0.01], dtype=np.float32),
                                 num_iter=30)
            print "reconstruction for " + str(num_loop) + " is done"
            temp = self.x_rotation(recon, self.thetaArray)
            temp2 = zeros(temp.shape, dtype=float32)
            temp2[...] = wiener(temp)[...]
            #temp2[np.where(temp2<temp2.max()*0.01)]=0.1**5
            #print temp2
            mat, diff = self.xcor_data_proj_onlyx(mat, temp2)
            if saveok:
                tomopy.write_tiff_stack(mat,
                                        fname=fname + str(num_loop) + "/" +
                                        "stack_",
                                        dtype=float32,
                                        digit=3)
                #tomopy.write_tiff_stack(temp, fname=fname+str(num_loop)+"_bw/stack_",dtype=float32,digit=3)
                tomopy.write_tiff_stack(temp2,
                                        fname=fname + str(num_loop) +
                                        "_reprojection/stack_",
                                        dtype=float32,
                                        digit=3)
                tomopy.write_tiff_stack(recon,
                                        fname=fname + str(num_loop) +
                                        "_recon/stack_",
                                        dtype=float32,
                                        digit=3)
                self.diff_write_txt2(
                    diff, "./shift/shift_" + str(num_loop + 1) + ".txt")
                print diff
            num_loop += 1
Example #5
0
    for m in range(chunks):
        sino_start = start + num_sino * m
        sino_end = start + num_sino * (m + 1)

        # Read APS 32-ID raw data.
        proj, flat, dark = tomopy.read_aps_32id(fname,
                                                sino=(sino_start, sino_end))

        # Set data collection angles as equally spaced between 0-180 degrees.
        theta = tomopy.angles(proj.shape[0])

        # Remove the missing angles from data.
        proj = np.concatenate(
            (proj[0:miss_projs[0], :, :], proj[miss_projs[1] + 1:-1, :, :]),
            axis=0)
        theta = np.concatenate(
            (theta[0:miss_projs[0]], theta[miss_projs[1] + 1:-1]))

        # Flat-field correction of raw data.
        proj = tomopy.normalize(proj, flat, dark)

        # Reconstruct object using Gridrec algorithm.
        rec = tomopy.recon(proj,
                           theta,
                           center=1024,
                           algorithm='gridrec',
                           emission=False)

        # Write data as stack of TIFs.
        tomopy.write_tiff_stack(rec, fname='recon_dir/recon', start=sino_start)
Example #6
0
                                                 ind_dark,
                                                 sino=(start, end))

    # Set data collection angles as equally spaced between 0-180 degrees.
    theta = tomopy.angles(proj.shape[0])

    # Flat-field correction of raw data.
    proj = tomopy.normalize(proj, flat, dark)

    # Find rotation center.
    rot_center = tomopy.find_center(proj,
                                    theta,
                                    emission=False,
                                    init=1024,
                                    ind=0,
                                    tol=0.5)
    print("Center of rotation: ", rot_center)

    # Reconstruct object using Gridrec algorithm.
    rec = tomopy.recon(proj,
                       theta,
                       center=rot_center,
                       algorithm='gridrec',
                       emission=False)

    # Mask each reconstructed slice with a circle.
    rec = tomopy.circ_mask(rec, axis=0, ratio=0.95)

    # Write data as stack of TIFs.
    tomopy.write_tiff_stack(rec, fname='recon_dir/recon')
Example #7
0
def recon(io_paras, data_paras, rot_center=None, normalize=True, stripe_removal=10, phase_retrieval=False, 
            opt_center=False, diag_center=False, output="tiff"):
    # Input and output
    datafile = io_paras.get('datafile')
    path2white = io_paras.get('path2white', datafile)
    path2dark = io_paras.get('path2dark', path2white)
    out_dir = io_paras.get('out_dir')
    diag_cent_dir = io_paras.get('diag_cent_dir', out_dir+"/center_diagnose/")
    recon_dir = io_paras.get('recon_dir', out_dir+"/recon/")
    out_prefix = io_paras.get('out_prefix', "recon_")

    # Parameters of dataset
    NumCycles = data_paras.get('NumCycles', 1) # Number of cycles used for recon
    ProjPerCycle = data_paras.get('ProjPerCycle') # Number of projections per cycle, N_theta
    cycle_offset = data_paras.get('cycle_offset', 0) # Offset in output cycle number
    proj_start = data_paras.get('proj_start', 0) # Starting projection of reconstruction 
    proj_step = data_paras.get('proj_step')
    z_start = data_paras.get('z_start', 0)
    z_end = data_paras.get('z_end', z_start+1)
    z_step = data_paras.get('z_step')
    x_start = data_paras.get('x_start')
    x_end = data_paras.get('x_end', x_start+1)
    x_step = data_paras.get('x_step')
    white_start = data_paras.get('white_start')
    white_end = data_paras.get('white_end')
    dark_start = data_paras.get('dark_start')
    dark_end = data_paras.get('dark_end')

    rot_center_copy = rot_center

    for cycle in xrange(NumCycles):
        # Set start and end of each cycle
        projections_start = cycle * ProjPerCycle + proj_start
        projections_end = projections_start + ProjPerCycle
        slice1 = slice(projections_start, projections_end, proj_step)
        slice2 = slice(z_start, z_end, z_step)
        slice3 = slice(x_start, x_end, x_step)
        slices = (slice1, slice2, slice3)
        white_slices = (slice(white_start, white_end), slice2, slice3)
        dark_slices = (slice(dark_start, dark_end), slice2, slice3)
        print("Running cycle #%s (projs %s to %s)" 
            % (cycle, projections_start, projections_end))
        
        # Read HDF5 file.
        print("Reading datafile %s..." % datafile, end="")
        sys.stdout.flush()
        data, white, dark = reader.read_aps_2bm(datafile, slices, white_slices, dark_slices, 
                                        path2white=path2white, path2dark=path2dark)
        theta = gen_theta(data.shape[0])
        print("Done!")
        print("Data shape = %s;\nwhite shape = %s;\ndark shape = %s." 
            % (data.shape, white.shape, dark.shape))
        
        ## Normalize dataset using data_white and data_dark
        if normalize:
            print("Normalizing data ...")
            # white = white.mean(axis=0).reshape(-1, *data.shape[1:])
            # dark = dark.mean(axis=0).reshape(-1, *data.shape[1:])
            # data = (data - dark) / (white - dark)
            data = tomopy.normalize(data, white, dark, cutoff=None, ncore=_ncore, nchunk=None)[...]
    
        ## Remove stripes caused by dead pixels in the detector
        if stripe_removal:
            print("Removing stripes ...")
            data = tomopy.remove_stripe_fw(data, level=stripe_removal, wname='db5', sigma=2,
                                    pad=True, ncore=_ncore, nchunk=None)
            # data = tomopy.remove_stripe_ti(data, nblock=0, alpha=1.5, 
            #                                 ncore=None, nchunk=None)

#        # Show preprocessed projection
#        plt.figure("%s-prep" % projections_start)
#        plt.imshow(d.data[0,:,:], cmap=cm.Greys_r)
#        plt.savefig(out_dir+"/preprocess/%s-prep.jpg" 
#                    % projections_start)
#        # plt.show()
#        continue

        ## Phase retrieval
        if phase_retrieval:
            print("Retrieving phase ...")
            data = tomopy.retrieve_phase(data,
                        pixel_size=1e-4, dist=50, energy=20,
                        alpha=1e-3, pad=True, ncore=_ncore, nchunk=None)
        
        ## Determine and set the center of rotation 
        if opt_center or (rot_center == None):
            ### Using optimization method to automatically find the center
            # d.optimize_center()
            print("Optimizing center ...", end="")
            sys.stdout.flush()
            rot_center = tomopy.find_center(data, theta, ind=None, emission=True, init=None,
                                            tol=0.5, mask=True, ratio=1.)
            print("Done!")
            print("center = %s" % rot_center)
        if diag_center:
            ### Output the reconstruction results using a range of centers,
            ### and then manually find the optimal center.
            # d.diagnose_center()
            if not os.path.exists(diag_cent_dir):
                os.makedirs(diag_cent_dir)
            print("Testing centers ...", end="")
            sys.stdout.flush()
            tomopy.write_center(data, theta, dpath=diag_cent_dir, 
                                cen_range=[center_start, center_end, center_step], 
                                ind=None, emission=False, mask=False, ratio=1.)
            print("Done!")
        
        ## Flip odd frames
        if (cycle % 2):
            data[...] = data[...,::-1]
            rot_center = data.shape[-1] - rot_center_copy
        else:
            rot_center = rot_center_copy

        ## Reconstruction using FBP
        print("Running gridrec ...", end="")
        sys.stdout.flush()
        recon = tomopy.recon(data, theta, center=rot_center, emission=False, algorithm='gridrec',
                                # num_gridx=None, num_gridy=None, filter_name='shepp',
                                ncore=_ncore, nchunk=_nchunk)
        print("Done!")

        ## Collect background
        # if cycle == 0:
        #     bg = recon
        # elif cycle < 4:
        #     bg += recon
        # else:
        #     recon -= bg/4.

        # Write to stack of TIFFs.
        if not os.path.exists(recon_dir):
            os.makedirs(recon_dir)
        out_fname = recon_dir+"/"+out_prefix+"t_%d" % (cycle + cycle_offset)      
        if "hdf" in output: 
            hdf_fname = out_fname + ".hdf5"
            print("Writing reconstruction output file %s..." 
                 % hdf_fname, end="")
            sys.stdout.flush()
            tomopy.write_hdf5(recon, fname=hdf_fname, gname='exchange', overwrite=False)
            print("Done!")
        if "tif" in output:
            tiff_fname = out_fname + ".tiff"
            print("Writing reconstruction tiff files %s ..."
                    % tiff_fname, end="")
            sys.stdout.flush()
            tomopy.write_tiff_stack(recon, fname=tiff_fname, axis=0, digit=5, start=0, overwrite=False)
            print("Done!")
        if "bin" in output:
            bin_fname = out_fname + ".bin"
            print("Writing reconstruction to binary files %s..." 
                    % bin_fname, end="")
            sys.stdout.flush()
            recon.tofile(bin_fname)
Example #8
0
if __name__ == '__main__':

    # Set path to the micro-CT data to reconstruct.
    fname = 'data_dir/sample_name_prefix'

    # Select the sinogram range to reconstruct.
    start = 0
    end = 16

    # Read the APS 1-ID raw data.
    proj, flat, dark = tomopy.read_aps_1id(fname, sino=(start, end))

    # Set data collection angles as equally spaced between 0-180 degrees.
    theta  = tomopy.angles(proj.shape[0])

    # Flat-field correction of raw data.
    proj = tomopy.normalize(proj, flat, dark)

    # Find rotation center.
    rot_center = tomopy.find_center(proj, theta, emission=False, init=1024, ind=0, tol=0.5)
    print "Center of rotation: ", rot_center

    # Reconstruct object using Gridrec algorithm.
    rec = tomopy.recon(proj, theta, center=rot_center, algorithm='gridrec', emission=False)
        
    # Mask each reconstructed slice with a circle.
    rec = tomopy.circ_mask(rec, axis=0, ratio=0.95)

    # Write data as stack of TIFs.
    tomopy.write_tiff_stack(rec, fname='recon_dir/recon')
Example #9
0
# -*- coding: utf-8 -*-
"""
Created on Fri Nov  6 14:41:29 2015

@author: lbluque
"""

import tomopy
import numpy as np

proj_num = 45
input_path = '/home/lbluque/TestDataSets/PhantomSets/projections832small' + str(proj_num)
basename = 'projections832small' + str(proj_num)
filename = basename + '_0000.tif'
input_name = input_path + '/' + filename
ind = range(proj_num)
digits = 4

tomo = tomopy.read_tiff_stack(input_name, ind, digits)
tomo_padded = np.pad(tomo, ((0, 0), (0,0), (20,20)), 'constant', constant_values=0)
center = (tomo.shape[2] - 1)/2.0
theta = tomopy.angles(tomo.shape[0], 90, 270 - 180/proj_num)

rec = tomopy.recon(tomo_padded, theta, center=center, algorithm='gridrec', emission=False)

output_path = '/home/lbluque/TestRecons/PhantomRecons/' + basename + '_reverse/'
outname = output_path + basename
tomopy.write_tiff_stack(rec, fname=outname, digit=digits)
Example #10
0
#20130807_234356_OIM121R_SAXS_5x.h5'
algo = 'fbp'
num_sets = 2

tomo, flats, darks, floc = tomopy.read_als_832h5(dataset, sino=(1000, 1010, 1))
print('Data read complete')

print('Displaying  sinogram')
imgplot = plt.imshow(tomo[:, 0, :])
plt.show()

print('Generating angles')
theta = tomopy.angles(tomo.shape[0])

print('Normalization')
tomo, weight = normalize_bo(tomo, flats, darks, num_sets)

#print('Ring removal')
#tomo = tomopy.remove_stripe_fw(tomo)

print('Recon')
rec = tomopy.recon(tomo, theta, center=1328, algorithm=algo)  #1294

print('Masking')
rec = tomopy.circ_mask(rec, 0)

imgplot = plt.imshow(rec[:, 0, :])
plt.show()

tomopy.write_tiff_stack(rec, 'test.tiff')
Example #11
0
# print "  done."

# plot an image
fig, ax = plt.subplots()
im = plt.imshow(data[0], cmap='gray')  #, vmin=0.2, vmax=1.2
fig.colorbar(im)
# plot a projection
fig, ax = plt.subplots()
im = plt.imshow(proj[:, 1000, :], cmap='gray')
fig.colorbar(im)
# dump
# tomopy.write_tiff_stack(proj, fname='proj', axis=1, overwrite=True)
# reconstruction
print "* reconstructing ..."
rec = tomopy.recon(
    # proj[:, 600:601, :],
    proj[:, 1023:1024, :],
    theta=theta,
    center=rot_center[0],
    algorithm='gridrec',
    emission=False)
print "  done."
# plot
fig, ax = plt.subplots()
im = plt.imshow(rec[0], cmap='gray')
fig.colorbar(im)
pylab.show()
print proj.shape, rec.shape
# dump
tomopy.write_tiff_stack(rec, fname='recon', axis=0, overwrite=True)
Example #12
0
for dataset in datasets:
    f.write('*****************************************************************************************************\n')
    f.write(dataset + '\n\n')
    for algorithm in algorithms:
        for sino in sinos:
            for core in cores:
                start_time = time.time()
                tomo, flats, darks, floc = tomopy.read_als_832h5(dataset,
                                                                 sino=(0, sino, 1))
                end_time = time.time() - start_time
                f.write('Function: {0}, Number of sinos: {1}, Runtime (s): {2}\n'.format('read', sino, end_time))
                theta = tomopy.angles(tomo.shape[0])
                tomo = tomopy.normalize(tomo, flats, darks, ncore=core)
                end_time = time.time() - start_time - end_time 
                f.write('Function: {0}, Number of sinos: {1}, Number of cores: {2}, Runtime (s): {3}\n'.format('normalize', sino, core, end_time))
                tomo = tomopy.remove_stripe_fw(tomo, ncore=core)
                end_time = time.time() - start_time - end_time 
                f.write('Function: {0}, Number of sinos: {1}, Number of cores: {2}, Runtime (s): {3}\n'.format('stripe_fw', sino, core, end_time))
                rec = tomopy.recon(tomo, theta, center=datasets[dataset],
                                   algorithm=algorithm, emission=False,
                                   ncore=core)
                end_time = time.time() - start_time - end_time
                rec = tomopy.circ_mask(rec, 0)
                f.write('Function: {0}, Number of sinos: {1}, Number of cores: {2}, Algorithm: {3}, Runtime (s): {4}\n'.format('recon', sino, core, algorithm, end_time))
                outname = os.path.join('.', '{0}_{1}_slices_{2}_cores_{3}'.format(dataset.split('.')[0], str(algorithm), str(sino), str(core)), dataset.split('.')[0])
                tomopy.write_tiff_stack(rec, fname=outname)
                end_time = time.time() - start_time - end_time  
                f.write('Function: {0}, Number of images: {1}, Runtime (s): {2}\n\n'.format('write', rec.shape[0], end_time))
                f.flush()
f.close()
Example #13
0
#!/usr/bin/env python

import tomopy
import numpy
import time

print "Hey!"

obj = numpy.ones((512, 512, 512), dtype='float32')
ang = tomopy.angles(512)

t = time.time()
prj = tomopy.project(obj, ang)
print time.time() - t

t = time.time()
rec = tomopy.recon(prj, ang, algorithm='gridrec', num_gridx=1024, num_gridy=1024)
print time.time() - t

tomopy.write_tiff_stack(rec, overwrite=True)
Example #14
0
        start2 = timeit.default_timer()
        # # Flat-field correction of raw data.
        proj = tomopy.normalize(proj, flat, dark)
        stop2 = timeit.default_timer()
        print("end normalize", (stop2 - start2))

        start3 = timeit.default_timer()
        # # Find rotation center.
        rot_center = tomopy.find_center(proj, theta, emission=False, ind=0, init=1024, tol=0.5)
        stop3 = timeit.default_timer()
        print("end find_center", (stop3 - start3))

        #
        # # Reconstruct object using Gridrec algorithm.

        start4 = timeit.default_timer()
        rec = tomopy.recon(proj, theta, center=rot_center, algorithm='gridrec', emission=False)

        stop4 = timeit.default_timer()
        print("end recon", (stop4 - start4))

        # #print("rec is ", rec)
        # # Mask each reconstructed slice with a circle.
        # rec = tomopy.circ_mask(rec, axis=0, ratio=0.95)
        #
        # # Write data as stack of TIFs.
        start5 = timeit.default_timer()
        tomopy.write_tiff_stack(rec, fname='recon_dir/recon', start = sliceStart)
        stop5 = timeit.default_timer()
        print("end write_tiff_stack", (stop5 - start5))
# print "  done."

# plot an image
fig, ax = plt.subplots()
im = plt.imshow(data[0], cmap='gray') #, vmin=0.2, vmax=1.2
fig.colorbar(im)
# plot a projection
fig, ax = plt.subplots()
im = plt.imshow(proj[:, 1000, :], cmap='gray')
fig.colorbar(im)
# dump
# tomopy.write_tiff_stack(proj, fname='proj', axis=1, overwrite=True)
# reconstruction
print "* reconstructing ..."
rec = tomopy.recon(
    # proj[:, 600:601, :], 
    proj[:, 923:1024, :], 
    theta=theta, center=rot_center[0], 
    algorithm='gridrec', emission=False
)
print "  done."
# plot
fig, ax = plt.subplots()
im = plt.imshow(rec[0], cmap='gray')
fig.colorbar(im)
pylab.show()
print proj.shape, rec.shape
# dump
tomopy.write_tiff_stack(rec, fname='recon', axis=0, overwrite=True)

Example #16
0
prj = numpy.random( ... )

# -----------------------------




# Processing funcs --------------

# phase retrieval
t = time.time()
prj = tomopy.retrieve_phase(prj,
	alpha=1e-4)
print time.time() - t

# reconstruct
t = time.time()
rec = tomopy.recon(prj, ang,
	algorithm='gridrec',
	center=1010,
	emission=False)
print time.time() - t

# -----------------------------



# save as tiff stack
tomopy.write_tiff_stack(rec, overwrite=False)