Ejemplo n.º 1
0
def transform_scalars(dataset, resampling_factor=[1, 1, 1]):
    """Resample dataset"""

    from tomviz import utils
    import scipy.ndimage
    import numpy as np

    array = utils.get_array(dataset)

    # Transform the dataset.
    result_shape = utils.zoom_shape(array, resampling_factor)
    result = np.empty(result_shape, array.dtype, order='F')
    scipy.ndimage.interpolation.zoom(array, resampling_factor, output=result)

    # Set the result as the new scalars.
    utils.set_array(dataset, result)

    # Update tilt angles if dataset is a tilt series.
    if resampling_factor[2] != 1:
        try:
            tilt_angles = utils.get_tilt_angles(dataset)

            result_shape = utils.zoom_shape(tilt_angles, resampling_factor[2])
            result = np.empty(result_shape, array.dtype, order='F')
            scipy.ndimage.interpolation.zoom(tilt_angles,
                                             resampling_factor[2],
                                             output=result)
            utils.set_tilt_angles(dataset, result)
        except:  # noqa
            # TODO What exception are we ignoring?
            pass
Ejemplo n.º 2
0
    def transform_scalars(self, dataset, N=25):
        """Add Poisson noise to tilt images"""
        self.progress.maximum = 1

        tiltSeries = utils.get_array(dataset).astype(float)
        if tiltSeries is None:
            raise RuntimeError("No scalars found!")

        Ndata = tiltSeries.shape[0] * tiltSeries.shape[1]

        self.progress.maximum = tiltSeries.shape[2]
        step = 0
        for i in range(tiltSeries.shape[2]):
            if self.canceled:
                return

            tiltImage = tiltSeries[:, :, i].copy()
            tiltImage = tiltImage / np.sum(tiltSeries[:, :, i]) * (Ndata * N)
            tiltImage = np.random.poisson(tiltImage)
            tiltImage = tiltImage * np.sum(tiltSeries[:, :, i]) / (Ndata * N)

            tiltSeries[:, :, i] = tiltImage.copy()
            step += 1
            self.progress.value = step

        utils.set_array(dataset, tiltSeries)
Ejemplo n.º 3
0
def transform_scalars(dataset):
    """Downsample volume by a factor of 2"""

    from tomviz import utils
    import scipy.ndimage
    import numpy as np

    array = utils.get_array(dataset)

    # Downsample the dataset x2 using order 1 spline (linear)
    # Calculate out array shape
    zoom = (0.5, 0.5, 0.5)
    result_shape = utils.zoom_shape(array, zoom)
    result = np.empty(result_shape, array.dtype, order='F')
    scipy.ndimage.interpolation.zoom(array, zoom,
                                     output=result, order=1,
                                     mode='constant', cval=0.0,
                                     prefilter=False)

    # Set the result as the new scalars.
    utils.set_array(dataset, result)

    # Update tilt angles if dataset is a tilt series.
    try:
        tilt_angles = utils.get_tilt_angles(dataset)
        result_shape = utils.zoom_shape(tilt_angles, 0.5)
        result = np.empty(result_shape, array.dtype, order='F')
        tilt_angles = scipy.ndimage.interpolation.zoom(tilt_angles, 0.5,
                                                       output=result)
        utils.set_tilt_angles(dataset, result)
    except: # noqa
        # TODO What exception are we ignoring?
        pass
Ejemplo n.º 4
0
def transform_scalars(dataset):
    """Downsample tilt images by a factor of 2"""

    from tomviz import utils
    import scipy.ndimage
    import numpy as np
    import warnings

    array = utils.get_array(dataset)

    zoom = (0.5, 0.5, 1)
    result_shape = utils.zoom_shape(array, zoom)
    result = np.empty(result_shape, array.dtype, order='F')
    # Downsample the dataset x2 using order 1 spline (linear)
    warnings.filterwarnings('ignore', '.*output shape of zoom.*')
    scipy.ndimage.interpolation.zoom(array,
                                     zoom,
                                     output=result,
                                     order=1,
                                     mode='constant',
                                     cval=0.0,
                                     prefilter=False)

    # Set the result as the new scalars.
    utils.set_array(dataset, result)
Ejemplo n.º 5
0
def transform_scalars(dataset, SHIFT=None, rotation_angle=90.0):
    from tomviz import utils
    from scipy import ndimage
    import numpy as np

    data_py = utils.get_array(dataset) # Get data as numpy array.

    if data_py is None: #Check if data exists
        raise RuntimeError("No data array found!")
    if SHIFT is None:
        SHIFT = np.zeros(len(data_py.shape), dtype=np.int)
    data_py_return = np.empty_like(data_py)
    ndimage.interpolation.shift(data_py, SHIFT, order=0, output=data_py_return)

    rotation_axis = 2 # This operator always assumes the rotation axis is Z
    if rotation_angle == []: # If tilt angle not given, assign it to 90 degrees.
        rotation_angle = 90

    axis1 = (rotation_axis + 1) % 3
    axis2 = (rotation_axis + 2) % 3
    axes = (axis1, axis2)
    shape = utils.rotate_shape(data_py_return, rotation_angle, axes=axes)
    data_py_return2 = np.empty(shape, data_py_return.dtype, order='F')
    ndimage.interpolation.rotate(
        data_py_return, rotation_angle, output=data_py_return2, axes=axes)

    utils.set_array(dataset, data_py_return2)
Ejemplo n.º 6
0
    def transform_scalars(self, dataset):
        """Automatically align tilt images by center of mass method"""
        self.progress.maximum = 1

        tiltSeries = utils.get_array(dataset).astype(float)

        self.progress.maximum = tiltSeries.shape[2]
        step = 1

        offsets = np.zeros((tiltSeries.shape[2], 2))

        for i in range(tiltSeries.shape[2]):
            if self.canceled:
                return
            self.progress.message = 'Processing tilt image No.%d/%d' % (
                i + 1, tiltSeries.shape[2])

            offsets[i, :], tiltSeries[:, :, i] = centerOfMassAlign(
                tiltSeries[:, :, i]
            )

            step += 1
            self.progress.value = step

        utils.set_array(dataset, tiltSeries)

        # Create a spreadsheet data set from table data
        column_names = ["X Offset", "Y Offset"]
        offsetsTable = utils.make_spreadsheet(column_names, offsets)
        # Set up dictionary to return operator results
        returnValues = {}
        returnValues["alignments"] = offsetsTable
        return returnValues
Ejemplo n.º 7
0
def transform_scalars(dataset):
    '''For each tilt image, the method uses average pixel value of selected region
      as the background level and subtracts it from the image.'''
    '''It does NOT set negative pixels to zero.'''

    from tomviz import utils
    import numpy as np

    #----USER SPECIFIED VARIABLES-----#
    ###XRANGE###
    ###YRANGE###
    ###ZRANGE###
    #---------------------------------#

    data_bs = utils.get_array(dataset)  # Get data as numpy array.

    data_bs = data_bs.astype(np.float32)  # Change tilt series type to float.

    if data_bs is None:  #Check if data exists
        raise RuntimeError("No data array found!")

    for i in range(ZRANGE[0], ZRANGE[1]):
        a = data_bs[:, :, i] - np.average(data_bs[XRANGE[0]:XRANGE[1],
                                                  YRANGE[0]:YRANGE[1], i])
        data_bs[:, :, i] = a

    utils.set_array(dataset, data_bs)
Ejemplo n.º 8
0
def transform_scalars(dataset, rotation_angle=90.0, rotation_axis=0):

    from tomviz import utils
    import numpy as np
    from scipy import ndimage

    data_py = utils.get_array(dataset)  #get data as numpy array

    if data_py is None:  #Check if data exists
        raise RuntimeError("No data array found!")

    if rotation_axis == []:  #If tilt axis is not given, assign one.
        # Find the smallest array dimension, assume it is the tilt angle axis.
        if data_py.ndim >= 2:
            rotation_axis = np.argmin(data_py.shape)
        else:
            raise RuntimeError("Data Array is not 2 or 3 dimensions!")

    if rotation_angle == []:  # If tilt angle not given, assign it to 90 degrees.
        rotation_angle = 90

    print('Rotating Dataset...')

    axis1 = (rotation_axis + 1) % 3
    axis2 = (rotation_axis + 2) % 3
    data_py_return = ndimage.interpolation.rotate(data_py,
                                                  rotation_angle,
                                                  axes=(axis1, axis2))

    utils.set_array(dataset, data_py_return)
    print('Rotation Complete')
Ejemplo n.º 9
0
def transform_scalars(dataset):
    """Downsample volume by a factor of 2"""

    from tomviz import utils
    import scipy.ndimage

    array = utils.get_array(dataset)

    # Downsample the dataset x2 using order 1 spline (linear)
    result = scipy.ndimage.interpolation.zoom(array, (0.5, 0.5, 0.5),
                                              output=None,
                                              order=1,
                                              mode='constant',
                                              cval=0.0,
                                              prefilter=False)

    # Set the result as the new scalars.
    utils.set_array(dataset, result)

    # Update tilt angles if dataset is a tilt series.
    try:
        tilt_angles = utils.get_tilt_angles(dataset)
        tilt_angles = scipy.ndimage.interpolation.zoom(tilt_angles, 0.5)
        utils.set_tilt_angles(dataset, tilt_angles)
    except:  # noqa
        # TODO What exception are we ignoring?
        pass
Ejemplo n.º 10
0
def transform_scalars(dataset):

    #----USER SPECIFIED VARIABLES-----#
    ###ROT_AXIS###    #Specify Tilt Axis Dimensions x=0, y=1, z=2
    ###ROT_ANGLE###   #Rotate the dataset by an Angle (in degrees)
    #---------------------------------#

    from tomviz import utils
    import numpy as np
    from scipy import ndimage

    data_py = utils.get_array(dataset)  #get data as numpy array

    if data_py is None:  #Check if data exists
        raise RuntimeError("No data array found!")

    if ROT_AXIS == []:  #If tilt axis is not given, assign one.
        #Find smallest array dimension, assume it is the tilt angle axis
        if data_py.ndim >= 2:
            ROT_AXIS = np.argmin(data_py.shape)
        else:
            raise RuntimeError("Data Array is not 2 or 3 dimensions!")

    if ROT_ANGLE == []:  #If tilt axis is not given, assign it to 90 degrees.
        ROT_ANGLE = 90

    print('Rotating Dataset...')

    data_py_return = ndimage.interpolation.rotate(data_py,
                                                  ROT_ANGLE,
                                                  axes=((ROT_AXIS + 1) % 3,
                                                        (ROT_AXIS + 2) % 3))

    utils.set_array(dataset, data_py_return)
    print('Rotation Complete')
Ejemplo n.º 11
0
def transform_scalars(dataset, threshold=None):
    """Remove bad pixels in tilt series."""

    from tomviz import utils
    import scipy.ndimage
    import numpy as np

    tiltSeries = utils.get_array(dataset).astype(np.float32)

    for i in range(tiltSeries.shape[2]):
        I = tiltSeries[:, :, i]
        I_pad = np.lib.pad(I, (1, 1), 'edge')

        # calculate standard deviation in a 3 x 3 window
        averageI2 = scipy.ndimage.filters.uniform_filter(I_pad**2)
        averageI = scipy.ndimage.filters.uniform_filter(I_pad)
        std = np.sqrt(abs(averageI2 - averageI**2))[1:-1, 1:-1]

        medianI = scipy.ndimage.filters.median_filter(I_pad, 2)[1:-1, 1:-1]

        #identiy bad pixels
        badPixelsMask = abs(I - medianI) > std * threshold

        I[badPixelsMask] = medianI[badPixelsMask]
        tiltSeries[:, :, i] = I

    # Set the result as the new scalars.
    utils.set_array(dataset, tiltSeries)
def transform_scalars(dataset, threshold=None):
    """Remove bad pixels in tilt series."""

    from tomviz import utils
    import scipy.ndimage
    import numpy as np

    tiltSeries = utils.get_array(dataset).astype(np.float32)

    for i in range(tiltSeries.shape[2]):
        I = tiltSeries[:, :, i]
        I_pad = np.lib.pad(I, (1, 1), 'edge')

        # calculate standard deviation in a 3 x 3 window
        averageI2 = scipy.ndimage.filters.uniform_filter(I_pad ** 2)
        averageI = scipy.ndimage.filters.uniform_filter(I_pad)
        std = np.sqrt(abs(averageI2 - averageI**2))[1:-1, 1:-1]

        medianI = scipy.ndimage.filters.median_filter(I_pad, 2)[1:-1, 1:-1]

        #identiy bad pixels
        badPixelsMask = abs(I - medianI) > std * threshold

        I[badPixelsMask] = medianI[badPixelsMask]
        tiltSeries[:, :, i] = I

    # Set the result as the new scalars.
    utils.set_array(dataset, tiltSeries)
Ejemplo n.º 13
0
def transform_scalars(dataset):
    """3D Reconstruct from a tilt series using Algebraic Reconstruction Technique (ART)"""
    ###Niter###

    #Get Tilt angles
    tiltAngles = utils.get_tilt_angles(dataset)

    #Get Tilt Series
    tiltSeries = utils.get_array(dataset)
    (Nslice, Nray, Nproj) = tiltSeries.shape

    if tiltSeries is None:
        raise RuntimeError("No scalars found!")

    #Generate measurement matrix
    A = parallelRay(Nray, 1.0, tiltAngles, Nray, 1.0)  #A is a sparse matrix
    recon = np.zeros((Nslice, Nray, Nray))

    art3(A.todense(), tiltSeries, recon, Niter)

    # set the result as the new scalars.
    utils.set_array(dataset, recon)

    # Mark dataset as volume
    utils.mark_as_volume(dataset)
def transform_scalars(dataset):
    '''For each tilt image, the method uses average pixel value of selected region
      as the background level and subtracts it from the image.'''
    '''It does NOT set negative pixels to zero.'''

    from tomviz import utils
    import numpy as np

    #----USER SPECIFIED VARIABLES-----#
    ###XRANGE###
    ###YRANGE###
    ###ZRANGE###
    #---------------------------------#

    data_bs = utils.get_array(dataset) # Get data as numpy array.

    data_bs = data_bs.astype(np.float32) # Change tilt series type to float.

    if data_bs is None: #Check if data exists
        raise RuntimeError("No data array found!")    

    for i in range(ZRANGE[0],ZRANGE[1]):
        a = data_bs[:,:,i] - np.average(data_bs[XRANGE[0]:XRANGE[1],YRANGE[0]:YRANGE[1],i])
        data_bs[:,:,i] = a

    utils.set_array(dataset, data_bs)
Ejemplo n.º 15
0
def transform_scalars(dataset):
    """3D Reconstruct from a tilt series using Algebraic Reconstruction Technique (ART)"""
    ###Niter###

    # Get Tilt angles
    tiltAngles = utils.get_tilt_angles(dataset)

    # Get Tilt Series
    tiltSeries = utils.get_array(dataset)
    (Nslice,Nray,Nproj) = tiltSeries.shape

    if tiltSeries is None:
        raise RuntimeError("No scalars found!")

    # Generate measurement matrix
    A = parallelRay(Nray,1.0,tiltAngles,Nray,1.0) #A is a sparse matrix
    recon = np.zeros((Nslice,Nray,Nray))

    art3(A.todense(),tiltSeries,recon,Niter)

    # Set the result as the new scalars.
    utils.set_array(dataset, recon)

    # Mark dataset as volume
    utils.mark_as_volume(dataset)
Ejemplo n.º 16
0
def transform_scalars(dataset):
    """Generate Tilt Series from Volume"""
    
    from tomviz import utils
    import numpy as np
    import scipy.ndimage
    
    
    #----USER SPECIFIED VARIABLES-----#
    ###startAngle###    #Starting angle
    ###angleIncrement###   #Angle increment
    ###Nproj### #Number of tilts
    #---------------------------------#
    
    # Generate Tilt Angles
    angles = np.linspace(startAngle,startAngle+(Nproj-1)*angleIncrement,Nproj);
    
    array = utils.get_array(dataset)
    N = array.shape[0];
    Nslice = array.shape[2]; #Number of slices along rotation axis
    tiltSeries = np.zeros((Nslice, N ,Nproj))
    for i in range(Nproj):
        #Rotate volume
        rotatedArray = scipy.ndimage.interpolation.rotate(array, angles[i],axes=(0,1),reshape=False)
        #Calculate Projection
        tiltSeries[:,:,i] = np.sum(rotatedArray,axis=0).transpose()

    # set the result as the new scalars.
    utils.set_array(dataset, tiltSeries)

    # Mark dataset as tilt series
    utils.mark_as_tiltseries(dataset)

    # Save tilt angles
    utils.set_tilt_angles(dataset, angles)
Ejemplo n.º 17
0
def set_array_from_itk_image(dataset, itk_image):
    """Set dataset array from an ITK image."""

    itk_output_image_type = type(itk_image)

    # Save the VTKGlue optimization for later
    #------------------------------------------
    # Export the ITK image to a VTK image. No copying should take place.
    #export_filter = itk.ImageToVTKImageFilter[itk_output_image_type].New()
    #export_filter.SetInput(itk_image_data)
    #export_filter.Update()

    # Get scalars from the temporary image and copy them to the data set
    #result_image = export_filter.GetOutput()
    #filter_array = result_image.GetPointData().GetArray(0)

    # Make a new instance of the array that will stick around after this
    # filters in this script are garbage collected
    #new_array = filter_array.NewInstance()
    #new_array.DeepCopy(filter_array) # Should be able to shallow copy?
    #new_array.SetName(name)
    #------------------------------------------
    import itk
    from . import utils
    result = itk.PyBuffer[
        itk_output_image_type].GetArrayFromImage(itk_image)
    result = result.copy()
    utils.set_array(dataset, result, isFortran=False)
Ejemplo n.º 18
0
def transform_scalars(dataset):
    """3D Reconstruct from a tilt series using constraint-based Direct Fourier Method"""

    from tomviz import utils
    import numpy as np
    ###Niter###
    ###Niter_update_support###
    ###supportSigma###
    ###supportThreshold### #percent
    supportThreshold = supportThreshold/100.0
    
    nonnegativeVoxels = True
    tilt_angles = utils.get_tilt_angles(dataset) #Get Tilt angles

    tilt_images = utils.get_array(dataset)
    if tilt_images is None:
        raise RuntimeError("No scalars found!")

    #Direct Fourier recon without constraints
    (recon,recon_F) = dfm3(tilt_images,tilt_angles,np.size(tilt_images,0)*2)

    kr_cutoffs = np.linspace(0.05,0.5,10);
    I_data = radial_average(tilt_images,kr_cutoffs) #average Fourier magnitude of tilt series as a function of kr

    #Search for solutions that satisfy additional constraints
    recon = difference_map_update(recon_F,nonnegativeVoxels,I_data,kr_cutoffs,Niter,Niter_update_support,supportSigma,supportThreshold)

    print('Reconsruction Complete')

    # Set the result as the new scalars.
    utils.set_array(dataset, recon)

    # Mark dataset as volume
    utils.mark_as_volume(dataset)
Ejemplo n.º 19
0
def transform_scalars(dataset, clipNum=5):
    """Set values outside a cirular range to minimum(dataset) to
    remove reconstruction artifacts"""

    from tomviz import utils
    import numpy as np

    array = utils.get_array(dataset)

    # Constant values
    numX = array.shape[1]
    numY = array.shape[2]
    minVal = array.min()

    # Find the values to be clipped
    maxR = min([numX, numY]) / 2 - clipNum
    XX, YY = np.mgrid[0:numX, 0:numY]
    RR = np.sqrt((XX - numX / 2) ** 2 + (YY - numY / 2) ** 2)
    clipThese = np.where(RR >= maxR)

    # Apply the mask along the original tilt axis direction
    # (always the first direction in the array)
    for ii in range(0, array.shape[0]):
        curImage = array[ii, :, :] # points to the relevant 2D part of the array
        curImage[clipThese] = minVal

    # Return to tomviz
    utils.set_array(dataset, array)
Ejemplo n.º 20
0
def transform_scalars(dataset):
    """Resample dataset"""

    from tomviz import utils
    import numpy as np
    import scipy.ndimage

    #----USER SPECIFIED VARIABLES-----#
    #resampingFactor  = [1,1,1]  #Specify the shifts (x,y,z) applied to data
    ###resampingFactor###
    #---------------------------------#
    array = utils.get_array(dataset)

    # Transform the dataset.
    result = scipy.ndimage.interpolation.zoom(array, resampingFactor)
    
    # Set the result as the new scalars.
    utils.set_array(dataset, result)

    # Update tilt angles if dataset is a tilt series.
    if resampingFactor[2] != 1:
        try:
            tilt_angles = utils.get_tilt_angles(dataset)
            tilt_angles = scipy.ndimage.interpolation.zoom(tilt_angles, resampingFactor[2])
            utils.set_tilt_angles(dataset, tilt_angles)
        except:
            pass
Ejemplo n.º 21
0
def transform_scalars(dataset):
    """3D Reconstruct from a tilt series using Weighted Back-projection Method"""
    
    from tomviz import utils
    import numpy as np
    interpolation_methods = ('linear','nearest','spline','cubic')
    filter_methods = ('none','ramp','shepp-logan','cosine','hamming','hann')

    ###Nrecon###
    ###filter###
    ###interp###
    
    #Get Tilt angles
    tilt_angles = utils.get_tilt_angles(dataset)
    
    data_py = utils.get_array(dataset)
    if data_py is None:
        raise RuntimeError("No scalars found!")

    recon = wbp3(data_py,tilt_angles,Nrecon,filter_methods[filter],interpolation_methods[interp])
    print('Reconsruction Complete')

    # set the result as the new scalars.
    utils.set_array(dataset, recon)
    
    # Mark dataset as volume
    utils.mark_as_volume(dataset)
Ejemplo n.º 22
0
def transform_scalars(dataset):
    """3D Reconstruct from a tilt series using Weighted Back-projection Method"""

    from tomviz import utils
    import numpy as np
    interpolation_methods = ('linear', 'nearest', 'spline', 'cubic')
    filter_methods = ('none', 'ramp', 'shepp-logan', 'cosine', 'hamming',
                      'hann')

    ###Nrecon###
    ###filter###
    ###interp###

    # Get Tilt angles
    tilt_angles = utils.get_tilt_angles(dataset)

    data_py = utils.get_array(dataset)
    if data_py is None:
        raise RuntimeError("No scalars found!")

    recon = wbp3(data_py, tilt_angles, Nrecon, filter_methods[filter],
                 interpolation_methods[interp])
    print('Reconsruction Complete')

    # Set the result as the new scalars.
    utils.set_array(dataset, recon)

    # Mark dataset as volume.
    utils.mark_as_volume(dataset)
Ejemplo n.º 23
0
def transform_scalars(dataset):
    """Delete Slices in Dataset"""

    from tomviz import utils
    import numpy as np
    axis = 0;
    #----USER SPECIFIED VARIABLES-----#
    ###firstSlice###
    ###lastSlice###
    ###axis### #Axis along which to delete the subarray
    #---------------------------------#

    # Get the current dataset.
    array = utils.get_array(dataset)

    # Get indices of the slices to be deleted.
    indices = np.linspace(firstSlice,lastSlice,lastSlice-firstSlice+1).astype(int)

    # Delete the specified slices.
    array = np.delete(array,indices,axis)

    # Set the result as the new scalars.
    utils.set_array(dataset, array)

    # Delete corresponding tilt anlges if dataset is a tilt series.
    if axis == 2:
        try:
            tilt_angles = utils.get_tilt_angles(dataset)
            tilt_angles = np.delete(tilt_angles,indices)
            utils.set_tilt_angles(dataset, tilt_angles)
        except:
            pass
Ejemplo n.º 24
0
def transform_scalars(dataset, firstSlice=None, lastSlice=None, axis=2):
    """Delete Slices in Dataset"""

    from tomviz import utils
    import numpy as np

    # Get the current dataset.
    array = utils.get_array(dataset)

    # Get indices of the slices to be deleted.
    indices = np.linspace(firstSlice, lastSlice,
                          lastSlice - firstSlice + 1).astype(int)

    # Delete the specified slices.
    array = np.delete(array, indices, axis)

    # Set the result as the new scalars.
    utils.set_array(dataset, array)

    # Delete corresponding tilt anlges if dataset is a tilt series.
    if axis == 2:
        try:
            tilt_angles = utils.get_tilt_angles(dataset)
            tilt_angles = np.delete(tilt_angles, indices)
            utils.set_tilt_angles(dataset, tilt_angles)
        except: # noqa
            # TODO what exception are we ignoring here?
            pass
Ejemplo n.º 25
0
def transform_scalars(dataset):
    from tomviz import utils
    import numpy as np

    data_py = utils.get_array(dataset)  #get data as numpy array

    if data_py is None:  #Check if data exists
        raise RuntimeError("No data array found!")

    (Nx, Ny, Nz) = data_py.shape

    #----USER SPECIFIED VARIABLES-----#
    #START_CROP= [0,0,0]        #Specify start and end point of crop cube
    #END_CROP  = [Nx-1,Ny-1,Nz-1] # <-- Default will keep all data in range
    ###START_CROP###
    ###END_CROP###
    #---------------------------------#

    #crop the data
    data_cropped = data_py[START_CROP[0]:END_CROP[0],
                           START_CROP[1]:END_CROP[1],
                           START_CROP[2]:END_CROP[2]]

    #set the data back into tomviz
    utils.set_array(dataset, data_cropped)
    print('Data has been cropped.')
Ejemplo n.º 26
0
def transform_scalars(dataset):
    """Generate Tilt Series from Volume"""

    from tomviz import utils
    import numpy as np
    import scipy.ndimage

    #----USER SPECIFIED VARIABLES-----#
    ###startAngle###    #Starting angle
    ###angleIncrement###   #Angle increment
    ###Nproj### #Number of tilts
    #---------------------------------#

    # Generate Tilt Angles.
    angles = np.linspace(startAngle,startAngle+(Nproj-1)*angleIncrement,Nproj);

    array = utils.get_array(dataset)
    N = array.shape[0];
    Nslice = array.shape[2]; # Number of slices along rotation axis.
    tiltSeries = np.zeros((Nslice, N ,Nproj))
    for i in range(Nproj):
        # Rotate the volume.
        rotatedArray = scipy.ndimage.interpolation.rotate(array, angles[i],axes=(0,1),reshape=False)
        # Calculate projection.
        tiltSeries[:,:,i] = np.sum(rotatedArray,axis=0).transpose()

    # Set the result as the new scalars.
    utils.set_array(dataset, tiltSeries)

    # Mark dataset as tilt series.
    utils.mark_as_tiltseries(dataset)

    # Save tilt angles.
    utils.set_tilt_angles(dataset, angles)
Ejemplo n.º 27
0
    def transform_scalars(self,
                          dataset,
                          Nrecon=None,
                          filter=None,
                          interp=None):
        """
        3D Reconstruct from a tilt series using Weighted Back-projection Method
        """
        self.progress.maximum = 1

        from tomviz import utils
        interpolation_methods = ('linear', 'nearest', 'spline', 'cubic')
        filter_methods = ('none', 'ramp', 'shepp-logan', 'cosine', 'hamming',
                          'hann')

        # Get Tilt angles
        tilt_angles = utils.get_tilt_angles(dataset)

        tiltSeries = utils.get_array(dataset)
        if tiltSeries is None:
            raise RuntimeError("No scalars found!")

        Nslice = tiltSeries.shape[0]

        self.progress.maximum = Nslice
        step = 0

        recon = np.empty([Nslice, Nrecon, Nrecon], dtype=float, order='F')
        t0 = time.time()
        counter = 1
        etcMessage = 'Estimated time to complete: n/a'

        for i in range(Nslice):
            if self.canceled:
                return
            self.progress.message = 'Slice No.%d/%d. ' % (i + 1,
                                                          Nslice) + etcMessage

            recon[i, :, :] = wbp2(tiltSeries[i, :, :], tilt_angles, Nrecon,
                                  filter_methods[filter],
                                  interpolation_methods[interp])
            step += 1
            self.progress.value = step
            timeLeft = (time.time() - t0) / counter * (Nslice - counter)
            counter += 1
            timeLeftMin, timeLeftSec = divmod(timeLeft, 60)
            timeLeftHour, timeLeftMin = divmod(timeLeftMin, 60)
            etcMessage = 'Estimated time to complete: %02d:%02d:%02d' % (
                timeLeftHour, timeLeftMin, timeLeftSec)

        # Set up the output dataset
        from vtk import vtkImageData
        recon_dataset = vtkImageData()
        recon_dataset.CopyStructure(dataset)
        utils.set_array(recon_dataset, recon)
        utils.mark_as_volume(recon_dataset)

        returnValues = {}
        returnValues["reconstruction"] = recon_dataset
        return returnValues
Ejemplo n.º 28
0
def transform_scalars(dataset):

    from tomviz import utils
    import numpy as np

    # Get the current volume as a numpy array.
    array = utils.get_array(dataset)

    # Save the type
    input_dtype = array.dtype
    array = array.astype(np.float32)

    # Create 3D hanning window.
    for axis, axis_size in enumerate(array.shape):
        # Set up shape for numpy broadcasting.
        filter_shape = [
            1,
        ] * array.ndim
        filter_shape[axis] = axis_size
        window = np.hanning(axis_size).reshape(filter_shape)
        array *= window

    # Recast the data to the input type
    result = array.astype(input_dtype)
    utils.set_array(dataset, result)
Ejemplo n.º 29
0
def transform_scalars(dataset, SHIFT=None, rotation_angle=90.0):
    from tomviz import utils
    from scipy import ndimage
    import numpy as np

    data_py = utils.get_array(dataset)  # Get data as numpy array.

    if data_py is None:  #Check if data exists
        raise RuntimeError("No data array found!")
    if SHIFT is None:
        SHIFT = np.zeros(len(data_py.shape), dtype=np.int)
    data_py_return = np.empty_like(data_py)
    ndimage.interpolation.shift(data_py, SHIFT, order=0, output=data_py_return)

    rotation_axis = 2  # This operator always assumes the rotation axis is Z
    if rotation_angle == []:  # If tilt angle not given, assign it to 90 degrees.
        rotation_angle = 90

    axis1 = (rotation_axis + 1) % 3
    axis2 = (rotation_axis + 2) % 3
    axes = (axis1, axis2)
    shape = utils.rotate_shape(data_py_return, rotation_angle, axes=axes)
    data_py_return2 = np.empty(shape, data_py_return.dtype, order='F')
    ndimage.interpolation.rotate(data_py_return,
                                 rotation_angle,
                                 output=data_py_return2,
                                 axes=axes)

    utils.set_array(dataset, data_py_return2)
Ejemplo n.º 30
0
def transform_scalars(dataset):
    """Delete Slices in Dataset"""
    
    from tomviz import utils
    import numpy as np
    axis = 0;
    #----USER SPECIFIED VARIABLES-----#
    ###firstSlice###
    ###lastSlice###
    ###axis### #Axis along which to delete the subarray
    #---------------------------------#
    
    #get current dataset
    array = utils.get_array(dataset)
    
    #Get indices of the slices to be deleted
    indices = np.linspace(firstSlice,lastSlice,lastSlice-firstSlice+1).astype(int)

    # delete slices
    array = np.delete(array,indices,axis)

    #set the result as the new scalars.
    utils.set_array(dataset, array)

    #Delete corresponding tilt anlges if dataset is a tilt series
    if axis == 2:
        try:
            tilt_angles = utils.get_tilt_angles(dataset)
            tilt_angles = np.delete(tilt_angles,indices)
            utils.set_tilt_angles(dataset, tilt_angles)
        except:
            pass
Ejemplo n.º 31
0
def transform_scalars(dataset, resampling_factor=[1, 1, 1]):
    """Resample dataset"""

    from tomviz import utils
    import scipy.ndimage
    import numpy as np

    array = utils.get_array(dataset)

    # Transform the dataset.
    result_shape = utils.zoom_shape(array, resampling_factor)
    result = np.empty(result_shape, array.dtype, order='F')
    scipy.ndimage.interpolation.zoom(array, resampling_factor, output=result)

    # Set the result as the new scalars.
    utils.set_array(dataset, result)

    # Update tilt angles if dataset is a tilt series.
    if resampling_factor[2] != 1:
        try:
            tilt_angles = utils.get_tilt_angles(dataset)

            result_shape = utils.zoom_shape(tilt_angles, resampling_factor[2])
            result = np.empty(result_shape, array.dtype, order='F')
            scipy.ndimage.interpolation.zoom(
                tilt_angles, resampling_factor[2], output=result)
            utils.set_tilt_angles(dataset, result)
        except: # noqa
            # TODO What exception are we ignoring?
            pass
Ejemplo n.º 32
0
def transform_scalars(dataset):
    """Resample dataset"""
    
    from tomviz import utils
    import numpy as np
    import scipy.ndimage

    #----USER SPECIFIED VARIABLES-----#
    #resampingFactor  = [1,1,1]  #Specify the shifts (x,y,z) applied to data
    ###resampingFactor###
    #---------------------------------#
    array = utils.get_array(dataset)
    
    # transform the dataset
    result = scipy.ndimage.interpolation.zoom(array, resampingFactor)
    
    # set the result as the new scalars.
    utils.set_array(dataset, result)

    #Update tilt angles if dataset is a tilt series
    if resampingFactor[2] != 1:
        try:
            tilt_angles = utils.get_tilt_angles(dataset)
            tilt_angles = scipy.ndimage.interpolation.zoom(tilt_angles, resampingFactor[2])
            utils.set_tilt_angles(dataset, tilt_angles)
        except:
            pass
Ejemplo n.º 33
0
def transform_scalars(dataset, clipNum=5):
    """Set values outside a cirular range to minimum(dataset) to
    remove reconstruction artifacts"""

    from tomviz import utils
    import numpy as np

    array = utils.get_array(dataset)

    # Constant values
    numX = array.shape[1]
    numY = array.shape[2]
    minVal = array.min()

    # Find the values to be clipped
    maxR = min([numX, numY]) / 2 - clipNum
    XX, YY = np.mgrid[0:numX, 0:numY]
    RR = np.sqrt((XX - numX / 2)**2 + (YY - numY / 2)**2)
    clipThese = np.where(RR >= maxR)

    # Apply the mask along the original tilt axis direction
    # (always the first direction in the array)
    for ii in range(0, array.shape[0]):
        curImage = array[
            ii, :, :]  # points to the relevant 2D part of the array
        curImage[clipThese] = minVal

    # Return to tomviz
    utils.set_array(dataset, array)
Ejemplo n.º 34
0
def transform_scalars(dataset):

    #----USER SPECIFIED VARIABLES-----#
    ###ROT_AXIS###    #Specify Tilt Axis Dimensions x=0, y=1, z=2
    ###ROT_ANGLE###   #Rotate the dataset by an Angle (in degrees)
    #---------------------------------#
        
    from tomviz import utils
    import numpy as np
    from scipy import ndimage
    
    data_py = utils.get_array(dataset) #get data as numpy array
    
    if data_py is None: #Check if data exists
        raise RuntimeError("No data array found!")
    
    if ROT_AXIS == []: #If tilt axis is not given, assign one.
    #Find smallest array dimension, assume it is the tilt angle axis
        if data_py.ndim >= 2:
            ROT_AXIS = np.argmin( data_py.shape )
        else:
            raise RuntimeError("Data Array is not 2 or 3 dimensions!")

    if ROT_ANGLE == []: #If tilt axis is not given, assign it to 90 degrees.
        ROT_ANGLE = 90;
            
    print('Rotating Images...')
    
    data_py_return = ndimage.interpolation.rotate( data_py, ROT_ANGLE, axes=((ROT_AXIS+1)%3, (ROT_AXIS+2)%3) )
    
    utils.set_array(dataset, data_py_return)
    print('Rotate Complete')
Ejemplo n.º 35
0
def transform_scalars(dataset):
    """Pad dataset"""
    from tomviz import utils
    import numpy as np
    
    #----USER SPECIFIED VARIABLES-----#
    ###padWidthX###
    ###padWidthY###
    ###padWidthZ###
    ###padMode_index###
    #---------------------------------#
    padModes = ['constant','edge','wrap','minimum','median']
    padMode = padModes[padMode_index]
    array = utils.get_array(dataset) #get data as numpy array
    
    if array is None: #Check if data exists
        raise RuntimeError("No data array found!")
    
    pad_width = (padWidthX,padWidthY,padWidthZ)

    # pad the data.
    array = np.lib.pad(array, pad_width, padMode)

    # Set the data so that it is visible in the application.
    utils.set_array(dataset, array)

    # If dataset is marked as tilt series, update tilt angles
    if padWidthZ[0]+padWidthZ[1] >0:
        try:
            tilt_angles = utils.get_tilt_angles(dataset)
            tilt_angles = np.lib.pad(tilt_angles,padWidthZ, padMode)
            utils.set_tilt_angles(dataset, tilt_angles)
        except:
            pass
Ejemplo n.º 36
0
def transform_scalars(dataset):
    from tomviz import utils
    import numpy as np

    #----USER SPECIFIED VARIABLES-----#
    TILT_AXIS  = []  #Specify the tilt axis, if none is specified
                     #it assume it is the smallest dimension
    ANGLES = []  #Specify the angles used in the tiltseries 
                 #For example, ANGLES = np.linspace(0,140,70)
    #---------------------------------#

    data_py = utils.get_array(dataset)
    if data_py is None:
        raise RuntimeError("No scalars found!")
        
    if TILT_AXIS == []: #If tilt axis is not given, find it
    #Find smallest array dimension, assume it is the tilt angle axis
        if data_py.ndim == 3:
            TILT_AXIS = np.argmin( data_py.shape )
        elif data_py.ndim == 2:
            raise RuntimeError("Data Array is 2 dimensions, it should be 3!")
        else: 
            raise RuntimeError("Data Array is not 2 or 3 dimensions!")
    
    if ANGLES == []: #If angles are not given, assume 2 degree tilts
        angles = np.linspace(0,146,74)
        
    dimx = np.size(data_py,0) #IN THE FUTURE THIS SHOULD NOT BE ASSUMED
    result3D = dfm3(data_py,angles,dimx)
    
    # set the result as the new scalars.
    utils.set_array(dataset, result3D)
    print('Reconsruction Complete')
Ejemplo n.º 37
0
    def transform_scalars(self, dataset):
        """Automatically align tilt images by cross-correlation"""
        self.progress.maximum = 1

        tiltSeries = utils.get_array(dataset).astype(float)
        tiltAngles = utils.get_tilt_angles(dataset)

        # determine reference image index
        zeroDegreeTiltImage = np.where(tiltAngles == 0)[0]
        if zeroDegreeTiltImage:
            referenceIndex = zeroDegreeTiltImage[0]
        else:
            referenceIndex = tiltSeries.shape[2] // 2

        # create Fourier space filter
        filterCutoff = 4
        (Ny, Nx, Nproj) = tiltSeries.shape
        ky = np.fft.fftfreq(Ny)
        kx = np.fft.fftfreq(Nx)
        [kX, kY] = np.meshgrid(kx, ky)
        kR = np.sqrt(kX**2 + kY**2)
        kFilter = (kR <= (0.5 / filterCutoff)) * \
            np.sin(2 * filterCutoff * np.pi * kR)**2

        # create real sapce filter to remove edge discontinuities
        y = np.linspace(1, Ny, Ny)
        x = np.linspace(1, Nx, Nx)
        [X, Y] = np.meshgrid(x, y)
        rFilter = (np.sin(np.pi * X / Nx) * np.sin(np.pi * Y / Ny))**2

        self.progress.maximum = tiltSeries.shape[2] - 1
        step = 1

        for i in range(referenceIndex, Nproj - 1):
            if self.canceled:
                return
            self.progress.message = 'Processing tilt image No.%d/%d' % (step,
                                                                        Nproj)

            tiltSeries[:, :,
                       i + 1] = crossCorrelationAlign(tiltSeries[:, :, i + 1],
                                                      tiltSeries[:, :, i],
                                                      rFilter, kFilter)
            step += 1
            self.progress.value = step

        for i in range(referenceIndex, 0, -1):
            if self.canceled:
                return
            self.progress.message = 'Processing tilt image No.%d/%d' % (step,
                                                                        Nproj)
            tiltSeries[:, :,
                       i - 1] = crossCorrelationAlign(tiltSeries[:, :, i - 1],
                                                      tiltSeries[:, :, i],
                                                      rFilter, kFilter)
            step += 1
            self.progress.value = step

        utils.set_array(dataset, tiltSeries)
Ejemplo n.º 38
0
    def transform_scalars(self, dataset, Niter=None, stepSize=None,
                          updateMethodIndex=None):
        """
        3D Reconstruct from a tilt series using Simultaneous Iterative
        Reconstruction Techniques (SIRT)"""
        self.progress.maximum = 1

        update_methods = ('landweber', 'cimmino', 'component averaging')
        #reference
        """L. Landweber, Amer. J. Math., 73 (1951), pp. 615–624"""
        """G. Cimmino, La Ric. Sci., XVI, Ser. II, Anno IX, 1 (1938),
        pp. 326–333
        """
        """Y. Censor et al, Parallel Comput., 27 (2001), pp. 777–808"""

        # Get Tilt angles
        tiltAngles = utils.get_tilt_angles(dataset)

        #remove zero tilt anlges
        if np.count_nonzero(tiltAngles) < tiltAngles.size:
            tiltAngles = tiltAngles + 0.001

        # Get Tilt Series
        tiltSeries = utils.get_array(dataset)
        (Nslice, Nray, Nproj) = tiltSeries.shape

        if tiltSeries is None:
            raise RuntimeError("No scalars found!")

        # Generate measurement matrix
        self.progress.message = 'Generating measurement matrix'
        A = parallelRay(Nray, 1.0, tiltAngles, Nray, 1.0) #A is a sparse matrix
        recon = np.zeros((Nslice, Nray, Nray))

        self.progress.maximum = Nslice + 1
        step = 0

        #create a reconstruction object
        r = SIRT(A, update_methods[updateMethodIndex])
        r.initialize()
        step += 1
        self.progress.value = step

        for s in range(Nslice):
            if self.canceled:
                return
            b = tiltSeries[s, :, :].transpose().flatten()
            self.progress.message = 'Slice No.%d/%d' % (s + 1, Nslice)
            recon[s, :, :] = r.recon2(b, Niter, stepSize).reshape((Nray, Nray))
            step += 1
            self.progress.value = step

        # Set the result as the new scalars.
        utils.set_array(dataset, recon)

        # Mark dataset as volume
        utils.mark_as_volume(dataset)
Ejemplo n.º 39
0
    def transform_scalars(self, dataset, Nrecon=None, filter=None, interp=None):
        """
        3D Reconstruct from a tilt series using Weighted Back-projection Method
        """
        self.progress.maximum = 1

        from tomviz import utils
        interpolation_methods = ('linear', 'nearest', 'spline', 'cubic')
        filter_methods = ('none', 'ramp', 'shepp-logan',
                          'cosine', 'hamming', 'hann')

        # Get Tilt angles
        tilt_angles = utils.get_tilt_angles(dataset)

        tiltSeries = utils.get_array(dataset)
        if tiltSeries is None:
            raise RuntimeError("No scalars found!")

        Nslice = tiltSeries.shape[0]

        self.progress.maximum = Nslice
        step = 0

        recon = np.empty([Nslice, Nrecon, Nrecon], dtype=float, order='F')
        t0 = time.time()
        counter = 1
        etcMessage = 'Estimated time to complete: n/a'

        for i in range(Nslice):
            if self.canceled:
                return
            self.progress.message = 'Slice No.%d/%d. ' % (
                i + 1, Nslice) + etcMessage

            recon[i, :, :] = wbp2(tiltSeries[i, :, :], tilt_angles, Nrecon,
                                  filter_methods[filter],
                                  interpolation_methods[interp])
            step += 1
            self.progress.value = step
            timeLeft = (time.time() - t0) / counter * (Nslice - counter)
            counter += 1
            timeLeftMin, timeLeftSec = divmod(timeLeft, 60)
            timeLeftHour, timeLeftMin = divmod(timeLeftMin, 60)
            etcMessage = 'Estimated time to complete: %02d:%02d:%02d' % (
                timeLeftHour, timeLeftMin, timeLeftSec)

        # Set up the output dataset
        from vtk import vtkImageData
        recon_dataset = vtkImageData()
        recon_dataset.CopyStructure(dataset)
        utils.set_array(recon_dataset, recon)
        utils.mark_as_volume(recon_dataset)

        returnValues = {}
        returnValues["reconstruction"] = recon_dataset
        return returnValues
Ejemplo n.º 40
0
def transform_scalars(dataset):

    #----USER SPECIFIED VARIABLES-----#
    TILT_AXIS  = []  #Specify Tilt Axis Dimensions x=0, y=1, z=2
    #---------------------------------#
        
    from tomviz import utils
    import numpy as np
    
    data_py = utils.get_array(dataset) #get data as numpy array
    
    if data_py is None: # Check if data exists
        raise RuntimeError("No data array found!")    
    
    if TILT_AXIS == []: # If tilt axis is not given, find it
    # Find the smallest array dimension, assume it is the tilt angle axis.
        if data_py.ndim == 3:
            TILT_AXIS = np.argmin( data_py.shape )
        elif data_py.ndim == 2:
            raise RuntimeError("Data Array is 2 dimensions, it should be 3!")
        else: 
            raise RuntimeError("Data Array is not 2 or 3 dimensions!")
    
    print('Aligning Images by Cross Correlation')
    for i in range(1,np.size(data_py,TILT_AXIS)): # Align image to previous
        if TILT_AXIS == 2:
            im0 = np.fft.fft2(data_py[:,:,i-1])
            im1 = np.fft.fft2(data_py[:,:,i])
            xcor = abs(np.fft.ifft2((im0 * im1.conjugate())))
            shift = np.unravel_index(xcor.argmax(), xcor.shape)
            print( shift )
            data_py[:,:,i] = np.roll( data_py[:,:,i], shift[0], axis = 0)
            data_py[:,:,i] = np.roll( data_py[:,:,i], shift[1], axis = 1)
        elif TILT_AXIS == 1:
            im0 = np.fft.fft2(data_py[:,i-1,:])
            im1 = np.fft.fft2(data_py[:,i,:])
            xcor = abs(np.fft.ifft2((im0 * im1.conjugate())))
            print( np.amax(xcor) )
            shift = np.unravel_index(xcor.argmax(), xcor.shape)
            print( shift )
            data_py[:,i,:] = np.roll( data_py[:,i,:], shift[0], axis = 0)
            data_py[:,i,:] = np.roll( data_py[:,i,:], shift[2], axis = 2)
        elif TILT_AXIS == 0:
            im0 = np.fft.fft2(data_py[i-1,:,:])
            im1 = np.fft.fft2(data_py[i,:,:])
            xcor = abs(np.fft.ifft2((im0 * im1.conjugate())))
            print( np.amax(xcor) )
            shift = np.unravel_index(xcor.argmax(), xcor.shape)
            print( shift )
            data_py[i,:,:] = np.roll( data_py[i,:,:], shift[1], axis = 1)
            data_py[i,:,:] = np.roll( data_py[i,:,:], shift[2], axis = 2)
        else:
            raise RuntimeError("Python Transform Error: Unknown TILT_AXIS.")
    
    utils.set_array(dataset, data_py)
    print('Align Images Complete')
Ejemplo n.º 41
0
def transform_scalars(dataset):

    #----USER SPECIFIED VARIABLES-----#
    TILT_AXIS  = []  #Specify Tilt Axis Dimensions x=0, y=1, z=2
    #---------------------------------#
        
    from tomviz import utils
    import numpy as np
    
    data_py = utils.get_array(dataset) #get data as numpy array
    
    if data_py is None: #Check if data exists
        raise RuntimeError("No data array found!")    
    
    if TILT_AXIS == []: #If tilt axis is not given, find it
    #Find smallest array dimension, assume it is the tilt angle axis
        if data_py.ndim == 3:
            TILT_AXIS = np.argmin( data_py.shape )
        elif data_py.ndim == 2:
            raise RuntimeError("Data Array is 2 dimensions, it should be 3!")
        else: 
            raise RuntimeError("Data Array is not 2 or 3 dimensions!")
    
    print('Aligning Images by Cross Correlation')
    for i in range(1,np.size(data_py,TILT_AXIS)):#Align image to previous
        if TILT_AXIS == 2:
            im0 = np.fft.fft2(data_py[:,:,i-1])
            im1 = np.fft.fft2(data_py[:,:,i])
            xcor = abs(np.fft.ifft2((im0 * im1.conjugate())))
            shift = np.unravel_index(xcor.argmax(), xcor.shape)
            print( shift )
            data_py[:,:,i] = np.roll( data_py[:,:,i], shift[0], axis = 0)
            data_py[:,:,i] = np.roll( data_py[:,:,i], shift[1], axis = 1)
        elif TILT_AXIS == 1:
            im0 = np.fft.fft2(data_py[:,i-1,:])
            im1 = np.fft.fft2(data_py[:,i,:])
            xcor = abs(np.fft.ifft2((im0 * im1.conjugate())))
            print( np.amax(xcor) )
            shift = np.unravel_index(xcor.argmax(), xcor.shape)
            print( shift )
            data_py[:,i,:] = np.roll( data_py[:,i,:], shift[0], axis = 0)
            data_py[:,i,:] = np.roll( data_py[:,i,:], shift[2], axis = 2)
        elif TILT_AXIS == 0:
            im0 = np.fft.fft2(data_py[i-1,:,:])
            im1 = np.fft.fft2(data_py[i,:,:])
            xcor = abs(np.fft.ifft2((im0 * im1.conjugate())))
            print( np.amax(xcor) )
            shift = np.unravel_index(xcor.argmax(), xcor.shape)
            print( shift )
            data_py[i,:,:] = np.roll( data_py[i,:,:], shift[1], axis = 1)
            data_py[i,:,:] = np.roll( data_py[i,:,:], shift[2], axis = 2)
        else:
            raise RuntimeError("Python Transform Error: Unknown TILT_AXIS.")
    
    utils.set_array(dataset, data_py)
    print('Align Images Complete')
    def transform_scalars(self, dataset):
        """Automatically align tilt images by cross-correlation"""
        self.progress.maximum = 1

        tiltSeries = utils.get_array(dataset).astype(float)
        tiltAngles = utils.get_tilt_angles(dataset)

        # determine reference image index
        zeroDegreeTiltImage = np.where(tiltAngles == 0)[0]
        if zeroDegreeTiltImage:
            referenceIndex = zeroDegreeTiltImage[0]
        else:
            referenceIndex = tiltSeries.shape[2] // 2

        # create Fourier space filter
        filterCutoff = 4
        (Ny, Nx, Nproj) = tiltSeries.shape
        ky = np.fft.fftfreq(Ny)
        kx = np.fft.fftfreq(Nx)
        [kX, kY] = np.meshgrid(kx, ky)
        kR = np.sqrt(kX**2 + kY**2)
        kFilter = (kR <= (0.5 / filterCutoff)) * \
            np.sin(2 * filterCutoff * np.pi * kR)**2

        # create real sapce filter to remove edge discontinuities
        y = np.linspace(1, Ny, Ny)
        x = np.linspace(1, Nx, Nx)
        [X, Y] = np.meshgrid(x, y)
        rFilter = (np.sin(np.pi * X / Nx) * np.sin(np.pi * Y / Ny)) ** 2

        self.progress.maximum = tiltSeries.shape[2] - 1
        step = 0

        for i in range(referenceIndex, Nproj - 1):
            if self.canceled:
                return
            self.progress.message = 'Processing tilt image No.%d/%d' % (
                i + 1, Nproj)

            tiltSeries[:, :, i + 1] = crossCorrelationAlign(
                tiltSeries[:, :, i + 1], tiltSeries[:, :, i], rFilter, kFilter)
            step += 1
            self.progress.value = step

        for i in range(referenceIndex, 0, -1):
            if self.canceled:
                return
            self.progress.message = 'Processing tilt image No.%d/%d' % (
                i, Nproj)
            tiltSeries[:, :, i - 1] = crossCorrelationAlign(
                tiltSeries[:, :, i - 1], tiltSeries[:, :, i], rFilter, kFilter)
            step += 1
            self.progress.value = step

        utils.set_array(dataset, tiltSeries)
Ejemplo n.º 43
0
def transform_scalars(dataset):
    """Set negative voxels to zero"""

    from tomviz import utils

    data = utils.get_array(dataset)

    data[data < 0] = 0  # Set negative voxels to zero

    # Set the result as the new scalars.
    utils.set_array(dataset, data)
Ejemplo n.º 44
0
def transform_scalars(dataset):
    """Set negative voxels to zero"""

    from tomviz import utils

    data = utils.get_array(dataset)

    data[data < 0] = 0 # Set negative voxels to zero

    # Set the result as the new scalars.
    utils.set_array(dataset, data)
Ejemplo n.º 45
0
    def transform_scalars(self, dataset):
        """Automatic align the tilt axis to the center of images"""
        self.progress.maximum = 1

        from tomviz import utils
        # Get Tilt angles
        tilt_angles = utils.get_tilt_angles(dataset)

        tiltSeries = utils.get_array(dataset)
        if tiltSeries is None:
            raise RuntimeError("No scalars found!")

        Nx, Ny, Nz = tiltSeries.shape

        shifts = (np.linspace(-20, 20, 41)).astype('int')
        numberOfSlices = 5  # number of slices used for recon

        # randomly choose slices with top 50% total intensities
        tiltSeriesSum = np.sum(tiltSeries, axis=(1, 2))
        temp = tiltSeriesSum.argsort()[Nx // 2:]
        slices = temp[np.random.permutation(temp.size)[:numberOfSlices]]
        print('Reconstruction slices:')
        print(slices)

        I = np.zeros(shifts.size)

        self.progress.maximum = shifts.size - 1
        step = 0

        for i in range(shifts.size):
            if self.canceled:
                return
            shiftedTiltSeries = np.roll(tiltSeries[slices, :, :, ],
                                        shifts[i],
                                        axis=1)
            for s in range(numberOfSlices):
                self.progress.message = ('Reconstructing slice No.%d with %d '
                                         'pixels shift' %
                                         (slices[s], shifts[i]))

                recon = wbp2(shiftedTiltSeries[s, :, :], tilt_angles, Ny,
                             'ramp', 'linear')
                I[i] = I[i] + np.amax(recon)

            step += 1
            self.progress.value = step

        print('shift: %d' % shifts[np.argmax(I)])

        result = np.roll(tiltSeries, shifts[np.argmax(I)], axis=1)
        result = np.asfortranarray(result)

        # Set the result as the new scalars.
        utils.set_array(dataset, result)
Ejemplo n.º 46
0
    def transform_scalars(self, dataset):
        """Automatic align the tilt axis to the center of images"""
        self.progress.maximum = 1

        from tomviz import utils
        # Get Tilt angles
        tilt_angles = utils.get_tilt_angles(dataset)

        tiltSeries = utils.get_array(dataset)
        if tiltSeries is None:
            raise RuntimeError("No scalars found!")

        Nx, Ny, Nz = tiltSeries.shape

        shifts = (np.linspace(-20, 20, 41)).astype('int')
        numberOfSlices = 5  # number of slices used for recon

        # randomly choose slices with top 50% total intensities
        tiltSeriesSum = np.sum(tiltSeries, axis=(1, 2))
        temp = tiltSeriesSum.argsort()[Nx // 2:]
        slices = temp[np.random.permutation(temp.size)[:numberOfSlices]]
        print('Reconstruction slices:')
        print(slices)

        I = np.zeros(shifts.size)

        self.progress.maximum = shifts.size - 1
        step = 0

        for i in range(shifts.size):
            if self.canceled:
                return
            shiftedTiltSeries = np.roll(
                tiltSeries[slices, :, :, ], shifts[i], axis=1)
            for s in range(numberOfSlices):
                self.progress.message = ('Reconstructing slice No.%d with %d '
                                         'pixels shift' %
                                         (slices[s], shifts[i]))

                recon = wbp2(shiftedTiltSeries[s, :, :],
                             tilt_angles, Ny, 'ramp', 'linear')
                I[i] = I[i] + np.amax(recon)

            step += 1
            self.progress.value = step

        print('shift: %d' % shifts[np.argmax(I)])

        result = np.roll(tiltSeries, shifts[np.argmax(I)], axis=1)
        result = np.asfortranarray(result)

        # Set the result as the new scalars.
        utils.set_array(dataset, result)
Ejemplo n.º 47
0
def transform_scalars(dataset):        
    from tomviz import utils
    import numpy as np
    
    #----USER SPECIFIED VARIABLES-----#
    TILT_AXIS  = []     #Specify Tilt Axis Dimensions x=0, y=1, z=2
    SHIFT_EXP  = 0.10   #Specify the Expected (mean) Random % Image Shift (0-1)
    SHIFT_STDDEV = 0.05 #Specify the Standard Deviation as % of Image (0-1)
    np.random.seed(12)   #Set a new seed to get different random alignments
    #---------------------------------#
    
    data_py = utils.get_array(dataset) #get data as numpy array
    
    if data_py is None: #Check if data exists
        raise RuntimeError("No data array found!")    
    
    if TILT_AXIS == []: #If tilt axis is not given, find it
    #Find smallest array dimension, assume it is the tilt angle axis
        if data_py.ndim == 3:
            TILT_AXIS = np.argmin( data_py.shape )
        elif data_py.ndim == 2:
            raise RuntimeError("Data Array is 2 dimensions, it should be 3!")
        else: 
            raise RuntimeError("Data Array is not 2 or 3 dimensions!")
            

    for i in range(0,np.size(data_py,TILT_AXIS)-1):
        if TILT_AXIS == 2:
            shift_mu    = np.size(data_py,0)*SHIFT_EXP
            shift_sigma = np.size(data_py,0)*SHIFT_STDDEV
            shift0 = int( np.random.normal(shift_mu, shift_sigma) )
            shift1 = int( np.random.normal(shift_mu, shift_sigma) )
            data_py[:,:,i] = np.roll( data_py[:,:,i], shift0, axis = 0)
            data_py[:,:,i] = np.roll( data_py[:,:,i], shift1, axis = 1)
        elif TILT_AXIS == 1:
            shift_mu    = np.size(data_py,0)*SHIFT_EXP
            shift_sigma = np.size(data_py,0)*SHIFT_STDDEV
            shift0 = int( np.random.normal(shift_mu, shift_sigma) )
            shift1 = int( np.random.normal(shift_mu, shift_sigma) )
            data_py[:,i,:] = np.roll( data_py[:,i,:], shift0, axis = 0)
            data_py[:,i,:] = np.roll( data_py[:,i,:], shift2, axis = 2)
        elif TILT_AXIS == 0:
            shift_mu    = np.size(data_py,1)*SHIFT_EXP
            shift_sigma = np.size(data_py,1)*SHIFT_STDDEV
            shift0 = int( np.random.normal(shift_mu, shift_sigma) )
            shift1 = int( np.random.normal(shift_mu, shift_sigma) )
            data_py[i,:,:] = np.roll( data_py[i,:,:], shift1, axis = 1)
            data_py[i,:,:] = np.roll( data_py[i,:,:], shift2, axis = 2)
        else:
            raise RuntimeError("Python Transform Error: Unknown TILT_AXIS.")
    
    utils.set_array(dataset, data_py)
    print('Misalign Images Complete')
Ejemplo n.º 48
0
def transform_scalars(dataset):
    from tomviz import utils
    import numpy as np

    #----USER SPECIFIED VARIABLES-----#
    TILT_AXIS = []  # Specify Tilt Axis Dimensions x=0, y=1, z=2
    SHIFT_EXP = 0.10  # Specify the Expected (mean) Random % Image Shift (0-1)
    SHIFT_STDDEV = 0.05  # Specify the Standard Deviation as % of Image (0-1)
    np.random.seed(12)  # Set a new seed to get different random alignments
    #---------------------------------#

    data_py = utils.get_array(dataset)  # Get data as numpy array.

    if data_py is None:  # Check if data exists.
        raise RuntimeError("No data array found!")

    if TILT_AXIS == []:  # If tilt axis is not given, find it.
        # Find the smallest array dimension, assume it is the tilt angle axis.
        if data_py.ndim == 3:
            TILT_AXIS = np.argmin(data_py.shape)
        elif data_py.ndim == 2:
            raise RuntimeError("Data Array is 2 dimensions, it should be 3!")
        else:
            raise RuntimeError("Data Array is not 2 or 3 dimensions!")

    for i in range(0, np.size(data_py, TILT_AXIS) - 1):
        if TILT_AXIS == 2:
            shift_mu = np.size(data_py, 0) * SHIFT_EXP
            shift_sigma = np.size(data_py, 0) * SHIFT_STDDEV
            shift0 = int(np.random.normal(shift_mu, shift_sigma))
            shift1 = int(np.random.normal(shift_mu, shift_sigma))
            data_py[:, :, i] = np.roll(data_py[:, :, i], shift0, axis=0)
            data_py[:, :, i] = np.roll(data_py[:, :, i], shift1, axis=1)
        elif TILT_AXIS == 1:
            shift_mu = np.size(data_py, 0) * SHIFT_EXP
            shift_sigma = np.size(data_py, 0) * SHIFT_STDDEV
            shift0 = int(np.random.normal(shift_mu, shift_sigma))
            shift1 = int(np.random.normal(shift_mu, shift_sigma))
            data_py[:, i, :] = np.roll(data_py[:, i, :], shift0, axis=0)
            data_py[:, i, :] = np.roll(data_py[:, i, :], shift1, axis=1)
        elif TILT_AXIS == 0:
            shift_mu = np.size(data_py, 1) * SHIFT_EXP
            shift_sigma = np.size(data_py, 1) * SHIFT_STDDEV
            shift0 = int(np.random.normal(shift_mu, shift_sigma))
            shift1 = int(np.random.normal(shift_mu, shift_sigma))
            data_py[i, :, :] = np.roll(data_py[i, :, :], shift0, axis=0)
            data_py[i, :, :] = np.roll(data_py[i, :, :], shift1, axis=1)
        else:
            raise RuntimeError("Python Transform Error: Unknown TILT_AXIS.")

    utils.set_array(dataset, data_py)
    print('Misalign Images Complete')
Ejemplo n.º 49
0
def transform_scalars(dataset):
    """Apply a Laplace filter to dataset."""

    from tomviz import utils
    import scipy.ndimage

    array = utils.get_array(dataset)

    # Transform the dataset
    result = scipy.ndimage.filters.laplace(array)

    # Set the result as the new scalars.
    utils.set_array(dataset, result)
Ejemplo n.º 50
0
def transform_scalars(dataset):
    """Apply a Laplace filter to dataset."""

    from tomviz import utils
    import numpy as np
    import scipy.ndimage

    array = utils.get_array(dataset)

    # Transform the dataset
    result = scipy.ndimage.filters.laplace(array)

    # Set the result as the new scalars.
    utils.set_array(dataset, result)
Ejemplo n.º 51
0
def transform_scalars(dataset):
    """Calculate 3D gradient magnitude using Sobel operator"""

    from tomviz import utils
    import numpy as np
    import scipy.ndimage

    array = utils.get_array(dataset)
    array = array.astype(np.float32)

    # Transform the dataset
    result = scipy.ndimage.filters.generic_gradient_magnitude(array, scipy.ndimage.filters.sobel)
    
    # Set the result as the new scalars.
    utils.set_array(dataset, result)
Ejemplo n.º 52
0
def transform_scalars(dataset):
    """Downsample dataset by a factor of 2"""
    
    from tomviz import utils
    import numpy as np
    import scipy.ndimage

    array = utils.get_array(dataset)

    # transform the dataset
    result = scipy.ndimage.interpolation.zoom(array, (0.5, 0.5, 0.5))
    
    # set the result as the new scalars.
    utils.set_array(dataset, result)
    
Ejemplo n.º 53
0
def transform_scalars(dataset, shift=[0, 0, 0]):
    from tomviz import utils
    import numpy as np

    data_py = utils.get_array(dataset) # Get data as numpy array.

    if data_py is None: #Check if data exists
        raise RuntimeError("No data array found!")

    data_py[:] = np.roll(data_py, shift[0], axis=0)
    data_py[:] = np.roll(data_py, shift[1], axis=1)
    data_py[:] = np.roll(data_py, shift[2], axis=2)

    utils.set_array(dataset, data_py)
    print('Data has been shifted uniformly.')
Ejemplo n.º 54
0
def transform_scalars(dataset):
    """Downsample dataset by a factor of 2"""

    from tomviz import utils
    import numpy as np
    import scipy.ndimage

    array = utils.get_array(dataset)

    # Downsample the dataset x2 using order 1 spline (linear)
    result = scipy.ndimage.interpolation.zoom(array, 
                (0.5, 0.5, 0.5),output=None, order=1,
                mode='constant', cval=0.0, prefilter=False)

    # Set the result as the new scalars.
    utils.set_array(dataset, result)
Ejemplo n.º 55
0
def transform_scalars(dataset,  XRANGE=None, YRANGE=None, ZRANGE=None):
    """Define this method for Python operators that
    transform input scalars"""

    from tomviz import utils
    import numpy as np

    array = utils.get_array(dataset)
    if array is None:
        raise RuntimeError("No scalars found!")

    # Transform the dataset.
    result = np.copy(array)
    result[XRANGE[0]:XRANGE[1], YRANGE[0]:YRANGE[1], ZRANGE[0]:ZRANGE[1]] = 0
    # Set the result as the new scalars.
    utils.set_array(dataset, result)