Ejemplo n.º 1
0
    def execute(self, input_dataobj, subpixel_accuracy, initual_value,
                output_dataobj):
        import tomopy
        projs = self.data[input_dataobj]
        if (projs is None):
            self.LogError('Please specific input Projections')
            return False

        if (len(projs.shape) != 3):
            self.LogError('The shape of Projections should been 3! here is ' +
                          str(projs.shape))
            return False

        dataobj = tomopy.find_center_pc(projs[0],
                                        projs[-1],
                                        tol=subpixel_accuracy,
                                        rotc_guess=initual_value)
        self.data[output_dataobj] = dataobj
        return True
def reconstruct(filename,inputPath="", outputPath="", COR=COR, doOutliers=doOutliers, outlier_diff=outlier_diff, outlier_size=outlier_size, doFWringremoval=doFWringremoval, ringSigma=ringSigma,ringLevel=ringLevel, ringWavelet=ringWavelet,pad_sino=pad_sino,  doPhaseRetrieval=doPhaseRetrieval, propagation_dist=propagation_dist, kev=kev,alphaReg=alphaReg, butterworthpars=butterworthpars, doPolarRing=doPolarRing,Rarc=Rarc, Rmaxwidth=Rmaxwidth, Rtmax=Rtmax, Rthr=Rthr, Rtmin=Rtmin, useAutoCOR=useAutoCOR, use360to180=use360to180, num_substacks=num_substacks,recon_slice=recon_slice):

	# Convert filename to list type if only one file name is given
	if type(filename) != list:
		filename=[filename]

	# If useAutoCor == true, a list of COR will be automatically calculated for all files
	# If a list of COR is given, only entries with boolean False will use automatic COR calculation
	if useAutoCOR==True or (len(COR) != len(filename)):
		logging.info('using auto COR for all input files')
		COR = [False]*len(filename)

	for x in range(len(filename)):
		logging.info('opening data set, checking metadata')

		fdata, gdata = read_als_832h5_metadata(inputPath[x]+filename[x]+'.h5')
		pxsize = float(gdata['pxsize'])/10.0 # convert from metadata (mm) to this script (cm)
		numslices = int(gdata['nslices'])

		# recon_slice == True, only center slice will be reconstructed
		# if integer is given, a specific 		
		if recon_slice != False:
			if (type(recon_slice) == int) and (recon_slice <= numslices):
				sinorange [recon_slice-1, recon_slice]
			else:
				sinorange = [numslices//2-1, numslices//2]
		else:
			sinorange = [0, numslices]

		# Calculate number of substacks (chunks)
		substacks = num_substacks #(sinorange[1]-sinorange[0]-1)//num_sino_per_substack+1

		if (sinorange[1]-sinorange[0]) >= substacks:
			num_sino_per_substack = (sinorange[1]-sinorange[0])//num_substacks
		else:
			num_sino_per_substack = 1

	
		firstcor, lastcor = 0, int(gdata['nangles'])-1
		projs, flat, dark, floc = dxchange.read_als_832h5(inputPath[x]+filename[x]+'.h5', ind_tomo=(firstcor, lastcor))
		projs = tomopy.normalize_nf(projs, flat, dark, floc)
		autocor = tomopy.find_center_pc(projs[0], projs[1], tol=0.25)


		if (type(COR[x]) == bool) or (COR[x]<0) or (COR[x]=='auto'):
			firstcor, lastcor = 0, int(gdata['nangles'])-1
			projs, flat, dark, floc = dxchange.read_als_832h5(inputPath[x]+filename[x]+'.h5', ind_tomo=(firstcor, lastcor))
			projs = tomopy.normalize_nf(projs, flat, dark, floc)
			cor = tomopy.find_center_pc(projs[0], projs[1], tol=0.25)
		else:
			cor = COR[x]

		logging.info('Dataset %s, has %d total slices, reconstructing slices %d through %d in %d substack(s), using COR: %f',filename[x], int(gdata['nslices']), sinorange[0], sinorange[1]-1, substacks, cor)
		
		for y in range(0, substacks):
			logging.info('Starting dataset %s (%d of %d), substack %d of %d',filename[x], x+1, len(filename), y+1, substacks)

			logging.info('Reading sinograms...')
			projs, flat, dark, floc = dxchange.read_als_832h5(inputPath[x]+filename[x]+'.h5', sino=(sinorange[0]+y*num_sino_per_substack, sinorange[0]+(y+1)*num_sino_per_substack, 1)) 

			logging.info('Doing remove outliers, norm (nearest flats), and -log...')
			if doOutliers:
				projs = tomopy.remove_outlier(projs, outlier_diff, size=outlier_size, axis=0)
				flat = tomopy.remove_outlier(flat, outlier_diff, size=outlier_size, axis=0)
			tomo = tomopy.normalize_nf(projs, flat, dark, floc)
			tomo = tomopy.minus_log(tomo, out=tomo) # in place logarithm 
		
			# Use padding to remove halo in reconstruction if present
			if pad_sino:
				npad = int(np.ceil(tomo.shape[2] * np.sqrt(2)) - tomo.shape[2])//2
				tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')
				cor_rec = cor + npad # account for padding
			else:
				cor_rec = cor
		
			if doFWringremoval:
				logging.info('Doing ring (Fourier-wavelet) function...')
				tomo = tomopy.remove_stripe_fw(tomo, sigma=ringSigma, level=ringLevel, pad=True, wname=ringWavelet)		

			if doPhaseRetrieval:
				logging.info('Doing Phase retrieval...')
				#tomo = tomopy.retrieve_phase(tomo, pixel_size=pxsize, dist=propagation_dist, energy=kev, alpha=alphaReg, pad=True)	
				tomo = tomopy.retrieve_phase(tomo, pixel_size=pxsize, dist=propagation_dist, energy=kev, alpha=alphaReg, pad=True)		

			logging.info('Doing recon (gridrec) function and scaling/masking, with cor %f...',cor_rec)
			rec = tomopy.recon(tomo, tomopy.angles(tomo.shape[0], 270, 90), center=cor_rec, algorithm='gridrec', filter_name='butterworth', filter_par=butterworthpars)
			#rec = tomopy.recon(tomo, tomopy.angles(tomo.shape[0], 180+angularrange/2, 180-angularrange/2), center=cor_rec, algorithm='gridrec', filter_name='butterworth', filter_par=butterworthpars)		
			rec /= pxsize  # intensity values in cm^-1
			if pad_sino:
				rec = tomopy.circ_mask(rec[:, npad:-npad, npad:-npad], 0)
			else:
				rec = tomopy.circ_mask(rec, 0, ratio=1.0, val=0.0)
			
			if doPolarRing:
				logging.info('Doing ring (polar mean filter) function...')
				rec = tomopy.remove_ring(rec, theta_min=Rarc, rwidth=Rmaxwidth, thresh_max=Rtmax, thresh=Rthr, thresh_min=Rtmin)

			logging.info('Writing reconstruction slices to %s', filename[x])
			#dxchange.write_tiff_stack(rec, fname=outputPath+'alpha'+str(alphaReg)+'/rec'+filename[x]+'/rec'+filename[x], start=sinorange[0]+y*num_sino_per_substack)
			dxchange.write_tiff_stack(rec, fname=outputPath + 'recon_'+filename[x]+'/recon_'+filename[x], start=sinorange[0]+y*num_sino_per_substack)
		logging.info('Reconstruction Complete: '+ filename[x])
Ejemplo n.º 3
0
def fast_tomo_recon(argv):
    """
    Reconstruct subset slices (sinograms) equally spaced within tomographic
    dataset
    """

    logger = logging.getLogger('fast_tomopy.fast_tomo_recon')

    # Parse arguments passed to function
    parser = argparse.ArgumentParser()
    parser.add_argument('-i',
                        '--input',
                        type=str,
                        help='path to input raw '
                        'dataset',
                        required=True)
    parser.add_argument('-o',
                        '--output-file',
                        type=str,
                        help='full path to h5 output '
                        'file',
                        default=os.path.join(os.getcwd(), "fast-tomopy.h5"))
    parser.add_argument('-sn',
                        '--sino-num',
                        type=int,
                        help='Number of slices '
                        'to reconstruct',
                        default=5)
    parser.add_argument('-a',
                        '--algorithm',
                        type=str,
                        help='Reconstruction'
                        ' algorithm',
                        default='gridrec',
                        choices=[
                            'art', 'bart', 'fbp', 'gridrec', 'mlem',
                            'ospml_hybrid', 'ospml_quad', 'pml_hybrid',
                            'pml_quad', 'sirt'
                        ])
    parser.add_argument('-c',
                        '--center',
                        type=float,
                        help='Center of rotation',
                        default=None)
    parser.add_argument('-fn',
                        '--filter-name',
                        type=str,
                        help='Name of filter'
                        ' used for reconstruction',
                        choices=[
                            'none', 'shepp', 'cosine', 'hann', 'hamming',
                            'ramlak', 'parzen', 'butterworth'
                        ],
                        default='butterworth')
    parser.add_argument('-rr',
                        '--ring-remove',
                        type=str,
                        help='Ring removal '
                        'method',
                        choices=['Octopus', 'Tomopy-FW', 'Tomopy-T'],
                        default='Tomopy-T')
    parser.add_argument('-lf',
                        '--log-file',
                        type=str,
                        help='log file name',
                        default='fast-tomopy.log')

    args = parser.parse_args()

    fh = logging.FileHandler(args.log_file)
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    if os.path.isdir(os.path.dirname(args.output_file)) is False:
        raise IOError(2, 'Directory of output file does not exist',
                      args.output_file)

    # Read file metadata
    logger.info('Reading input file metadata')
    fdata, gdata = read_als_832h5_metadata(args.input)
    proj_total = int(gdata['nangles'])
    last = proj_total - 1
    sino_total = int(gdata['nslices'])
    ray_total = int(gdata['nrays'])
    px_size = float(gdata['pxsize']) / 10  # cm

    # Set parameters for sinograms to read
    step = sino_total // (args.sino_num + 2)
    start = step
    end = step * (args.sino_num + 1)
    sino = (start, end, step)

    # Read full first and last projection to determine center of rotation
    if args.center is None:
        logger.info('Reading full first and last projection for COR')
        first_last, flats, darks, foobar = dx.read_als_832h5(args.input,
                                                             ind_tomo=(0,
                                                                       last))
        first_last = tomopy.normalize(first_last, flats, darks)
        args.center = tomopy.find_center_pc(first_last[0, :, :],
                                            first_last[1, :, :],
                                            tol=0.1)
        logger.info('Detected center: %f', args.center)

    # Read and normalize raw sinograms
    logger.info('Reading raw data')
    tomo, flats, darks, foobar = dx.read_als_832h5(args.input, sino=sino)
    logger.info('Normalizing raw data')
    tomo = tomopy.normalize(tomo, flats, darks)
    tomo = tomopy.minus_log(tomo)

    # Remove stripes from sinograms (remove rings)
    logger.info('Preprocessing normalized data')
    if args.ring_remove == 'Tomopy-FW':
        logger.info('Removing stripes from sinograms with %s',
                    args.ring_remove)
        tomo = tomopy.remove_stripe_fw(tomo)
    elif args.ring_remove == 'Tomopy-T':
        logger.info('Removing stripes from sinograms with %s',
                    args.ring_remove)
        tomo = tomopy.remove_stripe_ti(tomo)

    # Pad sinograms with edge values
    npad = int(np.ceil(ray_total * np.sqrt(2)) - ray_total) // 2
    tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')
    args.center += npad  # account for padding

    filter_name = np.array(args.filter_name, dtype=(str, 16))
    theta = tomopy.angles(proj_total, 270, 90)

    logger.info('Reconstructing normalized data')
    # Reconstruct sinograms
    # rec = tomopy.minus_log(tomo, out=tomo)
    rec = tomopy.recon(tomo,
                       theta,
                       center=args.center,
                       algorithm=args.algorithm,
                       filter_name=filter_name)
    rec = tomopy.circ_mask(rec[:, npad:-npad, npad:-npad], 0)
    rec = rec / px_size

    # Remove rings from reconstruction
    if args.ring_remove == 'Octopus':
        logger.info('Removing rings from reconstructions with %s',
                    args.ring_remove)
        thresh = float(gdata['ring_threshold'])
        thresh_max = float(gdata['upp_ring_value'])
        thresh_min = float(gdata['low_ring_value'])
        theta_min = int(gdata['max_arc_length'])
        rwidth = int(gdata['max_ring_size'])
        rec = tomopy.remove_rings(rec,
                                  center_x=args.center,
                                  thresh=thresh,
                                  thresh_max=thresh_max,
                                  thresh_min=thresh_min,
                                  theta_min=theta_min,
                                  rwidth=rwidth)

    # Write reconstruction data to new hdf5 file
    fdata['stage'] = 'fast-tomopy'
    fdata['stage_flow'] = '/raw/' + fdata['stage']
    fdata['stage_version'] = 'fast-tomopy-0.1'
    # Generate a new uuid based on host ID and current time
    fdata['uuid'] = str(uuid.uuid1())

    gdata['Reconstruction_Type'] = 'tomopy-gridrec'
    gdata['ring_removal_method'] = args.ring_remove
    gdata['rfilter'] = args.filter_name

    logger.info('Writing reconstructed data to h5 file')
    write_als_832h5(rec, args.input, fdata, gdata, args.output_file, step)

    return
Ejemplo n.º 4
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))
Ejemplo n.º 5
0
 def evaluate(self):
     self.center.value = tomopy.find_center_pc(self.proj1.value,
                                               self.proj2.value,
                                               tol=self.tol.value)
Ejemplo n.º 6
0
def fast_tomo_recon(argv):
    """
    Reconstruct subset slices (sinograms) equally spaced within tomographic
    dataset
    """

    logger = logging.getLogger("fast_tomopy.fast_tomo_recon")

    # Parse arguments passed to function
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input", type=str, help="path to input raw " "dataset", required=True)
    parser.add_argument(
        "-o",
        "--output-file",
        type=str,
        help="full path to h5 output " "file",
        default=os.path.join(os.getcwd(), "fast-tomopy.h5"),
    )
    parser.add_argument("-sn", "--sino-num", type=int, help="Number of slices " "to reconstruct", default=5)
    parser.add_argument(
        "-a",
        "--algorithm",
        type=str,
        help="Reconstruction" " algorithm",
        default="gridrec",
        choices=[
            "art",
            "bart",
            "fbp",
            "gridrec",
            "mlem",
            "ospml_hybrid",
            "ospml_quad",
            "pml_hybrid",
            "pml_quad",
            "sirt",
        ],
    )
    parser.add_argument("-c", "--center", type=float, help="Center of rotation", default=None)
    parser.add_argument(
        "-fn",
        "--filter-name",
        type=str,
        help="Name of filter" " used for reconstruction",
        choices=["none", "shepp", "cosine", "hann", "hamming", "ramlak", "parzen", "butterworth"],
        default="butterworth",
    )
    parser.add_argument(
        "-rr",
        "--ring-remove",
        type=str,
        help="Ring removal " "method",
        choices=["Octopus", "Tomopy-FW", "Tomopy-T"],
        default="Tomopy-T",
    )
    parser.add_argument("-lf", "--log-file", type=str, help="log file name", default="fast-tomopy.log")

    args = parser.parse_args()

    fh = logging.FileHandler(args.log_file)
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    if os.path.isdir(os.path.dirname(args.output_file)) is False:
        raise IOError(2, "Directory of output file does not exist", args.output_file)

    # Read file metadata
    logger.info("Reading input file metadata")
    fdata, gdata = read_als_832h5_metadata(args.input)
    proj_total = int(gdata["nangles"])
    last = proj_total - 1
    sino_total = int(gdata["nslices"])
    ray_total = int(gdata["nrays"])
    px_size = float(gdata["pxsize"]) / 10  # cm

    # Set parameters for sinograms to read
    step = sino_total // (args.sino_num + 2)
    start = step
    end = step * (args.sino_num + 1)
    sino = (start, end, step)

    # Read full first and last projection to determine center of rotation
    if args.center is None:
        logger.info("Reading full first and last projection for COR")
        first_last, flats, darks, floc = tomopy.read_als_832h5(args.input, ind_tomo=(0, last))
        first_last = tomopy.normalize(first_last, flats, darks)
        args.center = tomopy.find_center_pc(first_last[0, :, :], first_last[1, :, :], tol=0.1)
        logger.info("Detected center: %f", args.center)

    # Read and normalize raw sinograms
    logger.info("Reading raw data")
    tomo, flats, darks, floc = tomopy.read_als_832h5(args.input, sino=sino)
    logger.info("Normalizing raw data")
    tomo = tomopy.normalize_nf(tomo, flats, darks, floc)

    # Remove stripes from sinograms (remove rings)
    logger.info("Preprocessing normalized data")
    if args.ring_remove == "Tomopy-FW":
        logger.info("Removing stripes from sinograms with %s", args.ring_remove)
        tomo = tomopy.remove_stripe_fw(tomo)
    elif args.ring_remove == "Tomopy-T":
        logger.info("Removing stripes from sinograms with %s", args.ring_remove)
        tomo = tomopy.remove_stripe_ti(tomo)

    # Pad sinograms with edge values
    npad = int(np.ceil(ray_total * np.sqrt(2)) - ray_total) // 2
    tomo = tomopy.pad(tomo, 2, npad=npad, mode="edge")
    args.center += npad  # account for padding

    filter_name = np.array(args.filter_name, dtype=(str, 16))
    theta = tomopy.angles(proj_total, 270, 90)

    logger.info("Reconstructing normalized data")
    # Reconstruct sinograms
    # rec = tomopy.minus_log(tomo, out=tomo)
    rec = tomopy.recon(
        tomo, theta, center=args.center, emission=False, algorithm=args.algorithm, filter_name=filter_name
    )
    rec = tomopy.circ_mask(rec[:, npad:-npad, npad:-npad], 0)
    rec = rec / px_size

    # Remove rings from reconstruction
    if args.ring_remove == "Octopus":
        logger.info("Removing rings from reconstructions with %s", args.ring_remove)
        thresh = float(gdata["ring_threshold"])
        thresh_max = float(gdata["upp_ring_value"])
        thresh_min = float(gdata["low_ring_value"])
        theta_min = int(gdata["max_arc_length"])
        rwidth = int(gdata["max_ring_size"])
        rec = tomopy.remove_rings(
            rec,
            center_x=args.center,
            thresh=thresh,
            thresh_max=thresh_max,
            thresh_min=thresh_min,
            theta_min=theta_min,
            rwidth=rwidth,
        )

    # Write reconstruction data to new hdf5 file
    fdata["stage"] = "fast-tomopy"
    fdata["stage_flow"] = "/raw/" + fdata["stage"]
    fdata["stage_version"] = "fast-tomopy-0.1"
    # Generate a new uuid based on host ID and current time
    fdata["uuid"] = str(uuid.uuid1())

    gdata["Reconstruction_Type"] = "tomopy-gridrec"
    gdata["ring_removal_method"] = args.ring_remove
    gdata["rfilter"] = args.filter_name

    logger.info("Writing reconstructed data to h5 file")
    write_als_832h5(rec, args.input, fdata, gdata, args.output_file, step)

    return
Ejemplo n.º 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
    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))
Ejemplo n.º 8
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
		
		#projs, flat, dark, floc = dxchange.read_als_832h5(idirectory+iname[x]+'.h5', ind_tomo=(firstcor, lastcor))
		projs, flat, dark, flocOld = dxchange.read_als_832h5(idirectory+iname[x]+'.h5', ind_tomo=(firstcor, lastcor))
		

		if specialBakCrop[x]>0:
			num_per_flat = flat.shape[0]//original_floc_length
			flat = flat[0:-specialBakCrop[x]*num_per_flat]
			#logging.info('length flats: %d',flat.shape[0])
		
		if useNormalize_nf:
			projs = tomopy.normalize_nf(projs, flat, dark, floc)
		else:
			projs = tomopy.normalize(projs, flat, dark)
			
		cor = tomopy.find_center_pc(projs[0], projs[1], tol=0.25)
	else:
		cor = fixedcor[x]
	logging.info('Center of rotation: %f', cor)
	logging.info('recon slices %d through %d in %d chunk(s)', sinorange[0], sinorange[1]-1, chunks)
	
#	for alphaReg in thealphavalues:
	for y in range(0, chunks):
		

		logging.info('dataset %d/%d, chunk %d/%d (%d-%d)', x+1,len(iname), y+1, chunks,sinorange[0]+y*num_sino_per_chunk,sinorange[0]+(y+1)*num_sino_per_chunk-1)

		logging.info('Reading data')
		#projs, flat, dark, floc = dxchange.read_als_832h5(idirectory+iname[x]+'.h5', sino=(sinorange[0]+y*num_sino_per_chunk, sinorange[0]+(y+1)*num_sino_per_chunk, 1)) 

		if recon_centralSlice:
def reconstruct(filename,
                inputPath="",
                outputPath="",
                COR=COR,
                doOutliers=doOutliers,
                outlier_diff=outlier_diff,
                outlier_size=outlier_size,
                doFWringremoval=doFWringremoval,
                ringSigma=ringSigma,
                ringLevel=ringLevel,
                ringWavelet=ringWavelet,
                pad_sino=pad_sino,
                doPhaseRetrieval=doPhaseRetrieval,
                propagation_dist=propagation_dist,
                kev=kev,
                alphaReg=alphaReg,
                butterworthpars=butterworthpars,
                doPolarRing=doPolarRing,
                Rarc=Rarc,
                Rmaxwidth=Rmaxwidth,
                Rtmax=Rtmax,
                Rthr=Rthr,
                Rtmin=Rtmin,
                useAutoCOR=useAutoCOR,
                use360to180=use360to180,
                num_substacks=num_substacks,
                recon_slice=recon_slice):

    # Convert filename to list type if only one file name is given
    if type(filename) != list:
        filename = [filename]

    # If useAutoCor == true, a list of COR will be automatically calculated for all files
    # If a list of COR is given, only entries with boolean False will use automatic COR calculation
    if useAutoCOR == True or (len(COR) != len(filename)):
        logging.info('using auto COR for all input files')
        COR = [False] * len(filename)

    for x in range(len(filename)):
        logging.info('opening data set, checking metadata')

        fdata, gdata = read_als_832h5_metadata(inputPath[x] + filename[x] +
                                               '.h5')
        pxsize = float(
            gdata['pxsize']
        ) / 10.0  # convert from metadata (mm) to this script (cm)
        numslices = int(gdata['nslices'])

        # recon_slice == True, only center slice will be reconstructed
        # if integer is given, a specific
        if recon_slice != False:
            if (type(recon_slice) == int) and (recon_slice <= numslices):
                sinorange[recon_slice - 1, recon_slice]
            else:
                sinorange = [numslices // 2 - 1, numslices // 2]
        else:
            sinorange = [0, numslices]

        # Calculate number of substacks (chunks)
        substacks = num_substacks  #(sinorange[1]-sinorange[0]-1)//num_sino_per_substack+1

        if (sinorange[1] - sinorange[0]) >= substacks:
            num_sino_per_substack = (sinorange[1] -
                                     sinorange[0]) // num_substacks
        else:
            num_sino_per_substack = 1

        firstcor, lastcor = 0, int(gdata['nangles']) - 1
        projs, flat, dark, floc = dxchange.read_als_832h5(
            inputPath[x] + filename[x] + '.h5', ind_tomo=(firstcor, lastcor))
        projs = tomopy.normalize_nf(projs, flat, dark, floc)
        autocor = tomopy.find_center_pc(projs[0], projs[1], tol=0.25)

        if (type(COR[x]) == bool) or (COR[x] < 0) or (COR[x] == 'auto'):
            firstcor, lastcor = 0, int(gdata['nangles']) - 1
            projs, flat, dark, floc = dxchange.read_als_832h5(
                inputPath[x] + filename[x] + '.h5',
                ind_tomo=(firstcor, lastcor))
            projs = tomopy.normalize_nf(projs, flat, dark, floc)
            cor = tomopy.find_center_pc(projs[0], projs[1], tol=0.25)
        else:
            cor = COR[x]

        logging.info(
            'Dataset %s, has %d total slices, reconstructing slices %d through %d in %d substack(s), using COR: %f',
            filename[x], int(gdata['nslices']), sinorange[0], sinorange[1] - 1,
            substacks, cor)

        for y in range(0, substacks):
            logging.info('Starting dataset %s (%d of %d), substack %d of %d',
                         filename[x], x + 1, len(filename), y + 1, substacks)

            logging.info('Reading sinograms...')
            projs, flat, dark, floc = dxchange.read_als_832h5(
                inputPath[x] + filename[x] + '.h5',
                sino=(sinorange[0] + y * num_sino_per_substack,
                      sinorange[0] + (y + 1) * num_sino_per_substack, 1))

            logging.info(
                'Doing remove outliers, norm (nearest flats), and -log...')
            if doOutliers:
                projs = tomopy.remove_outlier(projs,
                                              outlier_diff,
                                              size=outlier_size,
                                              axis=0)
                flat = tomopy.remove_outlier(flat,
                                             outlier_diff,
                                             size=outlier_size,
                                             axis=0)
            tomo = tomopy.normalize_nf(projs, flat, dark, floc)
            tomo = tomopy.minus_log(tomo, out=tomo)  # in place logarithm

            # Use padding to remove halo in reconstruction if present
            if pad_sino:
                npad = int(
                    np.ceil(tomo.shape[2] * np.sqrt(2)) - tomo.shape[2]) // 2
                tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')
                cor_rec = cor + npad  # account for padding
            else:
                cor_rec = cor

            if doFWringremoval:
                logging.info('Doing ring (Fourier-wavelet) function...')
                tomo = tomopy.remove_stripe_fw(tomo,
                                               sigma=ringSigma,
                                               level=ringLevel,
                                               pad=True,
                                               wname=ringWavelet)

            if doPhaseRetrieval:
                logging.info('Doing Phase retrieval...')
                #tomo = tomopy.retrieve_phase(tomo, pixel_size=pxsize, dist=propagation_dist, energy=kev, alpha=alphaReg, pad=True)
                tomo = tomopy.retrieve_phase(tomo,
                                             pixel_size=pxsize,
                                             dist=propagation_dist,
                                             energy=kev,
                                             alpha=alphaReg,
                                             pad=True)

            logging.info(
                'Doing recon (gridrec) function and scaling/masking, with cor %f...',
                cor_rec)
            rec = tomopy.recon(tomo,
                               tomopy.angles(tomo.shape[0], 270, 90),
                               center=cor_rec,
                               algorithm='gridrec',
                               filter_name='butterworth',
                               filter_par=butterworthpars)
            #rec = tomopy.recon(tomo, tomopy.angles(tomo.shape[0], 180+angularrange/2, 180-angularrange/2), center=cor_rec, algorithm='gridrec', filter_name='butterworth', filter_par=butterworthpars)
            rec /= pxsize  # intensity values in cm^-1
            if pad_sino:
                rec = tomopy.circ_mask(rec[:, npad:-npad, npad:-npad], 0)
            else:
                rec = tomopy.circ_mask(rec, 0, ratio=1.0, val=0.0)

            if doPolarRing:
                logging.info('Doing ring (polar mean filter) function...')
                rec = tomopy.remove_ring(rec,
                                         theta_min=Rarc,
                                         rwidth=Rmaxwidth,
                                         thresh_max=Rtmax,
                                         thresh=Rthr,
                                         thresh_min=Rtmin)

            logging.info('Writing reconstruction slices to %s', filename[x])
            #dxchange.write_tiff_stack(rec, fname=outputPath+'alpha'+str(alphaReg)+'/rec'+filename[x]+'/rec'+filename[x], start=sinorange[0]+y*num_sino_per_substack)
            dxchange.write_tiff_stack(rec,
                                      fname=outputPath + 'recon_' +
                                      filename[x] + '/recon_' + filename[x],
                                      start=sinorange[0] +
                                      y * num_sino_per_substack)
        logging.info('Reconstruction Complete: ' + filename[x])
logger = logging.getLogger(__name__)

try:
    shift_grid = tomosaic.util.file2grid("shifts.txt")
    shift_grid = tomosaic.absolute_shift_grid(shift_grid, file_grid)
except:
    print('Refined shift is not provided. Using pre-set shift values. ')
    shift_grid = tomosaic.start_shift_grid(file_grid, x_shift, y_shift)
print(shift_grid)

if center_st is None:
    pano_list = glob.glob(os.path.join('preview_panos', '*_norm.tiff'))
    pano_list.sort()
    img1 = dxchange.read_tiff(pano_list[0])
    img2 = dxchange.read_tiff(pano_list[-1])
    center_init = tomopy.find_center_pc(np.squeeze(img1), np.squeeze(img2))
    print('Phase correlation estimate: {}'.format(center_init))
    center_st = center_init - 5
    center_end = center_init + 5
    # write current center into center_pos.txt file
    np.savetxt(
        'center_pos.txt',
        np.vstack([range(row_st, row_end),
                   [center_init] * (row_end - row_st)]).transpose(),
        fmt=['%d', '%.1f'])

shift_grid = shift_grid / ds
in_tile_pos = in_tile_pos / ds

t0 = time.time()
if mode == 'merged':
Ejemplo n.º 12
0
def fast_tomo_recon(argv):
    """
    Reconstruct subset slices (sinograms) equally spaced within tomographic
    dataset
    """

    logger = logging.getLogger('fast_tomopy.fast_tomo_recon')

    # Parse arguments passed to function
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input', type=str, help='path to input raw '
                        'dataset', required=True)
    parser.add_argument('-o', '--output-file', type=str, help='full path to h5 output '
                        'file', default=os.path.join(os.getcwd(), "fast-tomopy.h5"))
    parser.add_argument('-sn', '--sino-num', type=int, help='Number of slices '
                        'to reconstruct', default=5)
    parser.add_argument('-a', '--algorithm', type=str, help='Reconstruction'
                        ' algorithm', default='gridrec',
                        choices=['art', 'bart', 'fbp', 'gridrec', 'mlem',
                                 'ospml_hybrid', 'ospml_quad', 'pml_hybrid',
                                 'pml_quad', 'sirt'])
    parser.add_argument('-c', '--center', type=float, help='Center of rotation',
                        default=None)
    parser.add_argument('-fn', '--filter-name', type=str, help='Name of filter'
                        ' used for reconstruction',
                        choices=['none', 'shepp', 'cosine', 'hann', 'hamming',
                                 'ramlak', 'parzen', 'butterworth'],
                        default='butterworth')
    parser.add_argument('-rr', '--ring-remove', type=str, help='Ring removal '
                        'method', choices=['Octopus', 'Tomopy-FW', 'Tomopy-T'],
                        default='Tomopy-FW')
    parser.add_argument('-lf', '--log-file', type=str, help='log file name',
                        default='fast-tomopy.log')

    args = parser.parse_args()

    fh = logging.FileHandler(args.log_file)
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    if os.path.isdir(os.path.dirname(args.output_file)) is False:
        raise IOError(2, 'Directory of output file does not exist', args.output_file)

    # Read file metadata
    logger.info('Reading input file metadata')
    fdata, gdata = tomopy.read_als_832h5_metadata(args.input)
    proj_total = int(gdata['nangles'])
    last = proj_total - 1
    sino_total = int(gdata['nslices'])
    ray_total = int(gdata['nrays'])
    px_size = float(gdata['pxsize'])/10  # cm

    # Set parameters for sinograms to read
    step = sino_total // (args.sino_num + 2)
    start = step
    end = step*(args.sino_num + 1)
    sino = (start, end, step)

    # Read full first and last projection to determine center of rotation
    if args.center is None:
        logger.info('Reading full first and last projection for COR')
        first_last, flats, darks, floc = tomopy.read_als_832h5(args.input,
                                                               ind_tomo=(0, last))
        first_last = tomopy.normalize_nf(first_last, flats, darks, floc)
        args.center = tomopy.find_center_pc(first_last[0, :, :],
                                            first_last[1, :, :], tol=0.1)
        logger.info('Detected center: %f', args.center)

    # Read and normalize raw sinograms
    logger.info('Reading raw data')
    tomo, flats, darks, floc = tomopy.read_als_832h5(args.input, sino=sino)
    logger.info('Normalizing raw data')
    tomo = tomopy.normalize_nf(tomo, flats, darks, floc)

    # Remove stripes from sinograms (remove rings)
    logger.info('Preprocessing normalized data')
    if args.ring_remove == 'Tomopy-FW':
        logger.info('Removing stripes from sinograms with %s',
                    args.ring_remove)
        tomo = tomopy.remove_stripe_fw(tomo)
    elif args.ring_remove == 'Tomopy-T':
        logger.info('Removing stripes from sinograms with %s',
                    args.ring_remove)
        tomo = tomopy.remove_stripe_ti(tomo)

    # Pad sinograms with edge values
    npad = int(np.ceil(ray_total*np.sqrt(2)) - ray_total)//2
    tomo = tomopy.pad(tomo, 2, npad=npad, mode='edge')
    args.center += npad # account for padding

    filter_name = np.array(args.filter_name, dtype=(str, 16))
    theta = tomopy.angles(tomo.shape[0], 270, 90)

    logger.info('Reconstructing normalized data')
    # Reconstruct sinograms
    rec = tomopy.recon(tomo, theta, center=args.center, emission=False,
                       algorithm=args.algorithm, filter_name=filter_name)
    rec = tomopy.circ_mask(rec[:, npad:-npad, npad:-npad], 0)
    rec = rec/px_size

    # Remove rings from reconstruction
    if args.ring_remove == 'Octopus':
        logger.info('Removing rings from reconstructions with %s',
                    args.ring_remove)
        thresh = float(gdata['ring_threshold'])
        thresh_max = float(gdata['upp_ring_value'])
        thresh_min = float(gdata['low_ring_value'])
        theta_min = int(gdata['max_arc_length'])
        rwidth = int(gdata['max_ring_size'])
        rec = tomopy.remove_rings(rec, center_x=args.center, thresh=thresh,
                                  thresh_max=thresh_max, thresh_min=thresh_min,
                                  theta_min=theta_min, rwidth=rwidth)

    # Write reconstruction data to new hdf5 file
    fdata['stage'] = 'fast-tomopy'
    fdata['stage_flow'] = '/raw/' + fdata['stage']
    fdata['stage_version'] = 'fast-tomopy-0.1'
    # WHAT ABOUT uuid ????? Who asigns this???
    del fdata['uuid']  # I'll get rid of it altogether then...

    gdata['Reconstruction_Type'] = 'tomopy-gridrec'
    gdata['ring_removal_method'] = args.ring_remove
    gdata['rfilter'] = args.filter_name

    logger.info('Writing reconstructed data to h5 file')
    write_als_832h5(rec, args.input, fdata, gdata, args.output_file, step)

    return
Ejemplo n.º 13
0
    print('Create & Cleanup destination folder...')
    # create output folder if not exist
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    else:
        # clean folder if requested
        if clean_up_folder:
            filelist = os.listdir(outpath)
            for files in filelist:
                os.remove(os.path.join(outpath, files))

# debug
#dxwriter.write_tiff_stack(proj[:,:,:], fname= outpath + 'sinogram')

    if rec_type != 'full':
        cen = tomopy.find_center_pc(proj[0], proj[900],
                                    tol=0.5)  # for theta step = 0.2
        # cen = tomopy.find_center_pc(proj[0], proj[720], tol=0.5)    # for theta step = 0.25
        print("Expected rotation center: ", cen - proj.shape[2] / 2)

        #cv2.namedWindow('Check Proj', cv2.WINDOW_NORMAL)
        #cv2.selectROI('Check Proj', proj[:,0,:], True)

        print('Do 3 slices, ', list(range(sino[0], sino[1], sino[2])),
              ', to find Rot center')
        print(postrecroi)
        if postrecroi != None:
            recdimx = postrecroi[2]
            recdimy = postrecroi[3]
        else:
            recdimx = abs(proj.shape[2])
            recdimy = abs(proj.shape[2])