CERN / TIGRE

TIGRE: Tomographic Iterative GPU-based Reconstruction Toolbox
BSD 3-Clause "New" or "Revised" License
550 stars 182 forks source link

plotting problem #393

Closed shaghayegh1376 closed 1 year ago

shaghayegh1376 commented 2 years ago

hello when i rewrite demos in jupyter notebook , in some demos like number 3/4/7/... , in plotting part , code run without error but for result it just show the blank , but in other demo number 5 it shows the result as image or gif.

i use python 3.8 anaconda 3 cuda 11.7 nvidia getforce rtx 3050

AnderBiguri commented 2 years ago

Thanks for the issue. Coudl you please show the code you have in the jupyter notebook?

shaghayegh1376 commented 2 years ago

On Tue, Aug 16, 2022 at 5:13 PM Biguri @.***> wrote:

Thanks for the issue. Coudl you please show the code you have in the jupyter notebook?

— Reply to this email directly, view it on GitHub https://github.com/CERN/TIGRE/issues/393#issuecomment-1216360748, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYD4MB3OYGGYHMR47JFPXO3VZNLTVANCNFSM56U5VVDQ . You are receiving this because you authored the thread.Message ID: @.***>

!/usr/bin/env python

coding: utf-8

In[67]:

%% DEMO 03: Generate sample data and add realistic CT noise to it.

#

This demo will show how to generate sample data for image reconstruction

In[90]:

get_ipython().run_line_magic('matplotlib', 'notebook') import matplotlib.pyplot as pl import matplotlib import tigre import numpy as np from tigre.utilities import sample_loader from tigre.utilities import CTnoise import scipy import scipy.sparse.linalg from tigre.utilities.Ax import Ax from tigre.utilities import sample_loader from tigre.utilities import sl3d

In[91]:

geo = tigre.geometry_default(high_resolution=False)

In[92]:

%% Define angles of projection and load phantom image

define projection angles (in radians)

angles = np.linspace(0, 2 * np.pi, 50)

load phatnom image

from IPython.display import Image head = sample_loader.load_head_phantom(geo.nVoxel)

head = head = scipy.io.loadmat("D:/شقایق جدید 1401/پروژه/code/TIGRE-master/Python/tigre/data/head.mat" , geo.n_proj)

head

In[93]:

Simulate forward projection.

To match with mathematical notation, the projection operation is called Ax

projections = tigre.Ax(head, geo, angles)

In[94]:

Add realistic noise. Adds photon scattering noise ('Poisson') and

electronic noise of the detector ('Gaussian').

#

'Poisson' is related to the maximum photon count in the detector. 1e5 is

a standard clinical nuber, reduce it for more noise

'Gaussian' is related to possible electronic noise in the detector. mean

of 0 and std of 10 is common in clinical scenario. Increase std for more

noise.

noise_projections = CTnoise.add(projections, Poisson=1e5, Gaussian=np.array([0, 10]))

In[101]:

%% Plot Projections

tigre.plotproj( projections, angles)

In[96]:

plot noise

tigre.plotproj(projections - noise_projections)

In[ ]:

In[ ]:

In[ ]:

!/usr/bin/env python

coding: utf-8

In[1]:

% Demo 5: How to use plotting functions

#

This demo will demostrate the options for plotting projection and images

on TIGRE. The functions have been in previous demos, but in here an

exaustive explanation and usage of them is given.

In[1]:

%%Initialize

get_ipython().run_line_magic('matplotlib', 'notebook') import matplotlib import tigre import numpy as np from tigre.utilities import sample_loader from tigre.utilities import CTnoise import tigre.algorithms as algs

In[2]:

%% Geometry

geo = tigre.geometry_default(high_resolution=False)

In[6]:

%% Load data and generate projections

define angles

angles = np.linspace(0, 2 * np.pi, 100)

Load thorax phatom data

head = sample_loader.load_head_phantom(geo.nVoxel) head

In[7]:

generate projections

projections = tigre.Ax(head, geo, angles)

add noise

noise_projections = CTnoise.add(projections, Poisson=1e5, Gaussian=np.array([0, 10]))

In[4]:

%% Reconstruct image using OS-SART and FDK

FDK

imgFDK = algs.fdk(noise_projections, geo, angles) niter = 50 imgOSSART = algs.ossart(noise_projections, geo, angles, 50)

In[5]:

%% Lets use PlotProj

#

plotProj plots the projection data measure on the detector on each angle.

#

exhaustive list of possible parameters:

'Step' : Defines the step size for skippin projections when plotting,

usefull when there are a big amount of projections. Default is 1

step = 2

In[8]:

'Colormap': Defines the colormap used to plot. Default is 'gray'.

colormap = "viridis" colormap = "plasma" colormap = "gray"

In[9]:

'Clims': Defines the data limits for the color, usefull when one wants to

see some specific range. The default uses the minimum and maximum of the

data.

clims = [0, 200]

In[10]:

'Savegif': allows to save the plotted figure as an animated gif,

specified by the given filename.

giffilename = "demo5projections.gif"

In[11]:

'Slice': allows to plot a single projection .Will overwrite the behaviour

of 'Step'

slice = 5

In[12]:

Lets try out.

tigre.plotproj( noise_projections, angles, step=step, colormap=colormap, clims=clims, savegif=giffilename ) # not using 'Step'

In[12]:

Remember you can also plot errors, for example the added noise by:

noise = np.abs(noise_projections - projections) # abs is what we are interested in plotting tigre.plotproj( noise, angles, clims=[0, 2] )

In[13]:

%% PlotImg

plotImg plots the image slice by slice.

#

List of optional parameters:

'Dim': specifies the dimension for plotting.

Dim can be 'X','Y','Z'

# dimension = "Z"

In[14]:

'Step': step size of the plotting. Useful when images are big or one just

wants an overview of the result

step = 2

In[15]:

'Colormap': Defines the colormap used to plot. Default is 'gray'.

colormap = "plasma" colormap = "magma" colormap = "gray" colormap = "viridis"

In[16]:

'Clims': Defines the data limits for the color, usefull when one wants to

see some specific range. The default computes the 5% and 95% percentiles

of the data and uses that as limit.

clims = [0, 1]

In[17]:

'Savegif': allows to save the plotted figure as an animated gif,

specified by the given filename.

giffilename = "demo5image.gif"

In[18]:

'Slice': allows to plot a single slice .Will overwrite the behaviour

of 'Step'

slice = 64

In[19]:

Lets go for it

tigre.plotimg(imgFDK, dim=dimension, step=step, clims=clims, colormap=colormap, savegif=giffilename)

In[20]:

Remember: You can always plot more than 1 image together!

tigre.plotimg(np.concatenate([head, imgFDK, imgOSSART], axis=1), dim="z")

Or even the errors!

tigre.plotImg(np.concatenate([np.abs(head - imgFDK), np.abs(head - imgOSSART)]), dim="z")

In[13]:

projections

In[ ]:

!/usr/bin/env python

coding: utf-8

In[2]:

%% Demo 4: Simple Image reconstruction

# #

This demo will show how a simple image reconstruction can be performed,

by using OS-SART and FDK

In[1]:

%%Initialize

get_ipython().run_line_magic('matplotlib', 'notebook') import matplotlib import tigre import numpy as np from tigre.utilities import sample_loader from tigre.utilities import CTnoise import tigre.algorithms as algs

In[9]:

%% Geometry

geo = tigre.geometry_default(high_resolution=False)

In[3]:

%% Load data and generate projections

define angles

angles = np.linspace(0, 2 * np.pi, 100)

In[10]:

head = sample_loader.load_head_phantom(geo.nVoxel) head

In[11]:

Load thorax phantom data

generate projections

projections = tigre.Ax(head, geo, angles)

add noise

noise_projections = CTnoise.add(projections, Poisson=1e5, Gaussian=np.array([0, 10]))

In[12]:

%% Reconstruct image using OS-SART and FDK

FDK

imgFDK = algs.fdk(noise_projections, geo, angles)

In[13]:

OS-SART

niter = 50 imgOSSART = algs.ossart(noise_projections, geo, angles, niter)

In[14]:

%% Show the results

tigre.plotimg( np.concatenate([imgFDK, imgOSSART], axis=1), dim="z" )

In[ ]:

In[ ]:

!/usr/bin/env python

coding: utf-8

In[2]:

This demo presents the Total variation algorithms in TIGRE. Total

variation algorithms try to minimize the variation (gradient) of the

image, assuming its piecewise smooth, as most things in nature are (i.e.

human body).

This set of algorithms is specially good performing when the noise is

very big or the number of projections is small, however, they require more

computational time and memory than the other algorithms to run.

In[3]:

- AwASD_POCS: Edge preserving ASD_POCS (Adaptative weigthed).

- OS_AwASD_POCS: OS-version of the previous algorithm

- PCSD: A version of ASD_POCS that heuristically select some of the

parameters, particularly epsilon (maxL2norm)

- AwPCSD: Edge preserving version of the previous algorithm

- OS_AwPCSD: block-wise version of the previous

In[4]:

%%Initialize

import tigre import numpy as np from tigre.utilities import sample_loader from tigre.utilities import CTnoise import tigre.algorithms as algs from matplotlib import pyplot as plt from tigre.utilities.im3Dnorm import im3DNORM

In[5]:

%% Geometry

geo = tigre.geometry_default(high_resolution=False)

In[6]:

%% Load data and generate projections

define angles

angles = np.linspace(0, 2 * np.pi, 100)

Load thorax phatom data

head = sample_loader.load_head_phantom(geo.nVoxel)

generate projections

projections = tigre.Ax(head, geo, angles)

add noise

noise_projections = CTnoise.add(projections, Poisson=1e5, Gaussian=np.array([0, 10]))

In[7]:

%% Lets create a OS-SART test for comparison

imgOSSART = algs.ossart(noise_projections, geo, angles, 10)

In[8]:

%% Total Variation algorithms

#

ASD-POCS: Adaptative Steeppest Descent-Projection On Convex Subsets

Often called POCS

==========================================================================

==========================================================================

ASD-POCS minimizes At-B and the TV norm separately in each iteration,

i.e. reconstructs the image first and then reduces the TV norm, every

iteration. As the other algorithms the mandatory inputs are projections,

geometry, angles and maximum iterations.

#

ASD-POCS has a veriety of optional arguments, and some of them are crucial

to determine the behaviour of the algorithm. The advantage of ASD-POCS is

the power to create good images from bad data, but it needs a lot of

tunning.

#

Optional parameters that are very relevant:

----------------------------------------------

'maxL2err' Maximum L2 error to accept an image as valid. This

parameter is crucial for the algorithm, determines at

what point an image should not be updated further.

Default is 20% of the FDK L2 norm.

its called epsilon in the paper

epsilon = ( im3DNORM(tigre.Ax(algs.fdk(noise_projections, geo, angles), geo, angles) - noise_projections, 2)

In[9]:

'alpha': Defines the TV hyperparameter. default is 0.002.

However the paper mentions 0.2 as good choice

alpha = 0.002

In[10]:

'tviter': Defines the amount of TV iterations performed per SART

iteration. Default is 20

ng = 25

In[11]:

Other optional parameters

----------------------------------------------

'lambda': Sets the value of the hyperparameter for the SART iterations.

Default is 1

#

'lambdared': Reduction of lambda Every iteration

lambda=lambdared*lambda. Default is 0.99

# lmbda = 1 lambdared = 0.9999 # you generally want 1

In[12]:

'alpha_red': Defines the reduction rate of the TV hyperparameter

alpha_red = 0.95

In[13]:

'Ratio': The maximum allowed image/TV update ration. If the TV

update changes the image more than this, the parameter

will be reduced.default is 0.95

ratio = 0.94

In[14]:

'Verbose' 1 or 0. Default is 1. Gives information about the

progress of the algorithm.

verb = True

In[15]:

imgASDPOCS = algs.asd_pocs( noise_projections, geo, angles, 10, # these are very important tviter=ng, maxl2err=epsilon, alpha=alpha, # less important. lmbda=lmbda, lmbda_red=lambdared, rmax=ratio, verbose=verb, )

In[16]:

OS_ASD_POCS: Odered Subset-TV algorithm

==========================================================================

==========================================================================

#

The logical next step to imporce ASD-POCS is substituting SART with a

faster algorithm, such as OS-SART

#

The parameters are the same as in ASD-POCS, but also have 'BlockSize'

In[17]:

imgOSASDPOCS = algs.os_asd_pocs( noise_projections, geo, angles, 10, # these are very important tviter=ng, maxl2err=epsilon, alpha=alpha, # less important. lmbda=lmbda, lmbda_red=lambdared, rmax=ratio, verbose=verb,

OSC params

blocksize=10,

)

In[18]:

AwASD_POCS: adaptative weighted ASD_POCS

==========================================================================

==========================================================================

#

This is a more edge preserving algorithms than ASD_POCS, in theory.

delta is the cuttof vlaue of anromalized edge exponential weight....

not super clear, but it cotnrols at which point you accept something as real vs noise edge.

In[19]:

imgAWASDPOCS = algs.awasd_pocs( noise_projections, geo, angles, 10, # these are very important tviter=ng, maxl2err=epsilon, alpha=alpha, # less important. lmbda=lmbda, lmbda_red=lambdared, rmax=ratio, verbose=verb, # AwASD_POCS params delta=np.array([-0.005]), )

In[20]:

%% plot results

plot images

tigre.plotimg( np.concatenate([imgAWASDPOCS, imgOSASDPOCS, imgASDPOCS, imgOSSART], axis=1), dim="z", step=2 )

In[ ]:

AnderBiguri commented 2 years ago

@shaghayegh1376 please can you shorten this to the minimal example that reproduces the case? Reduce the code as much as possible

shaghayegh1376 commented 2 years ago

yes its the simplest example :

On Tue, Aug 16, 2022 at 5:19 PM Biguri @.***> wrote:

@shaghayegh1376 https://github.com/shaghayegh1376 please can you shorten this to the minimal example that reproduces the case? Reduce the code as much as possible

— Reply to this email directly, view it on GitHub https://github.com/CERN/TIGRE/issues/393#issuecomment-1216374136, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYD4MB5FYQXYMYL3BCUWGI3VZNMKDANCNFSM56U5VVDQ . You are receiving this because you were mentioned.Message ID: @.***>

!/usr/bin/env python

coding: utf-8

In[67]:

%% DEMO 03: Generate sample data and add realistic CT noise to it.

#

This demo will show how to generate sample data for image reconstruction

In[90]:

get_ipython().run_line_magic('matplotlib', 'notebook') import matplotlib.pyplot as pl import matplotlib import tigre import numpy as np from tigre.utilities import sample_loader from tigre.utilities import CTnoise import scipy import scipy.sparse.linalg from tigre.utilities.Ax import Ax from tigre.utilities import sample_loader from tigre.utilities import sl3d

In[91]:

geo = tigre.geometry_default(high_resolution=False)

In[92]:

%% Define angles of projection and load phantom image

define projection angles (in radians)

angles = np.linspace(0, 2 * np.pi, 50)

load phatnom image

from IPython.display import Image head = sample_loader.load_head_phantom(geo.nVoxel)

head = head = scipy.io.loadmat("D:/شقایق جدید 1401/پروژه/code/TIGRE-master/Python/tigre/data/head.mat" , geo.n_proj)

head

In[93]:

Simulate forward projection.

To match with mathematical notation, the projection operation is called Ax

projections = tigre.Ax(head, geo, angles)

In[94]:

Add realistic noise. Adds photon scattering noise ('Poisson') and

electronic noise of the detector ('Gaussian').

#

'Poisson' is related to the maximum photon count in the detector. 1e5 is

a standard clinical nuber, reduce it for more noise

'Gaussian' is related to possible electronic noise in the detector. mean

of 0 and std of 10 is common in clinical scenario. Increase std for more

noise.

noise_projections = CTnoise.add(projections, Poisson=1e5, Gaussian=np.array([0, 10]))

In[101]:

%% Plot Projections

tigre.plotproj( projections, angles)

In[96]:

plot noise

tigre.plotproj(projections - noise_projections)

In[ ]:

In[ ]:

In[ ]:

AnderBiguri commented 2 years ago

I will have a look, but meanwhile I suggest trying it in a normal python enviroment and not in jupyter if you want the plots.

I myself dont have it installed and its not officially supported, so I will try to test this but can't promise anything.

shaghayegh1376 commented 2 years ago

Thank you for your response And i will try it with normal python environment

On Tue, Aug 16, 2022 at 17:24 Biguri @.***> wrote:

I will have a look, but meanwhile I suggest trying it in a normal python enviroment and not in jupyter if you want the plots.

I myself dont have it installed and its not officially supported, so I will try to test this but can't promise anything.

— Reply to this email directly, view it on GitHub https://github.com/CERN/TIGRE/issues/393#issuecomment-1216385145, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYD4MB3GJDLBP4KWZ4NRT4LVZNM35ANCNFSM56U5VVDQ . You are receiving this because you were mentioned.Message ID: @.***>

shaghayegh1376 commented 1 year ago

Dear mr Biguri

I have problem with implementing of tigre toolbox in environment except jupyter notebook. How can i write code in other environment for example visual studio code

On Tue, Aug 16, 2022 at 17:29 Shaghayegh Afshari < @.***> wrote:

Thank you for your response And i will try it with normal python environment

On Tue, Aug 16, 2022 at 17:24 Biguri @.***> wrote:

I will have a look, but meanwhile I suggest trying it in a normal python enviroment and not in jupyter if you want the plots.

I myself dont have it installed and its not officially supported, so I will try to test this but can't promise anything.

— Reply to this email directly, view it on GitHub https://github.com/CERN/TIGRE/issues/393#issuecomment-1216385145, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYD4MB3GJDLBP4KWZ4NRT4LVZNM35ANCNFSM56U5VVDQ . You are receiving this because you were mentioned.Message ID: @.***>

AnderBiguri commented 1 year ago

@shaghayegh1376 you will need to be more specific. There are tutorials in the installation page for python envoroments, have you looked at that? what are the problems you are having?

You don't need to "write code" to make TIGRE work in VSC (note that VSC is not an "enviroment").

shaghayegh1376 commented 1 year ago

Dear Mr. Biguri as you said before to use originally python environment instead of anaconda ( jupyter notebook and spyder) I followed the step as it said in the tigre installment and ran steps in cmd and it installed successfully. but when i run demo 3 , it would be the result : [image: image.png]

On Mon, Aug 29, 2022 at 7:27 PM Biguri @.***> wrote:

@shaghayegh1376 https://github.com/shaghayegh1376 you will need to be more specific. There are tutorials in the installation page for python envoroments, have you looked at that? what are the problems you are having?

You don't need to "write code" to make TIGRE work in VSC (note that VSC is not an "enviroment").

— Reply to this email directly, view it on GitHub https://github.com/CERN/TIGRE/issues/393#issuecomment-1230157212, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYD4MB64CBCGPGQQPWDN77LV3SNCTANCNFSM56U5VVDQ . You are receiving this because you were mentioned.Message ID: @.***>

AnderBiguri commented 1 year ago

@shaghayegh1376 I can't see the image, please post it in the github issue.

shaghayegh1376 commented 1 year ago

unnamed

AnderBiguri commented 1 year ago

@shaghayegh1376 please next time share text as text, not as an image, it is quite unhelpful as an image!

I would suggest trying an older version of python, perhaps 3.7 or so. I had similar issues in the past with 3.9, but I thought we solved this (are you running a recent version of TIGRE??). If you try python 3.7 and it works, let me know.

shaghayegh1376 commented 1 year ago

it was with python 3.10 , let me check the 3.7 version

shaghayegh1376 commented 1 year ago

Traceback (most recent call last): File "C:/Users/shaghayegh/Desktop/test.py", line 1, in import tigre ModuleNotFoundError: No module named 'tigre'

this was the result with python 3.7

AnderBiguri commented 1 year ago

Thats just that you installed it wrong in python 3.7.

shaghayegh1376 commented 1 year ago

but i follow the steps like tutorial.

AnderBiguri commented 1 year ago

Sorry, you will need to be more specific. Unfortunately as it currently stands I have no information to help you, I only know it doesn't work for you.

On Thu, 1 Sept 2022, 07:13 shaghayegh1376, @.***> wrote:

but i follow the steps like tutorial.

— Reply to this email directly, view it on GitHub https://github.com/CERN/TIGRE/issues/393#issuecomment-1233791026, or unsubscribe https://github.com/notifications/unsubscribe-auth/AC2OENBG54SL6H6SAFHLNELV4BCRTANCNFSM56U5VVDQ . You are receiving this because you commented.Message ID: @.***>

shaghayegh1376 commented 1 year ago

ok, another question is that: can we replace this function: tigre.plotimg(np.concatenate([imgFDK, imgOSSART], axis=1), dim="z") with other library like plt.show() or .imshow() and how i mean , what alternative to tigre.plotting can i use to display the result.

AnderBiguri commented 1 year ago

Absolutely. As you can see, Tigre uses np.arrays to store the data. Therefore you can use any plotting technique to plot np.arrays. In fact that is what tigre.plotimg does, just uses plt.imshow in a nice way. You are more than welcome to use your own functions!

Ander

On Fri, 2 Sept 2022, 03:45 shaghayegh1376, @.***> wrote:

ok, another question is that: can we replace this function: tigre.plotimg(np.concatenate([imgFDK, imgOSSART], axis=1), dim="z") with other library like plt.show() or .imshow() and how i mean , what alternative to tigre.plotting can i use to display the result.

— Reply to this email directly, view it on GitHub https://github.com/CERN/TIGRE/issues/393#issuecomment-1235007399, or unsubscribe https://github.com/notifications/unsubscribe-auth/AC2OENENZNFTJOOIKWYYPMTV4FS4VANCNFSM56U5VVDQ . You are receiving this because you commented.Message ID: @.***>

pjueon commented 1 year ago

unnamed

@shaghayegh1376 please next time share text as text, not as an image, it is quite unhelpful as an image!

I would suggest trying an older version of python, perhaps 3.7 or so. I had similar issues in the past with 3.9, but I thought we solved this (are you running a recent version of TIGRE??). If you try python 3.7 and it works, let me know.

This importing error is already fixed by #387 Judging by the line number in the error message, this fix is not applied to the version you're using. Try with the latest version of TIGRE. It should work on python 3.10.