Exemple #1
0
    def test_L1Norm_2D(self):
        model = 12 # select a model number from the library
        N = 400 # set dimension of the phantom
        path = os.path.dirname(tomophantom.__file__)
        path_library2D = os.path.join(path, "Phantom2DLibrary.dat")

        phantom_2D = TomoP2D.Model(model, N, path_library2D)    
        # data = ImageData(phantom_2D)
        ig = ImageGeometry(voxel_num_x=N, voxel_num_y=N)
        data = ig.allocate(None)
        data.fill(phantom_2D)

        # Create acquisition data and geometry
        detectors = N
        angles = np.linspace(0, 180, 120, dtype=np.float32)

        ag = AcquisitionGeometry.create_Parallel2D()\
            .set_angles(angles, angle_unit=AcquisitionGeometry.DEGREE)\
            .set_panel(detectors)
        sin = ag.allocate(None)
        sino = TomoP2D.ModelSino(model, detectors, detectors, angles, path_library2D)
        sin.fill(sino)
        sin_stripe = sin.copy()
        #        sin_stripe = sin
        tmp = sin_stripe.as_array()
        tmp[:,::27]=tmp[:,::28]
        sin_stripe.fill(tmp)

        ring_recon = RingRemover(20, "db15", 21, info = True)(sin_stripe)

        error = (ring_recon - sin).abs().as_array().mean()
        print ("L1Norm ", error)
        np.testing.assert_almost_equal(error, 83.20592, 4)
Exemple #2
0
 def Phantom(self, model, size):
     model = model
     sizeN = size
     #This will generate 256x256 phantom from the model
     self.phantom = TomoP2D.Model(
         model, sizeN,
         '/home/sohila/Documents/BIO-MATERIALS/Third-Year/Second-Term/MRI/Task2-MRI/phantoms/TomoPhantom/PhantomLibrary/models/Phantom2DLibrary.dat'
     )
     angles_num = int(sizeN)  # angles number
     self.angles = np.linspace(0, 180, angles_num, dtype='float32')
     angles_rad = self.angles * (np.pi / 180)
     P = int(np.sqrt(2) * sizeN)  #detectors
     #This will generate a sinogram of the model
     sino_an = TomoP2D.ModelSino(
         model, sizeN, P, self.angles,
         '/home/sohila/Documents/BIO-MATERIALS/Third-Year/Second-Term/MRI/Task2-MRI/phantoms/TomoPhantom/PhantomLibrary/models/Phantom2DLibrary.dat'
     )
     # pp = {'Obj': TomoP2D.Objects2D.RECTANGLE,
     #       'C0': 9.00,
     #       'x0': 0.3,
     #       'y0': -0.25,
     #       'a': 0.5,
     #       'b': 0.8,
     #       'phi': 90.0}
     # G=TomoP2D.Object(256, pp)
     return self.phantom
Exemple #3
0
def generateImage():
    model = 6  # selecting a model
    N_size = 256
    #specify a full path to the parameters file
    pathTP = 'Phantom2DLibrary.dat'
    #This will generate a N_size x N_size phantom (2D)
    phantom_2D = TomoP2D.Model(model, N_size, pathTP)

    Labels = []
    Labels_array = []
    Images = []
    shapeTypes = [TomoP2D.Objects2D.RECTANGLE, TomoP2D.Objects2D.ELLIPSE]

    for a in range(0, 1, 1):

        num_back_shapes = np.random.randint(200, 400)

        back_temp = np.zeros((256, 256), dtype=np.uint8)

        for i in range(0, num_back_shapes, 1):

            shapeRand = np.random.randint(2)
            shape = TomoP2D.Object(256, genTomoShape(shapeTypes[shapeRand]))
            back_temp = back_temp + shape

        scaler = np.amax(back_temp)
        back_temp = np.divide(back_temp, scaler)

        num_shapes = np.random.randint(5, 20)

        image_temp = np.zeros((256, 256), dtype=np.uint8)

        for i in range(0, num_shapes, 1):

            #Random pick of shape type
            shapeRand = np.random.randint(2)
            #Generate shape
            shape = TomoP2D.Object(256, genTomoShape(shapeTypes[shapeRand]))
            #add the shape to the image and take away the original to get the positions where a new shape has been added.
            fit = ((image_temp + shape) - image_temp) > 0
            #update the pixel values where the shape has been added, do no tjust add the pixel values together but replace them so the overlap is smooth
            image_temp[fit] = shape[fit]

        noise = np.random.uniform(low=0,
                                  high=np.amax(image_temp),
                                  size=(256, 256))
        nos = (image_temp * 1.0) + (noise * 1.0) + (back_temp * 1.0)
        nos = np.divide(nos, np.amax(nos))
        Images.append(nos)
        Labels_array.append(np.array(image_temp))

        #%%

    return np.array(Images), np.array(Labels_array)
                                ab_min,
                                ab_max,
                                N_size,
                                tot_objects,
                                object_type='mix')
plt.figure()
plt.imshow(Objfoam2D, vmin=0, vmax=0.3, cmap="gray")

# Generate a sinogram
angles_num = int(0.5 * np.pi * N_size)
# angles number
angles = np.linspace(0, 180, angles_num, dtype='float32')
angles_rad = angles * (np.pi / 180)
P = int(np.sqrt(2) * N_size)  #detectors

sino_Objfoam2D = TomoP2D.ObjectSino(N_size, P, angles, myObjects)
plt.figure()
plt.imshow(sino_Objfoam2D, cmap="gray")

#%%
# 3D example
print("Generating 3D random phantom")
(Objfoam3D, myObjects) = foam3D(x0min,
                                x0max,
                                y0min,
                                y0max,
                                z0min,
                                z0max,
                                c0min,
                                c0max,
                                ab_min,
def get_ImageData(num_model, geometry):
    '''Returns an ImageData relative to geometry with the model num_model from tomophantom
    
    :param num_model: model number
    :type num_model: int
    :param geometry: geometrical info that describes the phantom
    :type geometry: ImageGeometry
    Example usage:
    
    .. code-block:: python
      
      ndim = 2
      N=128
      angles = np.linspace(0, 360, 50, True, dtype=np.float32)
      offset = 0.4
      channels = 3
        
      if ndim == 2:
          ag = AcquisitionGeometry.create_Cone2D((offset,-100), (offset,100))
          ag.set_panel(N)
            
      else:
          ag = AcquisitionGeometry.create_Cone3D((offset,-100, 0), (offset,100,0))
          ag.set_panel((N,N-2))
        
      ag.set_channels(channels)
      ag.set_angles(angles, angle_unit=AcquisitionGeometry.DEGREE)
        
        
      ig = ag.get_ImageGeometry()
      num_model = 1
      phantom = TomoPhantom.get_ImageData(num_model=num_model, geometry=ig)

    
    '''
    ig = geometry.copy()
    ig.set_labels(DataOrder.TOMOPHANTOM_IG_LABELS)
    num_dims = len(ig.dimension_labels)
    
    if ImageGeometry.CHANNEL in ig.dimension_labels:
        if not is_model_temporal(num_model):
            raise ValueError('Selected model {} is not a temporal model, please change your selection'.format(num_model))
        if num_dims == 4:
            # 3D+time for tomophantom
            # output dimensions channel and then spatial, 
            # e.g. [ 'channel', 'vertical', 'horizontal_y', 'horizontal_x' ]
            num_model = num_model
            shape = tuple(ig.shape[1:])
            phantom_arr = TomoP3D.ModelTemporal(num_model, shape, path_library3D)
        elif num_dims == 3:
            # 2D+time for tomophantom
            # output dimensions channel and then spatial, 
            # e.g. [ 'channel', 'horizontal_y', 'horizontal_x' ]
            N = ig.shape[1]
            num_model = num_model
            phantom_arr = TomoP2D.ModelTemporal(num_model, ig.shape[1], path_library2D)
        else:
            raise ValueError('Wrong ImageGeometry')
        if ig.channels != phantom_arr.shape[0]:
            raise ValueError('The required model {} has {} channels. The ImageGeometry you passed has {}. Please update your ImageGeometry.'\
                .format(num_model, ig.channels, phantom_arr.shape[0]))
    else:
        if num_dims == 3:
            # 3D
            num_model = num_model
            phantom_arr = TomoP3D.Model(num_model, ig.shape, path_library3D)
        elif num_dims == 2:
            # 2D
            if ig.shape[0] != ig.shape[1]:
                raise ValueError('Can only handle square ImageData, got shape'.format(ig.shape))
            N = ig.shape[0]
            num_model = num_model
            phantom_arr = TomoP2D.Model(num_model, N, path_library2D)
        else:
            raise ValueError('Wrong ImageGeometry')

    
    im_data = ImageData(phantom_arr, geometry=ig, suppress_warning=True)
    im_data.reorder(list(geometry.dimension_labels))
    return im_data
Exemple #6
0
@author: Daniil Kazantsev
"""
import numpy as np
import matplotlib.pyplot as plt
import os
import tomophantom
from tomophantom import TomoP2D

model = 102  # note that the selected model is temporal (2D + time)
N_size = 512 # set dimension of the phantom
# one can specify an exact path to the parameters file
# path_library2D = '../../../PhantomLibrary/models/Phantom2DLibrary.dat'
path = os.path.dirname(tomophantom.__file__)
path_library2D = os.path.join(path, "Phantom2DLibrary.dat")
#This will generate a N_size x N_size x Time frames phantom (2D + time)
phantom_2Dt = TomoP2D.ModelTemporal(model, N_size, path_library2D)

plt.close('all')
plt.figure(1)
plt.rcParams.update({'font.size': 21})
plt.title('{}''{}'.format('2D+t phantom using model no.',model))
for sl in range(0,np.shape(phantom_2Dt)[0]):
    im = phantom_2Dt[sl,:,:]
    plt.imshow(im, vmin=0, vmax=1)
    plt.pause(.1)
    plt.draw

# create sinogram analytically
angles_num = int(0.5*np.pi*N_size); # angles number
angles = np.linspace(0,180,angles_num,dtype='float32')
angles_rad = angles*(np.pi/180)
Exemple #7
0
b_el3 = random.uniform(b_el3_min, b_el3_max)
phi_min = 0.0
phi_max = 90.0
phi = random.uniform(phi_min, phi_max)

el3 = {
    'Obj': Objects2D.RECTANGLE,
    'C0': C_0,
    'x0': 0.0,
    'y0': 0.0,
    'a': a_el3,
    'b': b_el3,
    'phi': phi
}

GROUND_TRUTH = TomoP2D.Object(N_size, [el1, el2, el3])

plt.close('all')
plt.figure(1)
plt.rcParams.update({'font.size': 21})
plt.imshow(GROUND_TRUTH, vmin=0, vmax=1, cmap="BuPu")
plt.colorbar(ticks=[0, 0.5, 1], orientation='vertical')
plt.title('{}'.format('Ground Truth Object'))
#%%

# define all objects bellow:
el1 = {
    'Obj': Objects2D.ELLIPSE,
    'C0': 0.7,
    'x0': 0.0,
    'y0': 0.0,
Exemple #8
0
import os, sys
import tomophantom
from tomophantom import TomoP2D

# user supplied input
if len(sys.argv) > 1:
    which_noise = int(sys.argv[1])
else:
    which_noise = 0

model = 1  # select a model number from the library
N = 128  # set dimension of the phantom
path = os.path.dirname(tomophantom.__file__)
path_library2D = os.path.join(path, "Phantom2DLibrary.dat")

phantom_2D = TomoP2D.Model(model, N, path_library2D)
data = ImageData(phantom_2D)
ig = ImageGeometry(voxel_num_x=N, voxel_num_y=N)

# Create acquisition data and geometry
detectors = N
angles = np.linspace(0, np.pi, 180)
ag = AcquisitionGeometry('parallel', '2D', angles, detectors)

# Select device
device = input('Available device: GPU==1 / CPU==0 ')
if device == '1':
    dev = 'gpu'
else:
    dev = 'cpu'
def generateImage():
    model = 6  # selecting a model
    N_size = 256
    #specify a full path to the parameters file
    pathTP = 'Phantom2DLibrary.dat'
    #This will generate a N_size x N_size phantom (2D)
    phantom_2D = TomoP2D.Model(model, N_size, pathTP)

    Labels = []
    Labels_array = []
    Images = []
    shapeTypes = [TomoP2D.Objects2D.RECTANGLE, TomoP2D.Objects2D.ELLIPSE]

    insertImage = np.asarray(PIL.Image.open('2.jpg').convert('L'))
    #    print(inssertImage.shape)
    #    insertImage = np.append(insertImage,insertImage, axis=0)
    #    insertImage = np.append(insertImage,insertImage, axis=0)
    #    insertImage = np.append(insertImage,insertImage, axis=0)
    #    print(insertImage.shape)
    insertImage.setflags(write=1)

    insertImage = [insertImage[:256, :256], insertImage[:256, :256]]

    for a in range(0, 1, 1):

        objects = []
        background = []
        array_label = []
        num_back_shapes = np.random.randint(200, 400)

        for i in range(0, num_back_shapes, 1):
            shapeRand = np.random.randint(2)
            background.append(genTomoShape(shapeTypes[shapeRand]))

        num_shapes = np.random.randint(5, 20)
        num_shapes = 5

        label_temp = np.zeros((256, 256), dtype=np.uint8)
        image_temp = np.zeros((256, 256), dtype=np.uint8)

        pattern = np.random.randint(len(insertImage))

        for i in range(0, num_shapes, 1):

            #Generate tomoshape
            #Random pick of shape type
            shapeRand = np.random.randint(2)
            #Generate shape
            shape = TomoP2D.Object(256, genTomoShape(shapeTypes[shapeRand]))
            #add the shape to the laebl image and take away the original to get the positions where a new shape has been added.
            fit = ((label_temp + shape) - image_temp) > 0
            #update the pixel values where the shape has been added, do no tjust add the pixel values together but replace them so the overlap is smooth
            label_temp[fit] = shape[fit]
            #filter looking for where the shape is
            shapeFilter = shape >= 0.5

            #for those positions where the shape exists set those values to the value in the image pattern
            shape[shapeFilter] = insertImage[pattern][shapeFilter]
            #add the shape to the image and take away the original to get the positions where a new shape has been added.
            fit = ((image_temp + shape) - image_temp) > 0
            #update the pixel values where the shape has been added, do no tjust add the pixel values together but replace them so the overlap is smooth
            image_temp[fit] = shape[fit]

        array_temp = np.zeros(len(insertImage))
        array_temp[pattern] = int(1)
        array_label.append(array_temp)

        noise = np.random.uniform(low=0,
                                  high=np.amax(image_temp) * 0.1,
                                  size=(256, 256))
        nos = (image_temp * 1.0) + (noise * 1.0)
        plt.imshow(nos)
        Images.append(nos)

        #%%


#    fig = plt.figure(figsize=(15, 15))
#    fig.subplots_adjust(bottom=0.15, top=0.95, hspace=0.2,left=0.1, right=0.95, wspace=0.2)
#    #plt.figure(1)
#    #plt.rcParams.update({'font.size': 21})
##    NOISY_IMAGES = np.array(NOISY_IMAGE)
##    IMAGE = np.array(IMAGE)
##    np.save('TM_Images.npy', NOISY_IMAGES)
##    np.save('TM_Labels.npy', IMAGE)
#    ax_heat = fig.add_subplot(121)
#
#    ax_heat.imshow(NOISY_IMAGE[0],  cmap="BuPu")
#    ax_heat = fig.add_subplot(122)
#
#    ax_heat.imshow(IMAGE[0],  cmap="BuPu")
#
#    plt.colorbar(ticks=[0, 0.5, 1], orientation='vertical')
#    plt.title('{}''{}'.format('2D Phantom using model no.',model))
#    plt.show()
    return np.array([Labels, Images])
Exemple #10
0
This demo demonstrates frequent inaccuracies which are accosiated with X-ray imaging:
zingers, rings and noise

@author: Daniil Kazantsev
"""
import numpy as np
import matplotlib.pyplot as plt
from tomophantom import TomoP2D

model = 4  # select a model
N_size = 512
#specify a full path to the parameters file
pathTP = '../../functions/models/Phantom2DLibrary.dat'
#objlist = modelfile2Dtolist(pathTP, model) # one can extract parameters
#This will generate a N_size x N_size phantom (2D)
phantom_2D = TomoP2D.Model(model, N_size, pathTP)

plt.close('all')
plt.figure(1)
plt.rcParams.update({'font.size': 21})
plt.imshow(phantom_2D, vmin=0, vmax=1, cmap="gray")
plt.colorbar(ticks=[0, 0.5, 1], orientation='vertical')
plt.title('{}' '{}'.format('2D Phantom using model no.', model))

# create sinogram analytically
angles_num = int(0.5 * np.pi * N_size)
# angles number
angles = np.linspace(0, 180, angles_num, dtype='float32')
angles_rad = angles * (np.pi / 180)
P = int(np.sqrt(2) * N_size)  #detectors
    'b': 0.3,
    'phi': -30.0
}

pp1 = {
    'Obj': Objects2D.RECTANGLE,
    'C0': 1.00,
    'x0': -0.2,
    'y0': 0.2,
    'a': 0.25,
    'b': 0.4,
    'phi': 60.0
}

myObjects = [pp, pp1]  # dictionary of objects
Object1 = TomoP2D.Object(N_size, myObjects)

plt.close('all')
plt.figure(1)
plt.rcParams.update({'font.size': 21})
plt.imshow(Object1, vmin=0, vmax=1, cmap="BuPu")
plt.colorbar(ticks=[0, 0.5, 1], orientation='vertical')
plt.title('{}'.format('2D Object'))

# create sinogram analytically without using the parameters file
angles_num = int(0.5 * np.pi * N_size)
# angles number
angles = np.linspace(0, 180, angles_num, dtype='float32')
angles_rad = angles * (np.pi / 180)
P = int(np.sqrt(2) * N_size)  #detectors
Exemple #12
0
def generateImage():
    model = 6 # selecting a model
    N_size = 256
    #specify a full path to the parameters file
    pathTP = 'Phantom2DLibrary.dat'
    #This will generate a N_size x N_size phantom (2D)
    phantom_2D = TomoP2D.Model(model, N_size, pathTP)
    
    IMAGE = []
    NOISY_IMAGE = []
    flowers = ((np.asarray(Image.open('flowers.png').convert('L')))/255)*0.9
    
    for a in range(0,1,1):
        pps = []
        back = []
        num_back_rectangles = np.random.randint(200, 400)
        for i in range(0,num_back_rectangles,1):
            pp = {'Obj': TomoP2D.Objects2D.RECTANGLE, 
              'C0' : float(np.random.uniform(low=0.5, high=0.9, size =1)), 
              'x0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'y0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'a'  : float(np.random.uniform(low=0.02, high=0.3, size = 1)),
              'b'  : float(np.random.uniform(low=0.02, high=0.3, size=1)),
              'phi': float(np.random.uniform(low=0, high=180, size=1))}
            
            bb = {'Obj': TomoP2D.Objects2D.ELLIPSE, 
              'C0' : float(np.random.uniform(low=0.1, high=0.5, size =1)), 
              'x0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'y0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'a'  : float(np.random.uniform(low=0.02, high=0.3, size = 1)),
              'b'  : float(np.random.uniform(low=0.02, high=0.3, size=1)),
              'phi': float(np.random.uniform(low=0, high=180, size=1))}
            cc = {'Obj': TomoP2D.Objects2D.RECTANGLE, 
              'C0' : float(np.random.uniform(low=0.5, high=0.9, size =1)), 
              'x0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'y0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'a'  : float(np.random.uniform(low=0.02, high=0.3, size = 1)),
              'b'  : float(np.random.uniform(low=0.02, high=0.3, size=1)),
              'phi': float(np.random.uniform(low=0, high=180, size=1))}
            dd = {'Obj': TomoP2D.Objects2D.ELLIPSE, 
              'C0' : float(np.random.uniform(low=0.5, high=0.9, size =1)), 
              'x0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'y0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'a'  : float(np.random.uniform(low=0.02, high=0.3, size = 1)),
              'b'  : float(np.random.uniform(low=0.02, high=0.3, size=1)),
              'phi': float(np.random.uniform(low=0, high=180, size=1))}
            back.append(pp)
            
            back.append(bb)
            
            back.append(cc)
           
            back.append(dd)
            
            back.append(bb)
        num_rectangles = np.random.randint(5, 20)
        print(a)
        
        for i in range(0,num_rectangles,1):
            pp = {'Obj': TomoP2D.Objects2D.RECTANGLE, 
              'C0' : float(np.random.uniform(low=0.7, high=0.9, size =1)), 
              'x0' : float(np.random.uniform(low=-0.5, high=1.0, size =1)),
              'y0' : float(np.random.uniform(low=-1.0, high=0.5, size =1)),
              'a'  : float(np.random.uniform(low=0.02, high=0.3, size = 1)),
              'b'  : float(np.random.uniform(low=0.02, high=0.3, size=1)),
              'phi': float(np.random.uniform(low=0, high=180, size=1))}
            
            bb = {'Obj': TomoP2D.Objects2D.ELLIPSE, 
              'C0' : float(np.random.uniform(low=0.7, high=0.9, size =1)), 
              'x0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'y0' : float(np.random.uniform(low=-1.0, high=0.5, size =1)),
              'a'  : float(np.random.uniform(low=0.02, high=0.3, size = 1)),
              'b'  : float(np.random.uniform(low=0.02, high=0.3, size=1)),
              'phi': float(np.random.uniform(low=0, high=180, size=1))}
            cc = {'Obj': TomoP2D.Objects2D.RECTANGLE, 
              'C0' : float(np.random.uniform(low=0.7, high=0.9, size =1)), 
              'x0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'y0' : float(np.random.uniform(low=-1.0, high=0.5, size =1)),
              'a'  : float(np.random.uniform(low=0.02, high=0.3, size = 1)),
              'b'  : float(np.random.uniform(low=0.02, high=0.3, size=1)),
              'phi': float(np.random.uniform(low=0, high=180, size=1))}
            dd = {'Obj': TomoP2D.Objects2D.ELLIPSE, 
              'C0' : float(np.random.uniform(low=0.7, high=0.9, size =1)), 
              'x0' : float(np.random.uniform(low=-1.0, high=1.0, size =1)),
              'y0' : float(np.random.uniform(low=-1.0, high=0.5, size =1)),
              'a'  : float(np.random.uniform(low=0.02, high=0.3, size = 1)),
              'b'  : float(np.random.uniform(low=0.02, high=0.3, size=1)),
              'phi': float(np.random.uniform(low=0, high=180, size=1))}
            pps.append(pp)
            pps.append(bb)
            pps.append(cc)
            pps.append(dd)
    
        plt.close('all')
        
        shapes = np.zeros((256, 256), dtype=np.uint8)
        background = np.zeros((256, 256), dtype=np.uint8)
        
        for i in range(0,num_back_rectangles,1):
            phantom_2D = (TomoP2D.Object(256,back[i]))
            background = (background + phantom_2D)
        for i in range(0,num_rectangles,1):
            phantom_2D = (TomoP2D.Object(256,pps[i]))
            shapes = (shapes + phantom_2D)
              
        noise = np.random.uniform(low=0,high=1, size=(256, 256))
        filter1 = shapes >1
        shapes[filter1] = 1
        filter2 = background >1
        background[filter1] = 1
        IMAGE.append(shapes)
        nos = (background*0.2)+(noise*1.0)+(shapes*1) 
        scaler = np.amax(nos)
        nos = nos / scaler
        NOISY_IMAGE.append(nos)
        
        #%%
    #plt.figure(1)
    #plt.rcParams.update({'font.size': 21}) 
#    NOISY_IMAGES = np.array(NOISY_IMAGE)
#    IMAGE = np.array(IMAGE)
#    np.save('TM_Images.npy', NOISY_IMAGES)
#    np.save('TM_Labels.npy', IMAGE)
    plt.imshow(NOISY_IMAGES[0],  cmap="BuPu")
    plt.colorbar(ticks=[0, 0.5, 1], orientation='vertical')
    plt.title('{}''{}'.format('2D Phantom using model no.',model))
    plt.show()
    return np.array([NOISY_IMAGES[0],IMAGES[0]])
Exemple #13
0
    def process_frames(self, data):
        # print "The input data shape is", data[0].shape
        if (self.out_shape_sino[1] == 1):
            # create a 2D phantom
            model = TomoP2D.Model(self.model, self.dims, self.path_library2D)
            # create a 2D sinogram
            projdata_clean = TomoP2D.ModelSino(self.model, self.dims,
                                               self.detectors_num, self.angles,
                                               self.path_library2D)
            # Adding artifacts and noise
            # forming dictionaries with artifact types
            _noise_ = {
                'type': self.parameters['artifacts_noise_type'],
                'sigma': self.parameters['artifacts_noise_sigma'],
                'seed': 0,
                'prelog': False
            }

            # misalignment dictionary
            _sinoshifts_ = {}
            if self.parameters[
                    'artifacts_misalignment_maxamplitude'] is not None:
                _sinoshifts_ = {
                    'maxamplitude':
                    self.parameters['artifacts_misalignment_maxamplitude']
                }

            # adding zingers and stripes
            _zingers_ = {}
            if self.parameters['artifacts_zingers_percentage'] is not None:
                _zingers_ = {
                    'percentage':
                    self.parameters['artifacts_zingers_percentage'],
                    'modulus': 10
                }

            _stripes_ = {}
            if self.parameters['artifacts_stripes_percentage'] is not None:
                _stripes_ = {
                    'percentage':
                    self.parameters['artifacts_stripes_percentage'],
                    'maxthickness':
                    self.parameters['artifacts_stripes_maxthickness'],
                    'intensity':
                    self.parameters['artifacts_stripes_intensity'],
                    'type':
                    self.parameters['artifacts_stripes_type'],
                    'variability':
                    self.parameters['artifacts_stripes_variability']
                }

            if self.parameters[
                    'artifacts_misalignment_maxamplitude'] is not None:
                [projdata,
                 shifts] = _Artifacts_(projdata_clean, _noise_, _zingers_,
                                       _stripes_, _sinoshifts_)
            else:
                projdata = _Artifacts_(projdata_clean, _noise_, _zingers_,
                                       _stripes_, _sinoshifts_)
        else:
            # create a 3D phantom
            frame_idx = self.out_pData[0].get_current_frame_idx()[0]
            model = TomoP3D.ModelSub(self.model, self.dims,
                                     (frame_idx, frame_idx + 1),
                                     self.path_library3D)
            model = np.swapaxes(model, 0, 1)
            model = np.flipud(model[:, 0, :])
            # create a 3D projection data
            projdata_clean = TomoP3D.ModelSinoSub(
                self.model, self.dims, self.detectors_num, self.dims,
                (frame_idx, frame_idx + 1), self.angles, self.path_library3D)
            # Adding artifacts and noise
            # forming dictionaries with artifact types
            _noise_ = {
                'type': self.parameters['artifacts_noise_type'],
                'sigma': self.parameters['artifacts_noise_sigma'],
                'seed': 0,
                'prelog': False
            }

            # misalignment dictionary
            _sinoshifts_ = {}
            if self.parameters[
                    'artifacts_misalignment_maxamplitude'] is not None:
                _sinoshifts_ = {
                    'maxamplitude':
                    self.parameters['artifacts_misalignment_maxamplitude']
                }

            # adding zingers and stripes
            _zingers_ = {}
            if self.parameters['artifacts_zingers_percentage'] is not None:
                _zingers_ = {
                    'percentage':
                    self.parameters['artifacts_zingers_percentage'],
                    'modulus': 10
                }

            _stripes_ = {}
            if self.parameters['artifacts_stripes_percentage'] is not None:
                _stripes_ = {
                    'percentage':
                    self.parameters['artifacts_stripes_percentage'],
                    'maxthickness':
                    self.parameters['artifacts_stripes_maxthickness'],
                    'intensity':
                    self.parameters['artifacts_stripes_intensity'],
                    'type':
                    self.parameters['artifacts_stripes_type'],
                    'variability':
                    self.parameters['artifacts_stripes_variability']
                }

            if self.parameters[
                    'artifacts_misalignment_maxamplitude'] is not None:
                [projdata,
                 shifts] = _Artifacts_(projdata_clean, _noise_, _zingers_,
                                       _stripes_, _sinoshifts_)
            else:
                projdata = _Artifacts_(projdata_clean, _noise_, _zingers_,
                                       _stripes_, _sinoshifts_)
            projdata = np.swapaxes(projdata, 0, 1)
        return [projdata, model]
Exemple #14
0
def generateImage():
    model = 6  # selecting a model
    N_size = 256
    #specify a full path to the parameters file
    pathTP = 'Phantom2DLibrary.dat'
    #This will generate a N_size x N_size phantom (2D)
    phantom_2D = TomoP2D.Model(model, N_size, pathTP)

    Labels = []
    Labels_array = []
    Images = []
    shapeTypes = [TomoP2D.Objects2D.RECTANGLE, TomoP2D.Objects2D.ELLIPSE]

    for a in range(0, 1, 1):
        objects = []
        background = []
        array_label = []
        num_back_shapes = np.random.randint(200, 400)

        for i in range(0, num_back_shapes, 1):
            shapeRand = np.random.randint(2)
            background.append(genTomoShape(shapeTypes[shapeRand]))

        num_shapes = np.random.randint(5, 20)
        num_shapes = 5

        insertImage = loadSimpleImg()

        label_temp = np.zeros((256, 256), dtype=np.uint8)
        image_temp = np.zeros((256, 256), dtype=np.uint8)

        temp_label_array = []

        for i in range(0, len(insertImage)):
            temp_label_array.append(label_temp)

        temp_label_array = np.array(temp_label_array)

        for i in range(0, num_shapes, 1):
            patternType = np.random.randint((insertImage.shape[0]))
            pattern = np.random.randint((insertImage[patternType].shape[0]))

            #Random pick of shape type
            shapeRand = np.random.randint(2)
            #Generate shape
            shape = TomoP2D.Object(256, genTomoShape(shapeTypes[shapeRand]))
            #add the shape to the laebl image and take away the original to get the positions where a new shape has been added.
            fit = ((temp_label_array[patternType] + shape) -
                   temp_label_array[patternType]) > 0
            #update the pixel values where the shape has been added, do no tjust add the pixel values together but replace them so the overlap is smooth
            temp_label_array[patternType][fit] = shape[fit]
            #filter looking for where the shape is
            shapeFilter = shape >= 0.5

            #for those positions where the shape exists set those values to the value in the image pattern
            shape[shapeFilter] = insertImage[patternType][pattern][shapeFilter]
            #add the shape to the image and take away the original to get the positions where a new shape has been added.
            fit = ((image_temp + shape) - image_temp) > 0
            #update the pixel values where the shape has been added, do no tjust add the pixel values together but replace them so the overlap is smooth
            image_temp[fit] = shape[fit]

        noise = np.random.uniform(low=0,
                                  high=np.amax(image_temp) * 1.0,
                                  size=(256, 256))
        nos = (image_temp * 1.0) + (noise * 0.2)

        Images.append(nos)
        Labels_array.append(np.array(temp_label_array))

        #%%
        item = []
        item.append(Images)
        item.append(Labels_array)
        item = np.array(item)

    return np.array(nos), np.array(temp_label_array)


#f,l =  generateImage()
#fig = plt.figure()
#ax = fig.add_subplot(121)
#ax.imshow(f)
#ax = fig.add_subplot(122)
#print(l.shape)
#ax.imshow(l[1])
#plt.show()
          x = np.random.rand() * 2
          y = np.random.rand() * 2
        max_length = R - (x**2 + y**2) ** 0.5
        max_length *= 4/(2**0.5)
        long_length = np.random.rand() * max_length
        short_length = np.random.rand() * long_length
    
      rot = np.random.randint(0, 360)
      ob = {'Obj': shape,
            'C0' : density,
            'x0' : x,
            'y0' : y,
            'a'  : long_length,
            'b'  : short_length,
            'phi': rot}
    
      ob_list[ob_index] = ob
    
    #make these choices
    phantom = TomoP2D.Object(1499, ob_list)
    
    vol_geom = astra.creators.create_vol_geom(1499, 1499, -256, 256, -256, 256)
    proj_geom = astra.creators.create_proj_geom('parallel',1, 
                                           512, np.linspace(0, np.pi, 512, False))
    proj_id = astra.create_projector("cuda",proj_geom,vol_geom)
    vol_geom_rec = astra.create_vol_geom(512,512)
    sino_id, sinogram = astra.create_sino(phantom,proj_id, gpuIndex=1)
    
    np.save(os.path.join(phantoms_folder, phantom_name.format(i)), phantom)
    np.save(os.path.join(sinogram_folder, sino_name.format(i)), sinogram)
Exemple #16
0
import matplotlib.pyplot as plt

from tomophantom import TomoP2D

model = 1  # selecting a model

N_size = 512

#specify a full path to the parameters file

pathTP = r'C:\Users\zyv57124\Documents\TomoPhantom-master\TomoPhantom-master\functions\models\Phantom2DLibrary.dat'

#objlist = modelfile2Dtolist(pathTP, model) # one can extract parameters

#This will generate a N_size x N_size phantom (2D)

phantom_2D = TomoP2D.Model(model, N_size, pathTP)

plt.close('all')

plt.figure(1)

plt.rcParams.update({'font.size': 21})

plt.imshow(phantom_2D, vmin=0, vmax=1, cmap="BuPu")

plt.colorbar(ticks=[0, 0.5, 1], orientation='vertical')

plt.title('{}' '{}'.format('2D Phantom using model no.', model))
#Components : 01;
#TimeSteps : 1;
#Object : rectangle 1.00 -0.15 0.2 0.4 0.3 45;

import numpy as np
import matplotlib.pyplot as plt
from tomophantom import TomoP2D
import PIL
from PIL import Image

model = 6  # selecting a model
N_size = 256
#specify a full path to the parameters file
pathTP = r'C:\Users\zyv57124\Documents\TomoPhantom-master\TomoPhantom-master\functions\models\Phantom2DLibrary.dat'
#This will generate a N_size x N_size phantom (2D)
phantom_2D = TomoP2D.Model(model, N_size, pathTP)

IMAGE = []
NOISY_IMAGE = []

for a in range(0, 1, 1):
    pps = []
    num_rectangles = np.random.randint(1, 11)
    for i in range(0, num_rectangles, 1):
        pp = {
            'Obj': TomoP2D.Objects2D.RECTANGLE,
            'C0': 1.0,
            'x0': float(np.random.uniform(low=-0.5, high=0.5, size=1)),
            'y0': float(np.random.uniform(low=-0.5, high=0.5, size=1)),
            'a': float(np.random.uniform(low=0.1, high=1.3, size=1)),
            'b': float(np.random.uniform(low=0.02, high=0.05, size=1)),
Exemple #18
0
if device=='1':
    dev = 'gpu'
else:
    dev = 'cpu'

# Create phantom for TV 2D dynamic tomography 

model = 102  # note that the selected model is temporal (2D + time)
N = 50 # set dimension of the phantom
# one can specify an exact path to the parameters file
# path_library2D = '../../../PhantomLibrary/models/Phantom2DLibrary.dat'
path = os.path.dirname(tomophantom.__file__)
path_library2D = os.path.join(path, "Phantom2DLibrary.dat")
#This will generate a N_size x N_size x Time frames phantom (2D + time)

phantom_2Dt = TomoP2D.ModelTemporal(model, N, path_library2D)[0:-1:2]


fig = plt.figure()
ims1 = []
for sl in range(0,np.shape(phantom_2Dt)[0]):    
    im1 = plt.imshow(phantom_2Dt[sl,:,:], animated=True, vmin=0, vmax=1)    
    ims1.append([im1])
ani1 = animation.ArtistAnimation(fig, ims1, interval=500,repeat_delay=10)
plt.show() 

    
ig = ImageGeometry(voxel_num_x = N, voxel_num_y = N, channels = np.shape(phantom_2Dt)[0])
data = ImageData(phantom_2Dt, geometry=ig)

detectors = N
Exemple #19
0
@author: Daniil Kazantsev
"""
import numpy as np
import matplotlib.pyplot as plt
from tomophantom import TomoP2D
import os
import tomophantom
from tomophantom.supp.qualitymetrics import QualityTools

model = 4 # select a model
N_size = 512 # set dimension of the phantom
# one can specify an exact path to the parameters file
# path_library2D = '../../../PhantomLibrary/models/Phantom2DLibrary.dat'
path = os.path.dirname(tomophantom.__file__)
path_library2D = os.path.join(path, "Phantom2DLibrary.dat")
phantom_2D = TomoP2D.Model(model, N_size, path_library2D)

plt.close('all')
plt.figure(1)
plt.rcParams.update({'font.size': 21})
plt.imshow(phantom_2D, vmin=0, vmax=1, cmap="gray")
plt.colorbar(ticks=[0, 0.5, 1], orientation='vertical')
plt.title('{}''{}'.format('2D Phantom using model no.',model))

# create sinogram analytically
angles_num = int(0.5*np.pi*N_size); # angles number
angles = np.linspace(0.0,179.9,angles_num,dtype='float32')
angles_rad = angles*(np.pi/180.0)
P = int(np.sqrt(2)*N_size) #detectors

sino_an = TomoP2D.ModelSino(model, N_size, P, angles, path_library2D)
Exemple #20
0
def foam2D(x0min, x0max, y0min, y0max, c0min, c0max, ab_min, ab_max, N_size,
           tot_objects, object_type):
    import numpy as np
    import math
    import random
    #2D functions
    from tomophantom import TomoP2D
    from tomophantom.TomoP2D import Objects2D
    attemptsNo = 2000  # the number of attempts to fit the object
    # objects accepted: 'ellipse', 'parabola', 'gaussian', 'mix'
    mix_objects = False
    if (object_type == 'ellipse'):
        object_type = Objects2D.ELLIPSE
    elif (object_type == 'parabola'):
        object_type = Objects2D.PARABOLA
    elif (object_type == 'gaussian'):
        object_type = Objects2D.GAUSSIAN
    elif (object_type == 'mix'):
        mix_objects = True
    else:
        raise TypeError(
            'object_type can be only ellipse, parabola, gaussian or mix')
    X0 = np.float32(np.zeros(tot_objects))
    Y0 = np.float32(np.zeros(tot_objects))
    AB = np.float32(np.zeros(tot_objects))
    C0_var = np.float32(np.zeros(tot_objects))
    for i in range(0, tot_objects):
        (x0, y0, c0, ab) = rand_init2D(x0min, x0max, y0min, y0max, c0min,
                                       c0max, ab_min, ab_max)
        if (i > 0):
            breakj = False
            for j in range(0, attemptsNo):
                if (breakj == True):
                    (x0, y0, c0, ab) = rand_init2D(x0min, x0max, y0min, y0max,
                                                   c0min, c0max, ab_min,
                                                   ab_max)
                    breakj = False
                else:
                    for l in range(
                            0, i
                    ):  # checks consistency with previously created objects
                        dist = math.sqrt((X0[l] - x0)**2 + (Y0[l] - y0)**2)
                        if (dist < (ab + AB[l])) or ((abs(x0) + ab)**2 +
                                                     (abs(y0) + ab)**2 > 1.0):
                            breakj = True
                            break
                    if (breakj == False
                        ):  # re-initialise if doesn't fit the criteria
                        X0[i] = x0
                        Y0[i] = y0
                        AB[i] = ab
                        C0_var[i] = c0
                        break
        if (AB[i] == 0.0):
            X0[i] = x0
            Y0[i] = y0
            AB[i] = 0.0001
            C0_var[i] = c0

    myObjects = []  # dictionary of objects
    for obj in range(0, len(X0)):
        if (mix_objects == True):
            rand_obj = random.randint(0, 2)
            if (rand_obj == 0):
                object_type = Objects2D.ELLIPSE
            if (rand_obj == 1):
                object_type = Objects2D.PARABOLA
            if (rand_obj == 2):
                object_type = Objects2D.GAUSSIAN
        curr_obj = {
            'Obj': object_type,
            'C0': C0_var[obj],
            'x0': X0[obj],
            'y0': Y0[obj],
            'a': AB[obj],
            'b': AB[obj],
            'phi': 0.0
        }
        myObjects.append(curr_obj)
    Object = TomoP2D.Object(N_size, myObjects)
    return (Object, myObjects)