Пример #1
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
Пример #2
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)
Пример #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)
Пример #4
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)
Пример #5
0
#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)),
Пример #6
0
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
Пример #7
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]

    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])
Пример #8
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]])
Пример #9
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]
Пример #10
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()