Пример #1
0
def find_rotation_axis(h5fname, nsino):

    data_size = get_dx_dims(h5fname, 'Prefiltered_images')
    ssino = int(data_size[1] * nsino)

    # Select sinogram range to reconstruct
    sino = None

    start = ssino
    end = start + 1
    sino = (start, end)

    # Read APS 32-BM raw data
    ##proj, flat, dark, theta = dxchange.read_aps_32id(h5fname, sino=sino)

    # Flat-field correction of raw data
    ##data = tomopy.normalize(proj, flat, dark, cutoff=1.4)
    data, theta = read_aps_7bm(h5fname, sino=sino)

    # remove stripes
    #data = tomopy.remove_stripe_fw(ndata,level=5,wname='sym16',sigma=1,pad=True)

    # find rotation center
    rot_center = tomopy.find_center_vo(data)

    return rot_center
Пример #2
0
def find_rotation_axis(h5fname, nsino):
    
    data_size = get_dx_dims(h5fname, 'data')
    ssino = int(data_size[1] * nsino)

    # Select sinogram range to reconstruct
    sino = None
        
    start = ssino
    end = start + 1
    sino = (start, end)

    # Read APS 32-BM raw data
    proj, flat, dark, theta = dxchange.read_aps_32id(h5fname, sino=sino)
        
    # Flat-field correction of raw data
    data = tomopy.normalize(proj, flat, dark, cutoff=1.4)

    # remove stripes
    data = tomopy.remove_stripe_fw(data,level=5,wname='sym16',sigma=1,pad=True)

    # find rotation center
    rot_center = tomopy.find_center_vo(data)   

    return rot_center
Пример #3
0
def _find_rotation_axis(params):

    log.info("  *** calculating automatic center")
    data_size = file_io.get_dx_dims(params)
    ssino = int(data_size[1] * params.nsino)

    # Select sinogram range to reconstruct
    sino_start = ssino
    sino_end = sino_start + pow(2, int(params.binning))

    sino = (int(sino_start), int(sino_end))

    # Read APS 32-BM raw data
    proj, flat, dark, theta, params_rotation_axis_ignored = file_io.read_tomo(
        sino, params)

    # apply all preprocessing functions
    data = prep.all(proj, flat, dark, params, sino)

    # find rotation center
    log.info("  *** find_center vo")
    rot_center = tomopy.find_center_vo(data)
    log.info("  *** automatic center: %f" % rot_center)

    return rot_center * np.power(2, float(params.binning))
Пример #4
0
def find_rotation_axis(h5fname, nsino):

    data_size = get_dx_dims(h5fname, 'data')
    ssino = int(data_size[1] * nsino)

    # Select sinogram range to reconstruct
    sino = None

    start = ssino
    end = start + 1
    sino = (start, end)

    # Read APS 32-BM raw data.
    h5fname_norm = '/local/data/2019-02/Dunand/In-situ_75_3/In-situ_75_3_0099.h5'
    proj1, flat, dark, theta1 = dxchange.read_aps_32id(h5fname_norm, sino=sino)
    proj, dummy, dummy1, theta = dxchange.read_aps_32id(h5fname, sino=sino)

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

    # remove stripes
    data = tomopy.remove_stripe_fw(data,
                                   level=5,
                                   wname='sym16',
                                   sigma=1,
                                   pad=True)

    # find rotation center
    rot_center = tomopy.find_center_vo(data)

    return rot_center
Пример #5
0
def _find_rotation_axis(params):
    log.info("  *** calculating automatic center")
    data_size = file_io.get_dx_dims(params)
    ssino = int(data_size[1] * params.nsino)
    params = file_io.read_pixel_size(params)
    params = file_io.read_filter_materials(params)
    params = file_io.read_scintillator(params)
    params = file_io.read_bright_ratio(params)

    # Select sinogram range to reconstruct
    sino_start = ssino
    sino_end = sino_start + pow(2, int(params.binning)) 

    sino = (int(sino_start), int(sino_end))

    # Read APS 32-BM raw data
    proj, flat, dark, theta, params_rotation_axis_ignored = file_io.read_tomo(sino, params, True)
        
    # apply all preprocessing functions
    data = prep.all(proj, flat, dark, params, sino)

    # if flip and stitch, just use the overlapped part of the dataset
    if params.file_type == 'flip_and_stich':
        params = _find_rotation_axis_flip_stitch(data, params)
    else:        
        # find rotation center
        log.info("  *** find_center vo")
        # if we start at 0 and end at 180, remove last angle
        if np.isclose(theta[-1] - theta[0], np.pi, 1e-4):
            data = data[:-1,...]
        params.rotation_axis = tomopy.find_center_vo(data) * np.power(2, float(params.binning))
        params.rotation_axis_flip = -1
    log.info("  *** automatic center: %f" % params.rotation_axis)
    return params
Пример #6
0
 def evaluate(self):
     self.center.value = tomopy.find_center_vo(
         self.tomo.value,
         ind=self.ind.value,
         smin=self.smin.value,
         smax=self.smax.value,
         srad=self.srad.value,
         step=self.step.value,
         ratio=self.ratio.value,
         drop=self.drop.value)
Пример #7
0
def recon(
        filename,
        inputPath='./',
        outputPath=None,
        outputFilename=None,
        doOutliers1D=False,  # outlier removal in 1d (along sinogram columns)
        outlier_diff1D=750,  # difference between good data and outlier data (outlier removal)
        outlier_size1D=3,  # radius around each pixel to look for outliers (outlier removal)
        doOutliers2D=False,  # outlier removal, standard 2d on each projection
        outlier_diff2D=750,  # difference between good data and outlier data (outlier removal)
        outlier_size2D=3,  # radius around each pixel to look for outliers (outlier removal)
        doFWringremoval=True,  # Fourier-wavelet ring removal
        doTIringremoval=False,  # Titarenko ring removal
        doSFringremoval=False,  # Smoothing filter ring removal
        ringSigma=3,  # damping parameter in Fourier space (Fourier-wavelet ring removal)
        ringLevel=8,  # number of wavelet transform levels (Fourier-wavelet ring removal)
        ringWavelet='db5',  # type of wavelet filter (Fourier-wavelet ring removal)
        ringNBlock=0,  # used in Titarenko ring removal (doTIringremoval)
        ringAlpha=1.5,  # used in Titarenko ring removal (doTIringremoval)
        ringSize=5,  # used in smoothing filter ring removal (doSFringremoval)
        doPhaseRetrieval=False,  # phase retrieval
        alphaReg=0.0002,  # smaller = smoother (used for phase retrieval)
        propagation_dist=75,  # sample-to-scintillator distance (phase retrieval)
        kev=24,  # energy level (phase retrieval)
        butterworth_cutoff=0.25,  #0.1 would be very smooth, 0.4 would be very grainy (reconstruction)
        butterworth_order=2,  # for reconstruction
        doPolarRing=False,  # ring removal
        Rarc=30,  # min angle needed to be considered ring artifact (ring removal)
        Rmaxwidth=100,  # max width of rings to be filtered (ring removal)
        Rtmax=3000.0,  # max portion of image to filter (ring removal)
        Rthr=3000.0,  # max value of offset due to ring artifact (ring removal)
        Rtmin=-3000.0,  # min value of image to filter (ring removal)
        cor=None,  # center of rotation (float). If not used then cor will be detected automatically
        corFunction='pc',  # center of rotation function to use - can be 'pc', 'vo', or 'nm'
        voInd=None,  # index of slice to use for cor search (vo)
        voSMin=-40,  # min radius for searching in sinogram (vo)
        voSMax=40,  # max radius for searching in sinogram (vo)
        voSRad=10,  # search radius (vo)
        voStep=0.5,  # search step (vo)
        voRatio=2.0,  # ratio of field-of-view and object size (vo)
        voDrop=20,  # drop lines around vertical center of mask (vo)
        nmInd=None,  # index of slice to use for cor search (nm)
        nmInit=None,  # initial guess for center (nm)
        nmTol=0.5,  # desired sub-pixel accuracy (nm)
        nmMask=True,  # if True, limits analysis to circular region (nm)
        nmRatio=1.0,  # ratio of radius of circular mask to edge of reconstructed image (nm)
        nmSinoOrder=False,  # if True, analyzes in sinogram space. If False, analyzes in radiograph space
        use360to180=False,  # use 360 to 180 conversion
        doBilateralFilter=False,  # if True, uses bilateral filter on image just before write step # NOTE: image will be converted to 8bit if it is not already
        bilateral_srad=3,  # spatial radius for bilateral filter (image will be converted to 8bit if not already)
        bilateral_rrad=30,  # range radius for bilateral filter (image will be converted to 8bit if not already)
        castTo8bit=False,  # convert data to 8bit before writing
        cast8bit_min=-10,  # min value if converting to 8bit
        cast8bit_max=30,  # max value if converting to 8bit
        useNormalize_nf=False,  # normalize based on background intensity (nf)
        chunk_proj=100,  # chunk size in projection direction
        chunk_sino=100,  # chunk size in sinogram direction
        npad=None,  # amount to pad data before reconstruction
        projused=None,  #should be slicing in projection dimension (start,end,step)
        sinoused=None,  #should be sliceing in sinogram dimension (start,end,step). If first value is negative, it takes the number of slices from the second value in the middle of the stack.
        correcttilt=0,  #tilt dataset
        tiltcenter_slice=None,  # tilt center (x direction)
        tiltcenter_det=None,  # tilt center (y direction)
        angle_offset=0,  #this is the angle offset from our default (270) so that tomopy yields output in the same orientation as previous software (Octopus)
        anglelist=None,  #if not set, will assume evenly spaced angles which will be calculated by the angular range and number of angles found in the file. if set to -1, will read individual angles from each image. alternatively, a list of angles can be passed.
        doBeamHardening=False,  #turn on beam hardening correction, based on "Correction for beam hardening in computed tomography", Gabor Herman, 1979 Phys. Med. Biol. 24 81
        BeamHardeningCoefficients=None,  #6 values, tomo = a0 + a1*tomo + a2*tomo^2 + a3*tomo^3 + a4*tomo^4 + a5*tomo^5
        projIgnoreList=None,  #projections to be ignored in the reconstruction (for simplicity in the code, they will not be removed and will be processed as all other projections but will be set to zero absorption right before reconstruction.
        *args,
        **kwargs):

    start_time = time.time()
    print("Start {} at:".format(filename) +
          time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()))

    outputPath = inputPath if outputPath is None else outputPath

    outputFilename = filename if outputFilename is None else outputFilename
    tempfilenames = [outputPath + 'tmp0.h5', outputPath + 'tmp1.h5']
    filenametowrite = outputPath + '/rec' + filename.strip(
        ".h5") + '/' + outputFilename
    #filenametowrite = outputPath+'/rec'+filename+'/'+outputFilename

    print("cleaning up previous temp files", end="")
    for tmpfile in tempfilenames:
        try:
            os.remove(tmpfile)
        except OSError:
            pass

    print(", reading metadata")

    datafile = h5py.File(inputPath + filename, 'r')
    gdata = dict(dxchange.reader._find_dataset_group(datafile).attrs)
    pxsize = float(gdata['pxsize']) / 10  # /10 to convert unites from mm to cm
    numslices = int(gdata['nslices'])
    numangles = int(gdata['nangles'])
    angularrange = float(gdata['arange'])
    numrays = int(gdata['nrays'])
    npad = int(np.ceil(numrays * np.sqrt(2)) -
               numrays) // 2 if npad is None else npad
    projused = (0, numangles - 1, 1) if projused is None else projused

    #	ndark = int(gdata['num_dark_fields'])
    #	ind_dark = list(range(0, ndark))
    #	group_dark = [numangles - 1]
    inter_bright = int(gdata['i0cycle'])
    nflat = int(gdata['num_bright_field'])
    ind_flat = list(range(0, nflat))
    if inter_bright > 0:
        group_flat = list(range(0, numangles, inter_bright))
        if group_flat[-1] != numangles - 1:
            group_flat.append(numangles - 1)
    elif inter_bright == 0:
        group_flat = [0, numangles - 1]
    else:
        group_flat = None
    ind_tomo = list(range(0, numangles))
    floc_independent = dxchange.reader._map_loc(ind_tomo, group_flat)

    #figure out the angle list (a list of angles, one per projection image)
    dtemp = datafile[list(datafile.keys())[0]]
    fltemp = list(dtemp.keys())
    firstangle = float(dtemp[fltemp[0]].attrs.get('rot_angle', 0))
    if anglelist is None:
        #the offset angle should offset from the angle of the first image, which is usually 0, but in the case of timbir data may not be.
        #we add the 270 to be inte same orientation as previous software used at bl832
        angle_offset = 270 + angle_offset - firstangle
        anglelist = tomopy.angles(numangles, angle_offset,
                                  angle_offset - angularrange)
    elif anglelist == -1:
        anglelist = np.zeros(shape=numangles)
        for icount in range(0, numangles):
            anglelist[icount] = np.pi / 180 * (270 + angle_offset - float(
                dtemp[fltemp[icount]].attrs['rot_angle']))

    #if projused is different than default, need to chnage numangles and angularrange

    #can't do useNormalize_nf and doOutliers2D at the same time, or doOutliers2D and doOutliers1D at the same time, b/c of the way we chunk, for now just disable that
    if useNormalize_nf == True and doOutliers2D == True:
        useNormalize_nf = False
        print(
            "we cannot currently do useNormalize_nf and doOutliers2D at the same time, turning off useNormalize_nf"
        )
    if doOutliers2D == True and doOutliers1D == True:
        doOutliers1D = False
        print(
            "we cannot currently do doOutliers1D and doOutliers2D at the same time, turning off doOutliers1D"
        )

    #figure out how user can pass to do central x number of slices, or set of slices dispersed throughout (without knowing a priori the value of numslices)
    if sinoused is None:
        sinoused = (0, numslices, 1)
    elif sinoused[0] < 0:
        sinoused = (
            int(np.floor(numslices / 2.0) - np.ceil(sinoused[1] / 2.0)),
            int(np.floor(numslices / 2.0) + np.floor(sinoused[1] / 2.0)), 1)

    num_proj_per_chunk = np.minimum(chunk_proj, projused[1] - projused[0])
    numprojchunks = (projused[1] - projused[0] - 1) // num_proj_per_chunk + 1
    num_sino_per_chunk = np.minimum(chunk_sino, sinoused[1] - sinoused[0])
    numsinochunks = (sinoused[1] - sinoused[0] - 1) // num_sino_per_chunk + 1
    numprojused = (projused[1] - projused[0]) // projused[2]
    numsinoused = (sinoused[1] - sinoused[0]) // sinoused[2]

    BeamHardeningCoefficients = (
        0, 1, 0, 0, 0,
        .1) if BeamHardeningCoefficients is None else BeamHardeningCoefficients

    if cor is None:
        print("Detecting center of rotation", end="")
        if angularrange > 300:
            lastcor = int(np.floor(numangles / 2) - 1)
        else:
            lastcor = numangles - 1
        #I don't want to see the warnings about the reader using a deprecated variable in dxchange
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            tomo, flat, dark, floc = dxchange.read_als_832h5(
                inputPath + filename, ind_tomo=(0, lastcor))
        tomo = tomo.astype(np.float32)
        if useNormalize_nf:
            tomopy.normalize_nf(tomo, flat, dark, floc, out=tomo)
        else:
            tomopy.normalize(tomo, flat, dark, out=tomo)

        if corFunction == 'vo':
            # same reason for catching warnings as above
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                cor = tomopy.find_center_vo(tomo,
                                            ind=voInd,
                                            smin=voSMin,
                                            smax=voSMax,
                                            srad=voSRad,
                                            step=voStep,
                                            ratio=voRatio,
                                            drop=voDrop)
        elif corFunction == 'nm':
            cor = tomopy.find_center(
                tomo,
                tomopy.angles(numangles, angle_offset,
                              angle_offset - angularrange),
                ind=nmInd,
                init=nmInit,
                tol=nmTol,
                mask=nmMask,
                ratio=nmRatio,
                sinogram_order=nmSinoOrder)
        elif corFunction == 'pc':
            cor = tomopy.find_center_pc(tomo[0], tomo[1], tol=0.25)
        else:
            raise ValueError("\'corFunction\' must be one of: [ pc, vo, nm ].")
        print(", {}".format(cor))
    else:
        print("using user input center of {}".format(cor))

    function_list = []

    if doOutliers1D:
        function_list.append('remove_outlier1d')
    if doOutliers2D:
        function_list.append('remove_outlier2d')
    if useNormalize_nf:
        function_list.append('normalize_nf')
    else:
        function_list.append('normalize')
    function_list.append('minus_log')
    if doBeamHardening:
        function_list.append('beam_hardening')
    if doFWringremoval:
        function_list.append('remove_stripe_fw')
    if doTIringremoval:
        function_list.append('remove_stripe_ti')
    if doSFringremoval:
        function_list.append('remove_stripe_sf')
    if correcttilt:
        function_list.append('correcttilt')
    if use360to180:
        function_list.append('do_360_to_180')
    if doPhaseRetrieval:
        function_list.append('phase_retrieval')
    function_list.append('recon_mask')
    if doPolarRing:
        function_list.append('polar_ring')
    if castTo8bit:
        function_list.append('castTo8bit')
    if doBilateralFilter:
        function_list.append('bilateral_filter')
    function_list.append('write_output')

    # Figure out first direction to slice
    for func in function_list:
        if slice_dir[func] != 'both':
            axis = slice_dir[func]
            break

    done = False
    curfunc = 0
    curtemp = 0
    while True:  # Loop over reading data in certain chunking direction
        if axis == 'proj':
            niter = numprojchunks
        else:
            niter = numsinochunks
        for y in range(niter):  # Loop over chunks
            print("{} chunk {} of {}".format(axis, y + 1, niter))
            if curfunc == 0:
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    if axis == 'proj':
                        tomo, flat, dark, floc = dxchange.read_als_832h5(
                            inputPath + filename,
                            ind_tomo=range(
                                y * num_proj_per_chunk + projused[0],
                                np.minimum(
                                    (y + 1) * num_proj_per_chunk + projused[0],
                                    numangles)),
                            sino=(sinoused[0], sinoused[1], sinoused[2]))
                    else:
                        tomo, flat, dark, floc = dxchange.read_als_832h5(
                            inputPath + filename,
                            ind_tomo=range(projused[0], projused[1],
                                           projused[2]),
                            sino=(y * num_sino_per_chunk + sinoused[0],
                                  np.minimum((y + 1) * num_sino_per_chunk +
                                             sinoused[0], numslices), 1))
            else:
                if axis == 'proj':
                    start, end = y * num_proj_per_chunk, np.minimum(
                        (y + 1) * num_proj_per_chunk, numprojused)
                    tomo = dxchange.reader.read_hdf5(
                        tempfilenames[curtemp],
                        '/tmp/tmp',
                        slc=((start, end, 1), (0, numslices, 1),
                             (0, numrays, 1)))  #read in intermediate file
                else:
                    start, end = y * num_sino_per_chunk, np.minimum(
                        (y + 1) * num_sino_per_chunk, numsinoused)
                    tomo = dxchange.reader.read_hdf5(tempfilenames[curtemp],
                                                     '/tmp/tmp',
                                                     slc=((0, numangles,
                                                           1), (start, end, 1),
                                                          (0, numrays, 1)))
            dofunc = curfunc
            keepvalues = None
            while True:  # Loop over operations to do in current chunking direction
                func_name = function_list[dofunc]
                newaxis = slice_dir[func_name]
                if newaxis != 'both' and newaxis != axis:
                    # We have to switch axis, so flush to disk
                    if y == 0:
                        try:
                            os.remove(tempfilenames[1 - curtemp])
                        except OSError:
                            pass
                    appendaxis = 1 if axis == 'sino' else 0
                    dxchange.writer.write_hdf5(
                        tomo,
                        fname=tempfilenames[1 - curtemp],
                        gname='tmp',
                        dname='tmp',
                        overwrite=False,
                        appendaxis=appendaxis)  #writing intermediate file...
                    break
                print(func_name, end=" ")
                curtime = time.time()
                if func_name == 'remove_outlier1d':
                    tomo = tomo.astype(np.float32, copy=False)
                    remove_outlier1d(tomo,
                                     outlier_diff1D,
                                     size=outlier_size1D,
                                     out=tomo)
                if func_name == 'remove_outlier2d':
                    tomo = tomo.astype(np.float32, copy=False)
                    tomopy.remove_outlier(tomo,
                                          outlier_diff2D,
                                          size=outlier_size2D,
                                          axis=0,
                                          out=tomo)
                elif func_name == 'normalize_nf':
                    tomo = tomo.astype(np.float32, copy=False)
                    tomopy.normalize_nf(
                        tomo, flat, dark, floc_independent, out=tomo
                    )  #use floc_independent b/c when you read file in proj chunks, you don't get the correct floc returned right now to use here.
                elif func_name == 'normalize':
                    tomo = tomo.astype(np.float32, copy=False)
                    tomopy.normalize(tomo, flat, dark, out=tomo)
                elif func_name == 'minus_log':
                    mx = np.float32(0.00000000000000000001)
                    ne.evaluate('where(tomo>mx, tomo, mx)', out=tomo)
                    tomopy.minus_log(tomo, out=tomo)
                elif func_name == 'beam_hardening':
                    loc_dict = {
                        'a{}'.format(i): np.float32(val)
                        for i, val in enumerate(BeamHardeningCoefficients)
                    }
                    tomo = ne.evaluate(
                        'a0 + a1*tomo + a2*tomo**2 + a3*tomo**3 + a4*tomo**4 + a5*tomo**5',
                        local_dict=loc_dict,
                        out=tomo)
                elif func_name == 'remove_stripe_fw':
                    tomo = tomopy.remove_stripe_fw(tomo,
                                                   sigma=ringSigma,
                                                   level=ringLevel,
                                                   pad=True,
                                                   wname=ringWavelet)
                elif func_name == 'remove_stripe_ti':
                    tomo = tomopy.remove_stripe_ti(tomo,
                                                   nblock=ringNBlock,
                                                   alpha=ringAlpha)
                elif func_name == 'remove_stripe_sf':
                    tomo = tomopy.remove_stripe_sf(tomo, size=ringSize)
                elif func_name == 'correcttilt':
                    if tiltcenter_slice is None:
                        tiltcenter_slice = numslices / 2.
                    if tiltcenter_det is None:
                        tiltcenter_det = tomo.shape[2] / 2
                    new_center = tiltcenter_slice - 0.5 - sinoused[0]
                    center_det = tiltcenter_det - 0.5

                    #add padding of 10 pixels, to be unpadded right after tilt correction. This makes the tilted image not have zeros at certain edges, which matters in cases where sample is bigger than the field of view. For the small amounts we are generally tilting the images, 10 pixels is sufficient.
                    #					tomo = tomopy.pad(tomo, 2, npad=10, mode='edge')
                    #					center_det = center_det + 10

                    cntr = (center_det, new_center)
                    for b in range(tomo.shape[0]):
                        tomo[b] = st.rotate(
                            tomo[b],
                            correcttilt,
                            center=cntr,
                            preserve_range=True,
                            order=1,
                            mode='edge',
                            clip=True
                        )  #center=None means image is rotated around its center; order=1 is default, order of spline interpolation


#					tomo = tomo[:, :, 10:-10]

                elif func_name == 'do_360_to_180':

                    # Keep values around for processing the next chunk in the list
                    keepvalues = [
                        angularrange, numangles, projused, num_proj_per_chunk,
                        numprojchunks, numprojused, numrays, anglelist
                    ]

                    #why -.5 on one and not on the other?
                    if tomo.shape[0] % 2 > 0:
                        tomo = sino_360_to_180(
                            tomo[0:-1, :, :],
                            overlap=int(
                                np.round((tomo.shape[2] - cor - .5)) * 2),
                            rotation='right')
                        angularrange = angularrange / 2 - angularrange / (
                            tomo.shape[0] - 1)
                    else:
                        tomo = sino_360_to_180(
                            tomo[:, :, :],
                            overlap=int(np.round((tomo.shape[2] - cor)) * 2),
                            rotation='right')
                        angularrange = angularrange / 2
                    numangles = int(numangles / 2)
                    projused = (0, numangles - 1, 1)
                    num_proj_per_chunk = np.minimum(chunk_proj,
                                                    projused[1] - projused[0])
                    numprojchunks = (projused[1] - projused[0] -
                                     1) // num_proj_per_chunk + 1
                    numprojused = (projused[1] - projused[0]) // projused[2]
                    numrays = tomo.shape[2]

                    anglelist = anglelist[:numangles]

                elif func_name == 'phase_retrieval':
                    tomo = tomopy.retrieve_phase(tomo,
                                                 pixel_size=pxsize,
                                                 dist=propagation_dist,
                                                 energy=kev,
                                                 alpha=alphaReg,
                                                 pad=True)
                elif func_name == 'recon_mask':
                    tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')

                    if projIgnoreList is not None:
                        for badproj in projIgnoreList:
                            tomo[badproj] = 0

                    rec = tomopy.recon(
                        tomo,
                        anglelist,
                        center=cor + npad,
                        algorithm='gridrec',
                        filter_name='butterworth',
                        filter_par=[butterworth_cutoff, butterworth_order])
                    rec = rec[:, npad:-npad, npad:-npad]
                    rec /= pxsize  # convert reconstructed voxel values from 1/pixel to 1/cm
                    rec = tomopy.circ_mask(rec, 0)
                elif func_name == 'polar_ring':
                    rec = np.ascontiguousarray(rec, dtype=np.float32)
                    rec = tomopy.remove_ring(rec,
                                             theta_min=Rarc,
                                             rwidth=Rmaxwidth,
                                             thresh_max=Rtmax,
                                             thresh=Rthr,
                                             thresh_min=Rtmin,
                                             out=rec)
                elif func_name == 'castTo8bit':
                    rec = convert8bit(rec, cast8bit_min, cast8bit_max)
                elif func_name == 'bilateral_filter':
                    rec = pyF3D.run_BilateralFilter(
                        rec,
                        spatialRadius=bilateral_srad,
                        rangeRadius=bilateral_rrad)
                elif func_name == 'write_output':
                    dxchange.write_tiff_stack(rec,
                                              fname=filenametowrite,
                                              start=y * num_sino_per_chunk +
                                              sinoused[0])
                print('(took {:.2f} seconds)'.format(time.time() - curtime))
                dofunc += 1
                if dofunc == len(function_list):
                    break
            if y < niter - 1 and keepvalues:  # Reset original values for next chunk
                angularrange, numangles, projused, num_proj_per_chunk, numprojchunks, numprojused, numrays, anglelist = keepvalues

        curtemp = 1 - curtemp
        curfunc = dofunc
        if curfunc == len(function_list):
            break
        axis = slice_dir[function_list[curfunc]]
    print("cleaning up temp files")
    for tmpfile in tempfilenames:
        try:
            os.remove(tmpfile)
        except OSError:
            pass
    print("End Time: " +
          time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()))
    print('It took {:.3f} s to process {}'.format(time.time() - start_time,
                                                  inputPath + filename))
Пример #8
0
    # Flat-field correction of raw data.
    data = tomopy.normalize(proj, flat, dark, cutoff=1.4)

    # remove stripes
    data = tomopy.remove_stripe_fw(data,level=5,wname='sym16',sigma=1,pad=True)
    #data = tomopy.prep.stripe.remove_stripe_ti(data,alpha=7)
    #data = tomopy.prep.stripe.remove_stripe_sf(data,size=51)

    # phase retrieval
    data = tomopy.prep.phase.retrieve_phase(data,pixel_size=detector_pixel_size_x,dist=sample_detector_distance,energy=monochromator_energy,alpha=alpha,pad=True)

    # Find rotation center
    # rot_center = 955
    # rot_center = 953.25
    # rot_center = tomopy.find_center(data, theta, init=rot_center, ind=0, tol=0.5)
    rot_center = tomopy.find_center_vo(data)   
    print(h5name, rot_center)

    data = tomopy.minus_log(data)

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

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

    # Write data as stack of TIFs.
    ##fname = top +'full_rec/' + prefix + h5name + '/recon'

    fname = top + h5name + '_slice_rec/' + 'recon'
    print("Rec: ", fname)
Пример #9
0
def loopEngine(filename,output_file,center=False,zinger=None,zinger_level=1000,offset=0,num_chunk=1,
               chunk_size=50,numRecSlices=50,margin_slices=30,flat_name=None,dark_name=None,
               mask=False,mask_ratio=1,**kwargs):
    dim = dataInfo(filename)
    numSlices = dim[1]  
    
    if kwargs.has_key('ExplicitParams'):
        center = kwargs['ExplicitParams']['center']
        zinger = kwargs['ExplicitParams']['zinger']
        zinger_level = kwargs['ExplicitParams']['zinger_level']
        offset = kwargs['ExplicitParams']['offset']
        num_chunk = kwargs['ExplicitParams']['num_chunk']
        chunk_size = kwargs['ExplicitParams']['chunk_size']
        numRecSlices = kwargs['ExplicitParams']['numRecSlices']
        margin_slices = kwargs['ExplicitParams']['margin_slices']
        flat_name = kwargs['ExplicitParams']['flat_name']
        dark_name = kwargs['ExplicitParams']['dark_name'] 
        mask = kwargs['ExplicitParams']['mask'] 
        mask_ratio = kwargs['ExplicitParams']['mask_ratio']
        
    if offset == None:
        offset = 0
    if numRecSlices == None:
        numRecSlices = dim[0] 
             
    state = 1
    for ii in range(num_chunk):   
        print 'chunk ',ii, ' reconstruction starts'                                                 
        print time.asctime()  
        
        if ii == 0:
            sliceStart = offset + ii*chunk_size
            sliceEnd = offset + (ii+1)*chunk_size
        else:
            sliceStart = offset + ii*(chunk_size-margin_slices)
            sliceEnd = offset + sliceStart + chunk_size
            if sliceEnd > (offset+numRecSlices):
                sliceEnd = offset+numRecSlices
            if sliceEnd > numSlices:
                sliceEnd = numSlices                
        
        if (sliceEnd - sliceStart) <= margin_slices:
            print 'Reconstruction finishes!'
            break        
    
        data,white,dark = dataStandardReader(filename,sliceStart=sliceStart,sliceEnd=sliceEnd,
                                             flat_name=flat_name,dark_name=dark_name)
   
        if data.all() == 0:
            state = 0
            break
        
        data_size = data.shape
        theta = np.linspace(0,np.pi,num=data_size[0]+1) 
        print 'data is read'
        
    #    # remove zingers (pixels with abnormal counts)
        if zinger == True:
            data = tomopy.misc.corr.remove_outlier(data,zinger_level,size=15,axis=0)
            white = tomopy.misc.corr.remove_outlier(white,zinger_level,size=15,axis=0)
            print  'remove outlier is done'
        
        # normalize projection images; for now you need to do below two operations in sequence
        data = tomopy.prep.normalize.normalize(data,white,dark)
        print 'normalization is done'
        
        data = generalFilterContainer(data,**kwargs)   

        if ii == 0 and center == False:
            center = tomopy.find_center_vo(data)
            
        print center    
        # tomo reconstruction
#        data = tomopy.prep.normalize.minus_log(data)
        data_recon = recon(data,theta,center=center,algorithm='gridrec')
        print 'reconstruction is done'
        
        if mask == True:
            data_recon = tomopy.circ_mask(data_recon, 0, ratio=mask_ratio)
        
        # save reconstructions
        dxchange.writer.write_tiff_stack(data_recon[np.int(margin_slices/2):(sliceEnd-sliceStart-np.int(margin_slices/2)),:,:], 
                                                     axis = 0,
                                                     fname = output_file, 
                                                     start = sliceStart+np.int(margin_slices/2),
                                                     overwrite = True)
        print 'chunk ',ii, ' reconstruction is saved'                                                 
        print time.asctime()
    
    if state == 1:
        print 'Reconstruction finishes!'  
    else:
        print 'Reconstruction is terminated due to data file error.'
Пример #10
0
    #data = tomopy.prep.stripe.remove_stripe_ti(data,alpha=7)
    #data = tomopy.prep.stripe.remove_stripe_sf(data,size=51)

    # phase retrieval
    data = tomopy.prep.phase.retrieve_phase(data,
                                            pixel_size=detector_pixel_size_x,
                                            dist=sample_detector_distance,
                                            energy=monochromator_energy,
                                            alpha=alpha,
                                            pad=True)

    # Find rotation center
    # rot_center = 955
    # rot_center = 953.25
    # rot_center = tomopy.find_center(data, theta, init=rot_center, ind=0, tol=0.5)
    rot_center = tomopy.find_center_vo(data)
    print(h5name, rot_center)

    data = tomopy.minus_log(data)

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

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

    # Write data as stack of TIFs.
    ##fname = top +'full_rec/' + prefix + h5name + '/recon'

    fname = top + h5name + '_slice_rec/' + 'recon'
    print("Rec: ", fname)
Пример #11
0
# phase retrieval
#data = tomopy.prep.phase.retrieve_phase(prj,pixel_size=detector_pixel_size_x,dist=sample_detector_distance,energy=monochromator_energy,alpha=alpha,pad=True)


prj = tomopy.median_filter(prj,size=medfilt_size)
print('\n** Median filter done!')
if debug:
    print('## Debug: after nedian filter:')
    print('\n** Min and max val in prj before recon: %0.5f, %0.3f'  % (np.min(prj), np.max(prj)))


if level>0:
    prj = tomopy.downsample(prj, level=level)
    print('\n** Down sampling done!\n')
if debug:
    print('## Debug: after down sampling:')
    print('\n** Min and max val in prj before recon: %0.5f, %0.3f'  % (np.min(prj), np.max(prj)))

if auto_center == False:

    tomopy.write_center(prj,theta,dpath=output_path,cen_range=[Center_st/pow(2,level),Center_end/pow(2,level),((Center_end - Center_st)/float(N_recon))/pow(2,level)])

else:
    rot_axis = tomopy.find_center_vo(prj)
    rot_axis = rot_axis * pow(2,level)
    print('*** Rotation center: %0.2f' % rot_axis)
    rec = tomopy.recon(prj, theta, center=rot_axis/pow(2,level), algorithm='gridrec', filter_name='parzen')
    rec=np.squeeze(rec)
    plt.figure()
    plt.imshow(rec, cmap='gray', aspect="auto", interpolation='none')
    plt.colorbar(), plt.title('Rotation center: %0.2f' % rot_axis), plt.show()
Пример #12
0
def cleaning(
    filename,
    bffilename=None,
    inputPath='/',  #input path, location of the data set to reconstruct
    outputPath=None,  # define an output path (default is inputPath), a sub-folder will be created based on file name
    outputFilename=None,  #file name for output tif files (a number and .tiff will be added). default is based on input filename
    fulloutputPath=None,  # definte the full output path, no automatic sub-folder will be created
    doFWringremoval=True,  # Fourier-wavelet ring removal
    ringSigma=3,  # damping parameter in Fourier space (Fourier-wavelet ring removal)
    ringLevel=8,  # number of wavelet transform levels (Fourier-wavelet ring removal)
    ringWavelet='db5',  # type of wavelet filter (Fourier-wavelet ring removal)
    ringNBlock=0,  # used in Titarenko ring removal (doTIringremoval)
    ringAlpha=1.5,  # used in Titarenko ring removal (doTIringremoval)
    ringSize=5,  # used in smoothing filter ring removal (doSFringremoval)
    butterworth_cutoff=0.25,  #0.1 would be very smooth, 0.4 would be very grainy (reconstruction)
    butterworth_order=2,  # for reconstruction
    npad=None,  # amount to pad data before reconstruction
    projused=None,  # should be slicing in projection dimension (start,end,step) Be sure to add one to the end as stop in python means the last value is omitted 
    sinoused=None,  # should be sliceing in sinogram dimension (start,end,step). If first value is negative, it takes the number of slices from the second value in the middle of the stack.
    angle_offset=0,  # this is the angle offset from our default (270) so that tomopy yields output in the same orientation as previous software (Octopus)
    anglelist=None,  # if not set, will assume evenly spaced angles which will be calculated by the angular range and number of angles found in the file. if set to -1, will read individual angles from each image. alternatively, a list of angles can be passed.
    cor=None,  # center of rotation (float). If not used then cor will be detected automatically
    corFunction='pc',  # center of rotation function to use - can be 'pc', 'vo', or 'nm'
    voInd=None,  # index of slice to use for cor search (vo)
    voSMin=-40,  # min radius for searching in sinogram (vo)
    voSMax=40,  # max radius for searching in sinogram (vo)
    voSRad=10,  # search radius (vo)
    voStep=0.5,  # search step (vo)
    voRatio=2.0,  # ratio of field-of-view and object size (vo)
    voDrop=20,  # drop lines around vertical center of mask (vo)
    nmInd=None,  # index of slice to use for cor search (nm)
    nmInit=None,  # initial guess for center (nm)
    nmTol=0.5,  # desired sub-pixel accuracy (nm)
    nmMask=True,  # if True, limits analysis to circular region (nm)
    nmRatio=1.0,  # ratio of radius of circular mask to edge of reconstructed image (nm)
    nmSinoOrder=False,  # if True, analyzes in sinogram space. If False, analyzes in radiograph space
    useNormalize_nf=False,  # normalize based on background intensity (nf)
    bfexposureratio=1  #ratio of exposure time of bf to exposure time of sample
):

    start_time = time.time()
    print("Start {} at:".format(filename) +
          time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()))

    outputFilename = os.path.splitext(
        filename)[0] if outputFilename is None else outputFilename
    outputPath = inputPath + 'rec' + os.path.splitext(
        filename
    )[0] + '/' if outputPath is None else outputPath + 'rec' + os.path.splitext(
        filename)[0] + '/'
    fulloutputPath = outputPath if fulloutputPath is None else fulloutputPath
    tempfilenames = [fulloutputPath + 'tmp0.h5', fulloutputPath + 'tmp1.h5']
    filenametowrite = fulloutputPath + outputFilename
    print(filenametowrite)

    print("cleaning up previous temp files", end="")
    for tmpfile in tempfilenames:
        try:
            os.remove(tmpfile)
        except OSError:
            pass

    print(", reading metadata")

    datafile = h5py.File(inputPath + filename, 'r')
    gdata = dict(dxchange.reader._find_dataset_group(datafile).attrs)
    numslices = int(gdata['nslices'])
    numangles = int(gdata['nangles'])
    print('There are ' + str(numslices) + ' sinograms and ' + str(numangles) +
          ' projections')
    angularrange = float(gdata['arange'])
    numrays = int(gdata['nrays'])
    npad = int(np.ceil(numrays * np.sqrt(2)) -
               numrays) // 2 if npad is None else npad
    if projused is not None and (
            projused[1] > numangles - 1 or projused[0] < 0
    ):  #allows program to deal with out of range projection values
        if projused[1] > numangles:
            print(
                "End Projection value greater than number of angles. Value has been lowered to the number of angles "
                + str(numangles))
            projused = (projused[0], numangles, projused[2])
        if projused[0] < 0:
            print("Start Projection value less than zero. Value raised to 0")
            projused = (0, projused[1], projused[2])
    if projused is None:
        projused = (0, numangles, 1)
    else:
        #if projused is different than default, need to chnage numangles and angularrange
        #dula attempting to do this with these two lines, we'll see if it works! 11/16/17
        testrange = range(projused[0], projused[1], projused[2])
        #+1 because we need to compensate for the range functions last value always being one less than the second arg
        angularrange = (angularrange /
                        (numangles - 1)) * (projused[1] - projused[0])
        # want angular range to stay constant if we keep the end values consistent
        numangles = len(testrange)


# ndark = int(gdata['num_dark_fields'])
# ind_dark = list(range(0, ndark))
# group_dark = [numangles - 1]
    inter_bright = int(gdata['i0cycle'])
    if inter_bright > 0:
        group_flat = list(range(0, numangles, inter_bright))
        if group_flat[-1] != numangles - 1:
            group_flat.append(numangles - 1)
    elif inter_bright == 0:
        group_flat = [0, numangles - 1]
    else:
        group_flat = None

    # figure out the angle list (a list of angles, one per projection image)
    dtemp = datafile[list(datafile.keys())[0]]
    fltemp = list(dtemp.keys())
    firstangle = float(dtemp[fltemp[0]].attrs.get('rot_angle', 0))
    anglegap = angularrange / (numangles - 1)
    firstangle += anglegap * projused[0]  #accounting for projused argument
    if anglelist is None:
        #the offset angle should offset from the angle of the first image, which is usually 0, but in the case of timbir data may not be.
        #we add the 270 to be inte same orientation as previous software used at bl832
        angle_offset = 270 + angle_offset - firstangle
        anglelist = tomopy.angles(numangles, angle_offset,
                                  angle_offset - angularrange)
    elif anglelist == -1:
        anglelist = np.zeros(shape=numangles)
        for icount in range(0, numangles):
            anglelist[icount] = np.pi / 180 * (270 + angle_offset - float(
                dtemp[fltemp[icount]].attrs['rot_angle']))

    #figure out how user can pass to do central x number of slices, or set of slices dispersed throughout (without knowing a priori the value of numslices)
    if sinoused is None:
        sinoused = (0, numslices, 1)
    elif sinoused[0] < 0:
        sinoused = (
            int(np.floor(numslices / 2.0) - np.ceil(sinoused[1] / 2.0)),
            int(np.floor(numslices / 2.0) + np.floor(sinoused[1] / 2.0)), 1)

    if cor is None:
        print("Detecting center of rotation", end="")
        if angularrange > 300:
            lastcor = int(np.floor(numangles / 2) - 1)
        else:
            lastcor = numangles - 1
        # I don't want to see the warnings about the reader using a deprecated variable in dxchange
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            tomo, flat, dark, floc = dxchange.read_als_832h5(
                inputPath + filename, ind_tomo=(0, lastcor))
            if bffilename is not None:
                tomobf, flatbf, darkbf, flocbf = dxchange.read_als_832h5(
                    inputPath + bffilename)
                flat = tomobf
        tomo = tomo.astype(np.float32)
        if useNormalize_nf:
            tomopy.normalize_nf(tomo, flat, dark, floc, out=tomo)
            if bfexposureratio != 1:
                tomo = tomo * bfexposureratio
        else:
            tomopy.normalize(tomo, flat, dark, out=tomo)
            if bfexposureratio != 1:
                tomo = tomo * bfexposureratio

        if corFunction == 'vo':
            # same reason for catching warnings as above
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                cor = tomopy.find_center_vo(tomo,
                                            ind=voInd,
                                            smin=voSMin,
                                            smax=voSMax,
                                            srad=voSRad,
                                            step=voStep,
                                            ratio=voRatio,
                                            drop=voDrop)
        elif corFunction == 'nm':
            cor = tomopy.find_center(
                tomo,
                tomopy.angles(numangles, angle_offset,
                              angle_offset - angularrange),
                ind=nmInd,
                init=nmInit,
                tol=nmTol,
                mask=nmMask,
                ratio=nmRatio,
                sinogram_order=nmSinoOrder)
        elif corFunction == 'pc':
            cor = tomopy.find_center_pc(tomo[0], tomo[1], tol=0.25)
        else:
            raise ValueError("\'corFunction\' must be one of: [ pc, vo, nm ].")
        print(", {}".format(cor))
    else:
        print("using user input center of {}".format(cor))

    tomo, flat, dark, floc = dxchange.read_als_832h5(
        inputPath + filename,
        ind_tomo=range(projused[0], projused[1], projused[2]),
        sino=(sinoused[0], sinoused[1], sinoused[2]))

    tomo = tomo.astype(np.float32, copy=False)
    tomopy.normalize(tomo, flat, dark, out=tomo)
    mx = np.float32(0.01)
    ne.evaluate('where(tomo>mx, tomo, mx)', out=tomo)
    tomopy.minus_log(tomo, out=tomo)
    tomo = tomopy.remove_stripe_fw(tomo,
                                   sigma=ringSigma,
                                   level=ringLevel,
                                   pad=True,
                                   wname=ringWavelet)
    tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')

    tomo = np.swapaxes(tomo, 0, 1)
    theta = anglelist

    print('It took {:.3f} s to process {}'.format(time.time() - start_time,
                                                  inputPath + filename))

    return tomo, theta, cor
Пример #13
0
def recon(
    filename,
    inputPath = './',
    outputPath = None,
    outputFilename = None,
    doOutliers1D = False, # outlier removal in 1d (along sinogram columns)
    outlier_diff1D = 750, # difference between good data and outlier data (outlier removal)
    outlier_size1D = 3, # radius around each pixel to look for outliers (outlier removal)
    doOutliers2D = False, # outlier removal, standard 2d on each projection
    outlier_diff2D = 750, # difference between good data and outlier data (outlier removal)
    outlier_size2D = 3, # radius around each pixel to look for outliers (outlier removal)
    doFWringremoval = True,  # Fourier-wavelet ring removal
    doTIringremoval = False, # Titarenko ring removal
    doSFringremoval = False, # Smoothing filter ring removal
    ringSigma = 3, # damping parameter in Fourier space (Fourier-wavelet ring removal)
    ringLevel = 8, # number of wavelet transform levels (Fourier-wavelet ring removal)
    ringWavelet = 'db5', # type of wavelet filter (Fourier-wavelet ring removal)
    ringNBlock = 0, # used in Titarenko ring removal (doTIringremoval)
    ringAlpha = 1.5, # used in Titarenko ring removal (doTIringremoval)
    ringSize = 5, # used in smoothing filter ring removal (doSFringremoval)
    doPhaseRetrieval = False, # phase retrieval
    alphaReg = 0.0002, # smaller = smoother (used for phase retrieval)
    propagation_dist = 75, # sample-to-scintillator distance (phase retrieval)
    kev = 24, # energy level (phase retrieval)
    butterworth_cutoff = 0.25, #0.1 would be very smooth, 0.4 would be very grainy (reconstruction)
    butterworth_order = 2, # for reconstruction
    doTranslationCorrection = False, # correct for linear drift during scan
    xshift = 0, # undesired dx transation correction (from 0 degree to 180 degree proj)
    yshift = 0, # undesired dy transation correction (from 0 degree to 180 degree proj)
    doPolarRing = False, # ring removal
    Rarc=30, # min angle needed to be considered ring artifact (ring removal)
    Rmaxwidth=100, # max width of rings to be filtered (ring removal)
    Rtmax=3000.0, # max portion of image to filter (ring removal)
    Rthr=3000.0, # max value of offset due to ring artifact (ring removal)
    Rtmin=-3000.0, # min value of image to filter (ring removal)
    cor=None, # center of rotation (float). If not used then cor will be detected automatically
    corFunction = 'pc', # center of rotation function to use - can be 'pc', 'vo', or 'nm'
    voInd = None, # index of slice to use for cor search (vo)
    voSMin = -40, # min radius for searching in sinogram (vo)
    voSMax = 40, # max radius for searching in sinogram (vo)
    voSRad = 10, # search radius (vo)
    voStep = 0.5, # search step (vo)
    voRatio = 2.0, # ratio of field-of-view and object size (vo)
    voDrop = 20, # drop lines around vertical center of mask (vo)
    nmInd = None, # index of slice to use for cor search (nm)
    nmInit = None, # initial guess for center (nm)
    nmTol = 0.5, # desired sub-pixel accuracy (nm)
    nmMask = True, # if True, limits analysis to circular region (nm)
    nmRatio = 1.0, # ratio of radius of circular mask to edge of reconstructed image (nm)
    nmSinoOrder = False, # if True, analyzes in sinogram space. If False, analyzes in radiograph space
    use360to180 = False, # use 360 to 180 conversion
    doBilateralFilter = False, # if True, uses bilateral filter on image just before write step # NOTE: image will be converted to 8bit if it is not already
    bilateral_srad = 3, # spatial radius for bilateral filter (image will be converted to 8bit if not already)
    bilateral_rrad = 30, # range radius for bilateral filter (image will be converted to 8bit if not already)
    castTo8bit = False, # convert data to 8bit before writing
    cast8bit_min=-10, # min value if converting to 8bit
    cast8bit_max=30, # max value if converting to 8bit
    useNormalize_nf = False, # normalize based on background intensity (nf)
    chunk_proj = 100, # chunk size in projection direction
    chunk_sino = 100, # chunk size in sinogram direction
    npad = None, # amount to pad data before reconstruction
    projused = None, #should be slicing in projection dimension (start,end,step)
    sinoused = None, #should be sliceing in sinogram dimension (start,end,step). If first value is negative, it takes the number of slices from the second value in the middle of the stack.
    correcttilt = 0, #tilt dataset
    tiltcenter_slice = None, # tilt center (x direction)
    tiltcenter_det = None, # tilt center (y direction)
    angle_offset = 0, #this is the angle offset from our default (270) so that tomopy yields output in the same orientation as previous software (Octopus)
    anglelist = None, #if not set, will assume evenly spaced angles which will be calculated by the angular range and number of angles found in the file. if set to -1, will read individual angles from each image. alternatively, a list of angles can be passed.
    doBeamHardening = False, #turn on beam hardening correction, based on "Correction for beam hardening in computed tomography", Gabor Herman, 1979 Phys. Med. Biol. 24 81
    BeamHardeningCoefficients = None, #6 values, tomo = a0 + a1*tomo + a2*tomo^2 + a3*tomo^3 + a4*tomo^4 + a5*tomo^5
    projIgnoreList = None, #projections to be ignored in the reconstruction (for simplicity in the code, they will not be removed and will be processed as all other projections but will be set to zero absorption right before reconstruction.
    *args, **kwargs):
    
    start_time = time.time()
    print("Start {} at:".format(filename)+time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()))
    
    outputPath = inputPath if outputPath is None else outputPath

    outputFilename = filename if outputFilename is None else outputFilename
    outputFilename = outputFilename.replace('.h5','')
    tempfilenames = [outputPath+'tmp0.h5',outputPath+'tmp1.h5']
    filenametowrite = outputPath+'/rec'+filename.strip(".h5")+'/'+outputFilename
    #filenametowrite = outputPath+'/rec'+filename+'/'+outputFilename
    
    print("cleaning up previous temp files", end="")
    for tmpfile in tempfilenames:
        try:
            os.remove(tmpfile)
        except OSError:
            pass
    
    print(", reading metadata")
    
    datafile = h5py.File(inputPath+filename, 'r')
    gdata = dict(dxchange.reader._find_dataset_group(datafile).attrs) 
    pxsize = float(gdata['pxsize'])/10 # /10 to convert units from mm to cm
    numslices = int(gdata['nslices'])
    numangles = int(gdata['nangles'])
    angularrange = float(gdata['arange'])
    numrays = int(gdata['nrays'])
    npad = int(np.ceil(numrays * np.sqrt(2)) - numrays)//2 if npad is None else npad
    projused = (0,numangles-1,1) if projused is None else projused

#    ndark = int(gdata['num_dark_fields'])
#    ind_dark = list(range(0, ndark))
#    group_dark = [numangles - 1]
    inter_bright = int(gdata['i0cycle'])
    nflat = int(gdata['num_bright_field'])
    ind_flat = list(range(0, nflat))
    if inter_bright > 0:
        group_flat = list(range(0, numangles, inter_bright))
        if group_flat[-1] != numangles - 1:
            group_flat.append(numangles - 1)
    elif inter_bright == 0:
        group_flat = [0, numangles - 1]
    else:
        group_flat = None
    ind_tomo = list(range(0, numangles))
    floc_independent = dxchange.reader._map_loc(ind_tomo, group_flat)        

    #figure out the angle list (a list of angles, one per projection image)
    dtemp = datafile[list(datafile.keys())[0]]
    fltemp = list(dtemp.keys())
    firstangle = float(dtemp[fltemp[0]].attrs.get('rot_angle',0))
    if anglelist is None:
        #the offset angle should offset from the angle of the first image, which is usually 0, but in the case of timbir data may not be.
        #we add the 270 to be inte same orientation as previous software used at bl832
        angle_offset = 270 + angle_offset - firstangle
        anglelist = tomopy.angles(numangles, angle_offset, angle_offset-angularrange)
    elif anglelist==-1:
        anglelist = np.zeros(shape=numangles)
        for icount in range(0,numangles):
            anglelist[icount] = np.pi/180*(270 + angle_offset - float(dtemp[fltemp[icount]].attrs['rot_angle']))
            
    #if projused is different than default, need to chnage numangles and angularrange
    
    #can't do useNormalize_nf and doOutliers2D at the same time, or doOutliers2D and doOutliers1D at the same time, b/c of the way we chunk, for now just disable that
    if useNormalize_nf==True and doOutliers2D==True:
        useNormalize_nf = False
        print("we cannot currently do useNormalize_nf and doOutliers2D at the same time, turning off useNormalize_nf")
    if doOutliers2D==True and doOutliers1D==True:
        doOutliers1D = False
        print("we cannot currently do doOutliers1D and doOutliers2D at the same time, turning off doOutliers1D")
    
    #figure out how user can pass to do central x number of slices, or set of slices dispersed throughout (without knowing a priori the value of numslices)
    if sinoused is None:
        sinoused = (0,numslices,1)
    elif sinoused[0]<0:
        sinoused=(int(np.floor(numslices/2.0)-np.ceil(sinoused[1]/2.0)),int(np.floor(numslices/2.0)+np.floor(sinoused[1]/2.0)),1)
    
    num_proj_per_chunk = np.minimum(chunk_proj,projused[1]-projused[0])
    numprojchunks = (projused[1]-projused[0]-1)//num_proj_per_chunk+1
    num_sino_per_chunk = np.minimum(chunk_sino,sinoused[1]-sinoused[0])
    numsinochunks = (sinoused[1]-sinoused[0]-1)//num_sino_per_chunk+1
    numprojused = (projused[1]-projused[0])//projused[2]
    numsinoused = (sinoused[1]-sinoused[0])//sinoused[2]
    
    BeamHardeningCoefficients = (0, 1, 0, 0, 0, .1) if BeamHardeningCoefficients is None else BeamHardeningCoefficients

    if cor is None:
        print("Detecting center of rotation", end="") 
        if angularrange>300:
            lastcor = int(np.floor(numangles/2)-1)
        else:
            lastcor = numangles-1
        #I don't want to see the warnings about the reader using a deprecated variable in dxchange
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            tomo, flat, dark, floc = dxchange.read_als_832h5(inputPath+filename,ind_tomo=(0,lastcor))
        tomo = tomo.astype(np.float32)
        if useNormalize_nf:
            tomopy.normalize_nf(tomo, flat, dark, floc, out=tomo)
        else:
            tomopy.normalize(tomo, flat, dark, out=tomo)

        if corFunction == 'vo':
            # same reason for catching warnings as above
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                cor = tomopy.find_center_vo(tomo, ind=voInd, smin=voSMin, smax=voSMax, srad=voSRad, step=voStep,
                                        ratio=voRatio, drop=voDrop)
        elif corFunction == 'nm':
            cor = tomopy.find_center(tomo, tomopy.angles(numangles, angle_offset, angle_offset-angularrange),
                                     ind=nmInd, init=nmInit, tol=nmTol, mask=nmMask, ratio=nmRatio,
                                     sinogram_order=nmSinoOrder)
        elif corFunction == 'pc':
            cor = tomopy.find_center_pc(tomo[0], tomo[1], tol=0.25)
        else:
            raise ValueError("\'corFunction\' must be one of: [ pc, vo, nm ].")
        print(", {}".format(cor))
    else:
        print("using user input center of {}".format(cor))
        
    
    function_list = []

    if doOutliers1D:
        function_list.append('remove_outlier1d')
    if doOutliers2D:
        function_list.append('remove_outlier2d')
    if useNormalize_nf:
        function_list.append('normalize_nf')
    else:
        function_list.append('normalize')
    function_list.append('minus_log')
    if doBeamHardening:
        function_list.append('beam_hardening')
    if doFWringremoval:
        function_list.append('remove_stripe_fw')
    if doTIringremoval:
        function_list.append('remove_stripe_ti')
    if doSFringremoval:
        function_list.append('remove_stripe_sf')
    if correcttilt:
        function_list.append('correcttilt')
    if use360to180:
        function_list.append('do_360_to_180')
    if doPhaseRetrieval:
        function_list.append('phase_retrieval')
    function_list.append('recon_mask')
    if doPolarRing:
        function_list.append('polar_ring')
    if castTo8bit:
        function_list.append('castTo8bit')
    if doBilateralFilter:
        function_list.append('bilateral_filter')
    function_list.append('write_output')
        
    
    # Figure out first direction to slice
    for func in function_list:
        if slice_dir[func] != 'both':
            axis = slice_dir[func]
            break
    
    done = False
    curfunc = 0
    curtemp = 0
    while True: # Loop over reading data in certain chunking direction
        if axis=='proj':
            niter = numprojchunks
        else:
            niter = numsinochunks
        for y in range(niter): # Loop over chunks
            print("{} chunk {} of {}".format(axis, y+1, niter))
            if curfunc==0:
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    if axis=='proj':
                        tomo, flat, dark, floc = dxchange.read_als_832h5(inputPath+filename,ind_tomo=range(y*num_proj_per_chunk+projused[0],np.minimum((y + 1)*num_proj_per_chunk+projused[0],numangles)),sino=(sinoused[0],sinoused[1], sinoused[2]) )
                    else:
                        tomo, flat, dark, floc = dxchange.read_als_832h5(inputPath+filename,ind_tomo=range(projused[0],projused[1],projused[2]),sino=(y*num_sino_per_chunk+sinoused[0],np.minimum((y + 1)*num_sino_per_chunk+sinoused[0],numslices),1) )
            else:
                if axis=='proj':
                    start, end = y * num_proj_per_chunk, np.minimum((y + 1) * num_proj_per_chunk,numprojused)
                    tomo = dxchange.reader.read_hdf5(tempfilenames[curtemp],'/tmp/tmp',slc=((start,end,1),(0,numslices,1),(0,numrays,1))) #read in intermediate file
                else:
                    start, end = y * num_sino_per_chunk, np.minimum((y + 1) * num_sino_per_chunk,numsinoused)
                    tomo = dxchange.reader.read_hdf5(tempfilenames[curtemp],'/tmp/tmp',slc=((0,numangles,1),(start,end,1),(0,numrays,1)))
            dofunc = curfunc
            keepvalues = None
            while True: # Loop over operations to do in current chunking direction
                func_name = function_list[dofunc]
                newaxis = slice_dir[func_name]
                if newaxis != 'both' and newaxis != axis:
                    # We have to switch axis, so flush to disk
                    if y==0:
                        try:
                            os.remove(tempfilenames[1-curtemp])
                        except OSError:
                            pass
                    appendaxis = 1 if axis=='sino' else 0
                    dxchange.writer.write_hdf5(tomo,fname=tempfilenames[1-curtemp],gname='tmp',dname='tmp',overwrite=False,appendaxis=appendaxis) #writing intermediate file...
                    break
                print(func_name, end=" ")
                curtime = time.time()
                if func_name == 'remove_outlier1d':
                    tomo = tomo.astype(np.float32,copy=False)
                    remove_outlier1d(tomo, outlier_diff1D, size=outlier_size1D, out=tomo)
                if func_name == 'remove_outlier2d':
                    tomo = tomo.astype(np.float32,copy=False)
                    tomopy.remove_outlier(tomo, outlier_diff2D, size=outlier_size2D, axis=0, out=tomo)
                elif func_name == 'normalize_nf':
                    tomo = tomo.astype(np.float32,copy=False)
                    tomopy.normalize_nf(tomo, flat, dark, floc_independent, out=tomo) #use floc_independent b/c when you read file in proj chunks, you don't get the correct floc returned right now to use here.
                elif func_name == 'normalize':
                    tomo = tomo.astype(np.float32,copy=False)
                    tomopy.normalize(tomo, flat, dark, out=tomo)
                elif func_name == 'minus_log':
                    mx = np.float32(0.00000000000000000001)
                    ne.evaluate('where(tomo>mx, tomo, mx)', out=tomo)
                    tomopy.minus_log(tomo, out=tomo)
                elif func_name == 'beam_hardening':
                    loc_dict = {'a{}'.format(i):np.float32(val) for i,val in enumerate(BeamHardeningCoefficients)}
                    tomo = ne.evaluate('a0 + a1*tomo + a2*tomo**2 + a3*tomo**3 + a4*tomo**4 + a5*tomo**5', local_dict=loc_dict, out=tomo)
                elif func_name == 'remove_stripe_fw':
                    tomo = tomopy.remove_stripe_fw(tomo, sigma=ringSigma, level=ringLevel, pad=True, wname=ringWavelet)
                elif func_name == 'remove_stripe_ti':
                    tomo = tomopy.remove_stripe_ti(tomo, nblock=ringNBlock, alpha=ringAlpha)
                elif func_name == 'remove_stripe_sf':
                    tomo = tomopy.remove_stripe_sf(tomo, size=ringSize)
                elif func_name == 'correcttilt':
                    if tiltcenter_slice is None:
                        tiltcenter_slice = numslices/2.
                    if tiltcenter_det is None:
                        tiltcenter_det = tomo.shape[2]/2
                    new_center = tiltcenter_slice - 0.5 - sinoused[0]
                    center_det = tiltcenter_det - 0.5
                    
                    #add padding of 10 pixels, to be unpadded right after tilt correction. This makes the tilted image not have zeros at certain edges, which matters in cases where sample is bigger than the field of view. For the small amounts we are generally tilting the images, 10 pixels is sufficient.
#                    tomo = tomopy.pad(tomo, 2, npad=10, mode='edge')
#                    center_det = center_det + 10
                    
                    cntr = (center_det, new_center)
                    for b in range(tomo.shape[0]):
                        tomo[b] = st.rotate(tomo[b], correcttilt, center=cntr, preserve_range=True, order=1, mode='edge', clip=True) #center=None means image is rotated around its center; order=1 is default, order of spline interpolation
#                    tomo = tomo[:, :, 10:-10]    
                        
                elif func_name == 'do_360_to_180':
                    
                    # Keep values around for processing the next chunk in the list
                    keepvalues = [angularrange, numangles, projused, num_proj_per_chunk, numprojchunks, numprojused, numrays, anglelist]
                    
                    #why -.5 on one and not on the other?
                    if tomo.shape[0]%2>0:
                        tomo = sino_360_to_180(tomo[0:-1,:,:], overlap=int(np.round((tomo.shape[2]-cor-.5))*2), rotation='right')
                        angularrange = angularrange/2 - angularrange/(tomo.shape[0]-1)
                    else:
                        tomo = sino_360_to_180(tomo[:,:,:], overlap=int(np.round((tomo.shape[2]-cor))*2), rotation='right')
                        angularrange = angularrange/2
                    numangles = int(numangles/2)
                    projused = (0,numangles-1,1)
                    num_proj_per_chunk = np.minimum(chunk_proj,projused[1]-projused[0])
                    numprojchunks = (projused[1]-projused[0]-1)//num_proj_per_chunk+1
                    numprojused = (projused[1]-projused[0])//projused[2]
                    numrays = tomo.shape[2]
                    
                    anglelist = anglelist[:numangles]
                
                elif func_name == 'phase_retrieval':
                    tomo = tomopy.retrieve_phase(tomo, pixel_size=pxsize, dist=propagation_dist, energy=kev, alpha=alphaReg, pad=True)
                
                elif func_name == 'translation_correction':
                    tomo = linear_translation_correction(tomo,dx=xshift,dy=yshift,interpolation=False):
                    
                elif func_name == 'recon_mask':
                    tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')

                    if projIgnoreList is not None:
                        for badproj in projIgnoreList:
                            tomo[badproj] = 0

                    rec = tomopy.recon(tomo, anglelist, center=cor+npad, algorithm='gridrec', filter_name='butterworth', filter_par=[butterworth_cutoff, butterworth_order])
                    rec = rec[:, npad:-npad, npad:-npad]
                    rec /= pxsize  # convert reconstructed voxel values from 1/pixel to 1/cm
                    rec = tomopy.circ_mask(rec, 0)
                elif func_name == 'polar_ring':
                    rec = np.ascontiguousarray(rec, dtype=np.float32)
                    rec = tomopy.remove_ring(rec, theta_min=Rarc, rwidth=Rmaxwidth, thresh_max=Rtmax, thresh=Rthr, thresh_min=Rtmin,out=rec)
                elif func_name == 'castTo8bit':
                    rec = convert8bit(rec, cast8bit_min, cast8bit_max)
                elif func_name == 'bilateral_filter':
                    rec = pyF3D.run_BilateralFilter(rec, spatialRadius=bilateral_srad, rangeRadius=bilateral_rrad)
                elif func_name == 'write_output':
                    dxchange.write_tiff_stack(rec, fname=filenametowrite, start=y*num_sino_per_chunk + sinoused[0])
                print('(took {:.2f} seconds)'.format(time.time()-curtime))
                dofunc+=1
                if dofunc==len(function_list):
                    break
            if y<niter-1 and keepvalues: # Reset original values for next chunk
                angularrange, numangles, projused, num_proj_per_chunk, numprojchunks, numprojused, numrays, anglelist = keepvalues
                
        curtemp = 1 - curtemp
        curfunc = dofunc
        if curfunc==len(function_list):
            break
        axis = slice_dir[function_list[curfunc]]
    print("cleaning up temp files")
    for tmpfile in tempfilenames:
        try:
            os.remove(tmpfile)
        except OSError:
            pass
    print("End Time: "+time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()))
    print('It took {:.3f} s to process {}'.format(time.time()-start_time,inputPath+filename))
Пример #14
0
if __name__ == '__main__':
    ## Set path (without file suffix) to the micro-CT data to reconstruct.
    fname = 'data_dir/sample'

    ## Import Data.
    proj, flat, dark, theta = dx.exchange.read_aps_13bm(fname, format = 'netcdf4')

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

    ## Additional flat-field correction of raw data to negate need to mask.
    proj = tp.normalize_bg(proj, air = 10)

    ## Set rotation center.
    rot_center = tp.find_center_vo(proj)
    print('Center of rotation: ', rot_center)

    tp.minus_log(proj, out = proj)

    # Reconstruct object using Gridrec algorith.
    rec = tp.recon(proj, theta, center = rot_center, sinogram_order = False, algorithm = 'gridrec', filter_name = 'hann')
    rec = tp.remove_nan(rec)

    ## Writing data in netCDF3 .volume.
    ncfile = Dataset('filename.volume', 'w', format = 'NETCDF3_64BIT', clobber = True)
    NX = ncfile.createDimension('NX', rec.shape[2])
    NY = ncfile.createDimension('NY', rec.shape[1])
    NZ = ncfile.createDimension('NZ', rec.shape[0])
    volume = ncfile.createVariable('VOLUME', 'f4', ('NZ','NY','NX'))
    volume[:] = rec
Пример #15
0
if __name__ == '__main__':
    ## Set path (without file suffix) to the micro-CT data to reconstruct.
    fname = 'data_dir/sample'

    ## Import Data.
    proj, flat, dark, theta = dx.exchange.read_aps_13bm(fname,
                                                        format='netcdf4')

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

    ## Additional flat-field correction of raw data to negate need to mask.
    proj = tp.normalize_bg(proj, air=10)

    ## Set rotation center.
    rot_center = tp.find_center_vo(proj)
    print('Center of rotation: ', rot_center)

    tp.minus_log(proj, out=proj)

    # Reconstruct object using Gridrec algorith.
    rec = tp.recon(proj,
                   theta,
                   center=rot_center,
                   sinogram_order=False,
                   algorithm='gridrec',
                   filter_name='hann')
    rec = tp.remove_nan(rec)

    ## Writing data in netCDF3 .volume.
    ncfile = Dataset('filename.volume',