Beispiel #1
0
def Normalization(reconspace, backprojector, sinogram):
    sinseg = sinogram.get_segment_by_sinogram(0)
    filler = np.ones(np.shape(stirextra.to_numpy(sinseg)))
    fillStirSpace(sinseg, filler)
    sinogram.set_segment(sinseg)

    backprojector.back_project(reconspace, sinogram)
    npReconSpace = stirextra.to_numpy(reconspace)
    pyvpx.numpy2vpx(npReconSpace, 'NormMap.vpx')
    return reconspace
Beispiel #2
0
def test_ProjData():
    s=Scanner.get_scanner_from_name("ECAT 962")
    #ProjDataInfoCTI(const shared_ptr<Scanner>& scanner_ptr,
    #		  const int span, const int max_delta,
    #             const int num_views, const int num_tangential_poss, 
    #
    projdatainfo=ProjDataInfo.ProjDataInfoCTI(s,3,9,8,6)
    #print projdatainfo
    projdata=ProjDataInMemory(ExamInfo(), projdatainfo)
    np=stirextra.to_numpy(projdata)
    np+=2
    projdata.fill(np.flat)
    seg0=stirextra.to_numpy(projdata.get_segment_by_sinogram(0))
    assert(seg0.max() == 2)
Beispiel #3
0
def test_ProjData():
    s = Scanner.get_scanner_from_name("ECAT 962")
    #construct_proj_data_info(const shared_ptr<Scanner>& scanner_ptr,
    #		  const int span, const int max_delta,
    #             const int num_views, const int num_tangential_poss,
    #
    projdatainfo = ProjDataInfo.construct_proj_data_info(s, 3, 9, 8, 6)
    #print projdatainfo
    projdata = ProjDataInMemory(ExamInfo(), projdatainfo)
    np = stirextra.to_numpy(projdata)
    np += 2
    projdata.fill(np.flat)
    seg0 = stirextra.to_numpy(projdata.get_segment_by_sinogram(0))
    assert (seg0.max() == 2)
Beispiel #4
0
def test_Array3Diterator():
    a=FloatArray3D(IndexRange3D(Int3BasicCoordinate((1,3,-1)), Int3BasicCoordinate((3,9,5))))
    for i1,i2 in zip(a.flat(), range(a.size_all())):
        i1=i2;
    np=stirextra.to_numpy(a);
    for i1,i2 in zip(a.flat(), np.flat):
        assert abs(i1-i2)<.01
Beispiel #5
0
def plot_sinogram_profiles(projection_data_list, sumaxis=0, select=0):
    """
    Plot a profile through STIR.ProjData.
    Average over all sinograms to reduce noise
    projection_data_list: list of sinogram file names or stir.ProjData objects to load and plot
    sumaxis: axes to sum over (passed to numpy.sum(..., axis))
    select: element to select after summing
    """
    plt.figure()
    ax = plt.subplot(111)

    for f in projection_data_list:
        label = ""
        if isinstance(f, str):
            print(f"Handling:\n  {f}")
            label = f
            f = stir.ProjData_read_from_file(f)
 
        if isinstance(f, stir.ProjData):
            f = stirextra.to_numpy(f)
            
        else:
            raise ValueError("wrong type of argument")

        plt.plot(np.sum(f, axis=sumaxis)[select,:], label=label)

    plt.title(f"Summing over axis {sumaxis} with element {select}")
    ax.legend()
    plt.show()
Beispiel #6
0
def test_Array3Diterator():
    a=FloatArray3D(IndexRange3D(Int3BasicCoordinate((1,3,-1)), Int3BasicCoordinate((3,9,5))))
    for i1,i2 in zip(a.flat(), range(a.size_all())):
        i1=i2;
    np=stirextra.to_numpy(a);
    for i1,i2 in zip(a.flat(), np.flat):
        assert abs(i1-i2)<.01
Beispiel #7
0
def test_Array2Diterator():
    a=FloatArray2D(IndexRange2D(Int2BasicCoordinate((1,3)), Int2BasicCoordinate((3,9))))
    for i1,i2 in itertools.izip(a.flat(), range(a.size_all())):
        i1=i2;
    np=stirextra.to_numpy(a);
    for i1,i2 in itertools.izip(a.flat(), np.flat):
        assert abs(i1-i2)<.01
Beispiel #8
0
def test_Array2Diterator():
    a = FloatArray2D(
        IndexRange2D(Int2BasicCoordinate((1, 3)), Int2BasicCoordinate((3, 9))))
    for i1, i2 in zip(a.flat(), range(a.size_all())):
        i1 = i2
    np = stirextra.to_numpy(a)
    for i1, i2 in zip(a.flat(), np.flat):
        assert abs(i1 - i2) < .01
Beispiel #9
0
def test_Array2D():
    minind=Int2BasicCoordinate((3,3));
    a=FloatArray2D(IndexRange2D(minind, Int2BasicCoordinate((9,8))))
    a.fill(2);
    ind=Int2BasicCoordinate((4,5));
    a[ind]=4
    np=stirextra.to_numpy(a);
    assert np[(0,0)]==2
    npind=(ind[1]-minind[1], ind[2]-minind[2])
    assert np[npind]==a[ind]
Beispiel #10
0
def test_Array2D():
    minind = Int2BasicCoordinate((3, 3))
    a = FloatArray2D(IndexRange2D(minind, Int2BasicCoordinate((9, 8))))
    a.fill(2)
    ind = Int2BasicCoordinate((4, 5))
    a[ind] = 4
    np = stirextra.to_numpy(a)
    assert np[(0, 0)] == 2
    npind = (ind[1] - minind[1], ind[2] - minind[2])
    assert np[npind] == a[ind]
Beispiel #11
0
    def _call(self, volume, out):
        """Forward project a volume."""
        # Set volume data
        self.volume.fill(volume.asarray().flat)

        # project
        with StirVerbosity(0):
            self.projector.forward_project(self.proj_data, self.volume)

        # make ODL data
        out[:] = stirextra.to_numpy(self.proj_data)
Beispiel #12
0
    def _call(self, projections, out):
        """Back project."""
        # Set projection data
        self.proj_data.fill(projections.asarray().flat)

        # back-project
        with StirVerbosity(0):
            self.back_projector.back_project(self.volume, self.proj_data)

        # make ODL data
        out[:] = stirextra.to_numpy(self.volume)
Beispiel #13
0
    def _call(self, volume, out):
        """Forward project a volume."""
        # Set volume data
        self.volume.fill(volume.asarray().flat)

        # project
        with StirVerbosity(0):
            self.projector.forward_project(self.proj_data, self.volume)

        # make ODL data
        out[:] = stirextra.to_numpy(self.proj_data)
Beispiel #14
0
    def _call(self, projections, out):
        """Back project."""
        # Set projection data
        self.proj_data.fill(projections.asarray().flat)

        # back-project
        with StirVerbosity(0):
            self.back_projector.back_project(self.volume, self.proj_data)

        # make ODL data
        out[:] = stirextra.to_numpy(self.volume)
Beispiel #15
0
def call_with_stir_buffer(function,
                          b_in,
                          b_out,
                          v_in,
                          subset_num=0,
                          num_subsets=1,
                          clear_buffer=False):
    b_in.fill(v_in.asarray().flat)
    if clear_buffer:
        b_out.fill(0)
    function(b_out, b_in, subset_num, num_subsets)
    return to_numpy(b_out)
Beispiel #16
0
def test_Array3D():
    minind=Int3BasicCoordinate((3,3,5));
    a=FloatArray3D(IndexRange3D(minind, Int3BasicCoordinate((9,8,7))))
    a.fill(2);
    ind=Int3BasicCoordinate((4,5,6));
    a[ind]=4
    np=stirextra.to_numpy(a);
    assert np[(0,0,1)]==2
    npind=(ind[1]-minind[1], ind[2]-minind[2], ind[3]-minind[3])
    assert np[npind]==a[ind]
    np+=2
    a.fill(np.flat)
    assert np[(0,0,1)]==4
    assert np[npind]==a[ind]
Beispiel #17
0
def test_Array3D():
    minind = Int3BasicCoordinate((3, 3, 5))
    a = FloatArray3D(IndexRange3D(minind, Int3BasicCoordinate((9, 8, 7))))
    a.fill(2)
    ind = Int3BasicCoordinate((4, 5, 6))
    a[ind] = 4
    np = stirextra.to_numpy(a)
    assert np[(0, 0, 1)] == 2
    npind = (ind[1] - minind[1], ind[2] - minind[2], ind[3] - minind[3])
    assert np[npind] == a[ind]
    np += 2
    a.fill(np.flat)
    assert np[(0, 0, 1)] == 4
    assert np[npind] == a[ind]
Beispiel #18
0
def MLEMRecon(normMap, reconspace, imspaceError, forwardprojector, backprojector, sinogram, measurement, nIter = 30):
    imspaceError.fill(1)
    
    meascomp = measurement.get_segment_by_sinogram(0)
    npNormMap = stirextra.to_numpy(normMap)

    for iter in range(nIter):
        sinogram.fill(0)
        forwardprojector.forward_project(sinogram, reconspace);
        sinocomp = sinogram.get_segment_by_sinogram(0)
    
        #populate error sinogram
        error = stirextra.to_numpy(meascomp) /stirextra.to_numpy(sinocomp)
        error[np.isnan(error)] = 1
        error[np.isinf(error)] = 1
        #error[error > 1E10] = 1;
        #error[error < 1E-10] = 1;
        
        sinocompy = fillStirSpace(sinocomp, error)
        sinogram.set_segment(sinocompy)

        #backproject error
        backprojector.back_project(imspaceError, sinogram)
        image = stirextra.to_numpy(reconspace)
        error = stirextra.to_numpy(imspaceError)
        
        error = error/npNormMap
        #error[error > 1E10] = 0
        error[np.isinf(error)] = 0
        error[np.isnan(error)] = 1
        #pylab.imshow(error[0,:,:]), pylab.show()

        #update image
        image = image * error
        reconspace = fillStirSpace(reconspace, image)
    return reconspace
Beispiel #19
0
def forwardProjectionShiftError(yShift, forwardProjector, shiftingSino, referenceSino, image, shiftImage, iter, iFrame):
    
    npimage = stirextra.to_numpy(image)

    npshiftim = np.zeros(np.shape(npimage))
    ndimage.shift(npimage, [0, yShift, 0], output = npshiftim)
    shiftImage = fillStirSpace(shiftImage, npshiftim)
    
    #Forward project
    forwardProjector.forward_project(shiftingSino, shiftImage)

    #Calculate error measure
    shiftingSinoExtr =  stirextra.to_numpy(shiftingSino.get_segment_by_sinogram(0))
    shiftingSinoExtr /= np.sum(shiftingSinoExtr)

    referenceSinoExtr = stirextra.to_numpy(referenceSino.get_segment_by_sinogram(0))
    referenceSinoExtr /= np.sum(referenceSinoExtr)

    npShiftingSino =shiftingSinoExtr - referenceSinoExtr

    npShiftingSino[np.isnan(npShiftingSino)]   = 0
    npShiftingSino[np.isinf(npShiftingSino)]   = 0

    return np.sum(npShiftingSino**2)
Beispiel #20
0
def test_sinogram():
    """
    Make sure that the sinogram offsets are correct.
    """
    scanner = mCT()
    compression, proj, projections = get_projections(scanner)

    sinfo = compression._get_sinogram_info()

    seg_ind = np.random.randint(len(sinfo))
    segment = sinfo[seg_ind][0]
    ax_ind = np.random.randint(sinfo[seg_ind][1])

    offset = compression.get_offset(segment, ax_ind)
    computed = projections[offset].asarray()
    expected = stirextra.to_numpy(proj.proj_data.get_sinogram(ax_ind, segment))
    assert pytest.approx(computed) == expected
import stirextra

#%% You could set "interactive display" on
# This would mean that plots are generated and the program immediatelly continues,
# as opposed to waiting for you to close a figure.

#pylab.ion()

#%% image display

# read an image using STIR
image = stir.FloatVoxelsOnCartesianGrid.read_from_file(
    '../../recon_test_pack/test_image_3.hv')

# convert data to numpy 3d array
npimage = stirextra.to_numpy(image)

# make some plots
# first a bitmap
pylab.figure()
pylab.imshow(npimage[10, :, :], cmap='hot')
pylab.title('slice 10 (starting from 0)')
pylab.show()
# now a profile
pylab.figure()
pylab.plot(npimage[10, 45, :])
pylab.xlabel('x')
pylab.title('slice 10, line 45 (starting from 0)')
pylab.show()

#%% Let's read some projection data
Beispiel #22
0
#%% create projection data for output of forward projection
# We'll just create the data in memory here
projdataout = stir.ProjDataInMemory(projdata.get_exam_info(),
                                    projdata.get_proj_data_info())
# Note: we could write to file, but it is right now a bit complicated to open a
# file for read/write:
#  inout=stir.ios.trunc|stir.ios.ios_base_in|stir.ios.out;
#  projdataout=stir.ProjDataInterfile(projdata.get_exam_info(), projdata.get_proj_data_info(), 'my_test_python_projection.hs',inout);
#%% forward project an image. Here just some uniform data
target.fill(2)
forwardprojector.set_up(projdataout.get_proj_data_info(), target)
forwardprojector.forward_project(projdataout, target)
#%% display
seg = projdataout.get_segment_by_sinogram(0)
seg_array = stirextra.to_numpy(seg)
pylab.figure()
pylab.subplot(1, 2, 1)
pylab.imshow(seg_array[10, :, :])
pylab.title('Forward projection')
pylab.subplot(1, 2, 2)
pylab.plot(seg_array[10, 0, :])
pylab.show()
#%% backproject this projection data
# we need to set the target to zero first, otherwise it will add to existing numbers.
target.fill(0)
backprojector.set_up(projdataout.get_proj_data_info(), target)
backprojector.back_project(target, projdataout)
#%% display
# This shows a beautiful pattern, a well-known feature of a ray-tracing matrix
target_array = stirextra.to_numpy(target)
Beispiel #23
0
# Without it, the python shell will wait after every pylab.show() for you
# to close the window.
try:
    pylab.ion()
except:
    print("Enabling interactive-mode for plotting failed. Continuing.")

s = recon.set_up(target)
if (s == stir.Succeeded(stir.Succeeded.yes)):
    pylab.figure()
    for iter in range(1, 4):
        print('\n--------------------- Subiteration ', iter)
        recon.set_start_subiteration_num(iter)
        recon.set_num_subiterations(iter)
        s = recon.reconstruct(target)
        # currently we need to explicitly prevent recomputing sensitivity
        # when we call reconstruct() again in the next iteration
        poissonobj.set_recompute_sensitivity(False)
        # extract to python for plotting
        npimage = stirextra.to_numpy(target)
        pylab.plot(npimage[10, 30, :])
        pylab.show()

    # plot slice of final image
    pylab.figure()
    pylab.imshow(npimage[10, :, :])
    # Keep figures open until user closes them
    pylab.show(block=True)
else:
    print('Error setting-up reconstruction object')
Beispiel #24
0
import stir
import stirextra

#%% You could set "interactive display" on
# This would mean that plots are generated and the program immediatelly continues,
# as opposed to waiting for you to close a figure.

#pylab.ion()

#%% image display

# read an image using STIR
image=stir.FloatVoxelsOnCartesianGrid.read_from_file('../../recon_test_pack/test_image_3.hv')

# convert data to numpy 3d array
npimage=stirextra.to_numpy(image);

# make some plots
# first a bitmap
pylab.figure()
pylab.imshow(npimage[10,:,:], cmap='hot');
pylab.title('slice 10 (starting from 0)')
pylab.show()
# now a profile
pylab.figure();
pylab.plot(npimage[10,45,:]);
pylab.xlabel('x')
pylab.title('slice 10, line 45 (starting from 0)')
pylab.show()

Beispiel #25
0
def volume_from_voxels(_voxels):
    space = space_from_stir_domain(_voxels)
    arr = to_numpy(_voxels)
    element = space.element(arr)
    return element
Beispiel #26
0
def forwardProject(npSource):
    guessVolume.fill(npSource.flat)
    forwardSino2D.fill(0)
    forwardprojector2D.forward_project(forwardSino2D, guessVolume)
    return stirextra.to_numpy(forwardSino2D)
Beispiel #27
0
def backProject(npSino):
    guessVolume.fill(0)
    forwardSino2D.fill(npSino.flat)
    backprojector2D.back_project(guessVolume, forwardSino2D)
    return stirextra.to_numpy(guessVolume)
'''
image = np.zeros((160,160))
image[65:95, 65:95] = 1 
'''


## TEST:  Recons maken na verschillende iteraties -> som berekenen 
testList = []
sumList = [] 
test      = stir.FloatVoxelsOnCartesianGrid(projdata_info, 1,
                stir.FloatCartesianCoordinate3D(stir.make_FloatCoordinate(0,0,0)),
                stir.IntCartesianCoordinate3D(stir.make_IntCoordinate(1,200,200)))  # Lengte moet je gokken/weten 

for i in range(8): 
    test = test.read_from_file('output_config_Proj_1_{0}.hv'.format(i+1))
    testList.append(stirextra.to_numpy(test)) 
    sumList.append(np.sum(stirextra.to_numpy(test)[0,:,:]))

axisX = range(1,9,1)
plt.plot(axisX, sumList, axisX, [np.sum(image)]*len(axisX)), plt.title('Sum of OSMAPOSL recon (blue), sum of original image (green)'), plt.xlabel('Iteration number')
plt.savefig('./Plaatjes/OSMAPOSLSumAfterIterations.png')
plt.show()

for i in range(8): 
    plt.subplot(2,4,i+1), plt.imshow(testList[i][0,:,:], cmap=plt.cm.Greys_r, interpolation=None, vmin = 0), plt.title('Iteration {0}'.format(i))
plt.savefig('./Plaatjes/OSMAPOSLReconAfterIterations.png'.format(trueShiftPixels))
plt.show() 
## 


# Image shape ## 
projmatrix.set_up(projdata_info, originalImageS)

# Create projectors
forwardprojector = stir.ForwardProjectorByBinUsingProjMatrixByBin(projmatrix)
backprojector = stir.BackProjectorByBinUsingProjMatrixByBin(projmatrix)

#_________________________MEASUREMENT_______________________________
measurement = stir.ProjDataInMemory(stir.ExamInfo(), projdata_info)
measurementListP = []
MotionModel.setOffset(0.0)

for i in range(nFrames):
    forwardprojector.forward_project(measurement, phantomS[i])
    measurement.write_to_file('sinoMeas_{}.hs'.format(i + 1))
    measurementS = measurement.get_segment_by_sinogram(0)
    measurementP = stirextra.to_numpy(measurementS)
    #measurementP /= np.sum(measurementP)
    if (noise):
        measurementP = sp.random.poisson(measurementP)
    measurementListP.append(measurementP)
    plt.subplot(2, nFrames / 2 + 1,
                i + 1), plt.imshow(measurementP[0, :, :],
                                   cmap=plt.cm.Greys_r,
                                   interpolation=None,
                                   vmin=0), plt.title('Meas. TF0')

plt.savefig(figSaveDir + 'Fig{}_TrueShift{}_Measurements.png'.format(
    numFigures, trueShiftAmplitude))
numFigures += 1
plt.close()
Beispiel #30
0
# Define the time frames - we are just defining one timeframe starting at 0 and ending at 10s.
time_frames = stir.TimeFrameDefinitions()
time_frames.set_num_time_frames(1)
time_frames.set_time_frame(1, 0, 10)
lm_to_projdata.set_time_frame_definitions(time_frames)

# Read template ProjData.
template_projdata = stir.ProjData.read_from_file("../../recon_test_pack/Siemens_mMR_seg2.hs")
lm_to_projdata.set_template_proj_data_info(template_projdata.get_proj_data_info())

# Perform the actual processing.
lm_to_projdata.set_up()
lm_to_projdata.process_data()

# Read in the generated proj data and visualise them (looks a bit like abstract art, 
# as there are very few counts in this example data).
generated_projdata = stir.ProjData.read_from_file("output_projdata_f1g1d0b0.hs")
first_segment = generated_projdata.get_segment_by_sinogram(0)
projdata_np = stirextra.to_numpy(first_segment)
plt.figure()
plt.imshow(projdata_np[projdata_np.shape[0] // 2, :, :])  # plot the middle slice
plt.title("sinogram 10 (starting from 0)")
plt.clim(0, projdata_np.max() * 0.9)
plt.colorbar()
plt.show(block=True)

# Finally, let's keep the example folder clean.
os.remove("output_projdata_f1g1d0b0.hs")
os.remove("output_projdata_f1g1d0b0.s")
projmatrix.set_num_tangential_LORs(nLOR)
projmatrix.set_up(projdata_info, originalImageS)

# Create projectors
forwardprojector = stir.ForwardProjectorByBinUsingProjMatrixByBin(projmatrix)
backprojector = stir.BackProjectorByBinUsingProjMatrixByBin(projmatrix)

# Creating an instance for the sinogram (measurement), it is not yet filled
measurement = stir.ProjDataInMemory(stir.ExamInfo(), projdata_info)

# Forward project originalImageS and store in measurement
forwardprojector.forward_project(measurement, originalImageS)

# Converting the stir sinogram to a numpy sinogram
measurementS = measurement.get_segment_by_sinogram(0)
measurementP = stirextra.to_numpy(measurementS)

#plt.figure(2), plt.title('Sinogram original image'), plt.imshow(measurementP[0,:,:]), plt.show()

# Backprojecting the sinogram to get an image
finalImageS = stir.FloatVoxelsOnCartesianGrid(
    projdata_info, 1,
    stir.FloatCartesianCoordinate3D(stir.make_FloatCoordinate(0, 0, 0)),
    stir.IntCartesianCoordinate3D(
        stir.make_IntCoordinate(
            np.shape(originalImageP)[0],
            np.shape(originalImageP)[1],
            np.shape(originalImageP)[2])))

backprojector.back_project(finalImageS, measurement)
finalImageP = stirextra.to_numpy(finalImageS)
# create a coordinate for the centre (note the z,y,x order)
centre=stir.FloatCartesianCoordinate3D(z_centre,0,0)
# create a geometrical shape
shape=stir.EllipsoidalCylinder(length, radius, radius,
                               centre)
#%% we set the image to a discretised version of this shape
# (the last argument means we'll sample every voxel only once)
shape.construct_volume(image_data, stir.IntCartesianCoordinate3D(1,1,1))
#%% Let's add another translated cylinder
# The way to do this is currently still awkward. Apologies.
shape.translate(stir.FloatCartesianCoordinate3D(15,90,40))
# make a clone and fill that one with the second shape
image_data2=image_data.clone()
shape.construct_volume(image_data2, stir.IntCartesianCoordinate3D(1,1,1))
# now add that to the previous one (currently messy as we need to pass through numpy, sorry)
image_data_array=stirextra.to_numpy(image_data);
image_data_array+=stirextra.to_numpy(image_data2);
image_data.fill(image_data_array.flat)
#%% display 2 transaxial slices of the volume
maxforplot=image_data.find_max(); # save for display
image_data_array=stirextra.to_numpy(image_data);
plt.figure();
plt.subplot(1,2,1)
plt.imshow(image_data_array[middle_slice,:,:]);
plt.clim(0,maxforplot)
plt.title('slice %d' % middle_slice)
plt.subplot(1,2,2)
plt.imshow(image_data_array[middle_slice+5,:,:]);
plt.title('slice %d' % (middle_slice+5))
plt.clim(0,maxforplot)
Beispiel #33
0
import os
import numpy as np
import time
#%% go to directory with input files

print("\nRunning ROI_demo.py")
os.chdir('../recon_demo')
image_filename = 'init.hv'

# Load image from file (for shape)
print(f"Loading {image_filename} as image...")
image = stir.FloatVoxelsOnCartesianGrid.read_from_file(image_filename)

print("Populating image with random values...")
# Make a copy in numpy, populate random voxel value and back-fill STIR FloatVoxelsOnCartesianGrid object
image_numpy = stirextra.to_numpy(image)
image_numpy = np.random.random(image_numpy.shape)
image.fill(image_numpy.flat)

# Construct an example shape
print(
    "Creating a EllipsoidalCylinder object as the Region Of Interest (ROI)...")
ROI_shape = stir.EllipsoidalCylinder(10, 5, 4,
                                     stir.FloatCartesianCoordinate3D(0, 0, 0))

# number_of_sample needs to be a 3D Int CartesianCoordinate
n = 10
print(f"Setting the number of samples of each axis to be {n}...")
number_of_samples = stir.IntCartesianCoordinate3D(n, n, n)

print(
Beispiel #34
0
forwardprojector=stir.ForwardProjectorByBinUsingProjMatrixByBin(projmatrix);
backprojector=stir.BackProjectorByBinUsingProjMatrixByBin(projmatrix);

#%% create projection data for output of forward projection
# We'll just create the data in memory here
projdataout=stir.ProjDataInMemory(projdata.get_exam_info(), projdata.get_proj_data_info());
# Note: we could write to file, but it is right now a bit complicated to open a
# file for read/write:
#  inout=stir.ios.trunc|stir.ios.ios_base_in|stir.ios.out;
#  projdataout=stir.ProjDataInterfile(projdata.get_exam_info(), projdata.get_proj_data_info(), 'my_test_python_projection.hs',inout);
#%% forward project an image. Here just some uniform data
target.fill(2);
forwardprojector.forward_project(projdataout, target);
#%% display
seg=projdataout.get_segment_by_sinogram(0);
seg_array=stirextra.to_numpy(seg);
pylab.figure();
pylab.subplot(1,2,1)
pylab.imshow(seg_array[10,:,:]);
pylab.title('Forward projection')
pylab.subplot(1,2,2)
pylab.plot(seg_array[10,0,:])
pylab.show()
#%% backproject this projection data
# we need to set the target to zero first, otherwise it will add to existing numbers.
target.fill(0)
backprojector.back_project(target, projdataout);
#%% display
# This shows a beautiful pattern, a well-known feature of a ray-tracing matrix
target_array=stirextra.to_numpy(target);
pylab.figure();
Beispiel #35
0
    NormSpace, backprojector,
    stir.ProjDataInMemory(stir.ExamInfo(), projdata_info))

locationList = []
#sinosum = np.zeros((1,252,344))
for iFrame in range(nFrames):
    reconList[iFrame] = MLEMRecon(NormSpace,
                                  reconList[iFrame],
                                  imspaceError,
                                  forwardprojector,
                                  backprojector,
                                  sinogramList[iFrame],
                                  measurementList[iFrame],
                                  nIter=5)
    #sinosum += stirextra.to_numpy(measurementList[iFrame].get_segment_by_sinogram(0))
recon = pyvpx.numpy2vpx(stirextra.to_numpy(reconList[0]), 'Recon0.vpx')
recon = pyvpx.numpy2vpx(stirextra.to_numpy(reconList[1]), 'Recon1.vpx')
recon = pyvpx.numpy2vpx(
    stirextra.to_numpy(reconList[1]) - stirextra.to_numpy(reconList[0]),
    'ReconDiff.vpx')
#recnp = stirextra.to_numpy(reconList[0])
#plt.imshow(recnp[0,:,:]), plt.show()
'''
guestimatespace = stir.FloatVoxelsOnCartesianGrid(projdata_info, 1,
                    stir.FloatCartesianCoordinate3D(stir.make_FloatCoordinate(0,0,0)),
                    stir.IntCartesianCoordinate3D(stir.make_IntCoordinate(np.shape(p)[0],np.shape(p)[1],np.shape(p)[2] ))) 

vShift = np.array([0,0,0])
vShiftOut, errorLog = OptimizeSinogramError(vShift, forwardprojector,sinogramList ,measurementList ,reconList[0], guestimatespace,  SurrogateSignal)
print(vShiftOut)
projmatrix = stir.ProjMatrixByBinUsingRayTracing(MotionModel)
projmatrix.set_num_tangential_LORs(nLOR)
projmatrix.set_up(projdata_info, originalImageS)

# Create projectors
forwardprojector    = stir.ForwardProjectorByBinUsingProjMatrixByBin(projmatrix)
backprojector       = stir.BackProjectorByBinUsingProjMatrixByBin(projmatrix)


#_________________________FIRST RECONSTRUCTION________________________
# Measurement/projections of inital time frame
measurement = stir.ProjDataInMemory(stir.ExamInfo(), projdata_info)
forwardprojector.forward_project(measurement, phantomS[0])
measurement.write_to_file('sino_1.hs')
measurementS = measurement.get_segment_by_sinogram(0)
measurementP = stirextra.to_numpy(measurementS)

# Image reconstruction using OSMAPOSL 
reconImageS = stir.FloatVoxelsOnCartesianGrid(projdata_info, 1,
                    stir.FloatCartesianCoordinate3D(stir.make_FloatCoordinate(0,0,0)),
                    stir.IntCartesianCoordinate3D(stir.make_IntCoordinate(np.shape(originalImageP)[0],np.shape(originalImageP)[1],np.shape(originalImageP)[2] ))) 
reconImageS.fill(1) # moet er staan 

MotionModel.setOffset(0.0)
reconOSMAPOSL = stir.OSMAPOSLReconstruction3DFloat(projmatrix, 'config_Image_1.par')
s = reconOSMAPOSL.set_up(reconImageS)
reconOSMAPOSL.reconstruct(reconImageS)
reconImagePRef = stirextra.to_numpy(reconImageS) # reference time frame


#_________________________SECOND RECONSTRUCTION________________________
z_centre = middle_slice * image_data.get_voxel_size().z()
# create a coordinate for the centre (note the z,y,x order)
centre = stir.FloatCartesianCoordinate3D(z_centre, 0, 0)
# create a geometrical shape
shape = stir.EllipsoidalCylinder(length, radius, radius, centre)
#%% we set the image to a discretised version of this shape
# (the last argument means we'll sample every voxel only once)
shape.construct_volume(image_data, stir.IntCartesianCoordinate3D(1, 1, 1))
#%% Let's add another translated cylinder
# The way to do this is currently still awkward. Apologies.
shape.translate(stir.FloatCartesianCoordinate3D(15, 90, 40))
# make a clone and fill that one with the second shape
image_data2 = image_data.clone()
shape.construct_volume(image_data2, stir.IntCartesianCoordinate3D(1, 1, 1))
# now add that to the previous one (currently messy as we need to pass through numpy, sorry)
image_data_array = stirextra.to_numpy(image_data)
image_data_array += stirextra.to_numpy(image_data2)
image_data.fill(image_data_array.flat)
#%% display 2 transaxial slices of the volume
maxforplot = image_data.find_max()
# save for display
image_data_array = stirextra.to_numpy(image_data)
plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(image_data_array[middle_slice, :, :])
plt.clim(0, maxforplot)
plt.title('slice %d' % middle_slice)
plt.subplot(1, 2, 2)
plt.imshow(image_data_array[middle_slice + 5, :, :])
plt.title('slice %d' % (middle_slice + 5))
plt.clim(0, maxforplot)
Beispiel #38
0
# Switch 'interactive' mode on for pylab.
# Without it, the python shell will wait after every pylab.show() for you
# to close the window. 
pylab.ion()

s=recon.set_up(target);
if (s==stir.Succeeded(stir.Succeeded.yes)):
    pylab.figure()
    pylab.hold(True)
    for iter in range(1,4):
        print '\n--------------------- Subiteration ', iter
        recon.set_start_subiteration_num(iter)
        recon.set_num_subiterations(iter)
        s=recon.reconstruct(target);
        # currently we need to explicitly prevent recomputing sensitivity when we
        # call reconstruct() again in the next iteration
        poissonobj.set_recompute_sensitivity(False)
        # extract to python for plotting
        npimage=stirextra.to_numpy(target);
        pylab.plot(npimage[10,30,:])
        pylab.show()

    # plot slice of final image
    pylab.figure()
    pylab.imshow(npimage[10,:,:])
    pylab.show()
else:
    print 'Error setting-up reconstruction object'

Beispiel #39
0
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# See STIR/LICENSE.txt for details

import numpy
import pylab
import stir
import stirextra

# read an image using STIR
image=stir.FloatVoxelsOnCartesianGrid.read_from_file('../../recon_test_pack/test_image_3.hv')

# convert data to numpy 3d array
npimage=stirextra.to_numpy(image);

# make some plots
# first a bitmap
pylab.figure()
pylab.imshow(npimage[10,:,:]);
pylab.title('slice 10 (starting from 0)')
pylab.show()
# now a profile
pylab.figure()
pylab.plot(npimage[10,45,:]);
pylab.xlabel('x')
pylab.title('slice 10, line 45 (starting from 0)')
pylab.show()
Beispiel #40
0
def test_load():
    volume_file = base / 'initial.hv'
    vol = volume_from_file(volume_file.as_posix())
    stir_vol = stir.FloatVoxelsOnCartesianGrid.read_from_file(volume_file.as_posix())
    assert pytest.approx(vol.asarray(), stirextra.to_numpy(stir_vol))