Mentions légales du service

Skip to content
Snippets Groups Projects
Commit 257cee40 authored by LEGRAND Jonathan's avatar LEGRAND Jonathan
Browse files

Upload notebooks & associated python scripts

parent d9d03ab4
Branches notebooks
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Applying a transformation matrix to an image
%% Cell type:code id: tags:
``` python
%matplotlib inline
from vt import create_trsf
from vt import apply_trsf
from vt import vtImage
```
%% Cell type:code id: tags:
``` python
from utils import save_url_temp_file
from visu import slice_show
```
%% Cell type:markdown id: tags:
Download some example files (grayscale & segmented images) from URL links:
%% Cell type:code id: tags:
``` python
url_grayscale = "https://zenodo.org/record/3737630/files/sphere_membrane_t0.inr.gz"
url_labelled = "https://zenodo.org/record/3737630/files/sphere_membrane_t0_seg.inr.gz"
# Save the files to temporary directory and get the files locations:
img_path = save_url_temp_file(url_grayscale)
seg_img_path = save_url_temp_file(url_labelled)
```
%% Output
File at URL has already been downloaded here: /tmp/sphere_membrane_t0.inr.gz
File at URL has already been downloaded here: /tmp/sphere_membrane_t0_seg.inr.gz
%% Cell type:markdown id: tags:
Load the files with `vtImage`:
%% Cell type:code id: tags:
``` python
img = vtImage(img_path)
seg_img = vtImage(seg_img_path)
```
%% Cell type:markdown id: tags:
Display the files with the `slice_show` method from `visu`:
%% Cell type:code id: tags:
``` python
fig = slice_show([img, seg_img], titles=["Intensity", "Labelled"], cmap=['gray', 'glasbey'])
fig.show()
```
%% Output
Done registering the 'glasbey' colormap to matplotlib.
/home/jonathan/miniconda3/envs/vt-python/lib/python3.7/site-packages/ipykernel_launcher.py:2: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
%% Cell type:markdown id: tags:
## Quick background
%% Cell type:markdown id: tags:
When transforming an image, an **interpolation method** is required to defines how to process the values on the discrete grid after transformation.
There are many interpolation methods, but `vt-python` implements the following four that apply to specific types of images:
- **linear**: apply to grayscale images;
- **cspline**: apply to grayscale images;
- **nearest**: apply to labelled & binary images;
- **cellbased**: apply to labelled images.
%% Cell type:markdown id: tags:
## Resampling
%% Cell type:markdown id: tags:
Resampling change the image geometry, its *shape* or *voxelsize*, while conserving its *physical extent*.
%% Cell type:markdown id: tags:
### Grayscale images
%% Cell type:code id: tags:
``` python
print(img.shape())
xs, ys, zs = [sh//2 for sh in img.shape()]
```
%% Output
[225, 225, 225]
%% Cell type:markdown id: tags:
Create required *identity transformation*:
%% Cell type:code id: tags:
``` python
id_trsf = create_trsf(params='-identity')
```
%% Cell type:markdown id: tags:
Apply *identity transformation* with `-resize` parameter to given dimensions `-dim` using *linear* and *cspline* interpolation methods:
%% Cell type:code id: tags:
``` python
# Linear interpolation:
lin_img = apply_trsf(img, id_trsf, params=f"-resize -dim {xs} {ys} {zs} -interpolation linear")
# Cubic-spline interpolation:
csp_img = apply_trsf(img, id_trsf, params=f"-resize -dim {xs} {ys} {zs} -interpolation cspline")
```
%% Cell type:code id: tags:
``` python
fig = slice_show([lin_img, csp_img], titles=['linear', 'cspline'], cmap='viridis')
fig.show()
```
%% Output
/home/jonathan/miniconda3/envs/vt-python/lib/python3.7/site-packages/ipykernel_launcher.py:2: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
%% Cell type:markdown id: tags:
### Labelled images
%% Cell type:code id: tags:
``` python
print(seg_img.shape())
xs, ys, zs = [sh//2 for sh in seg_img.shape()]
```
%% Output
[225, 225, 225]
%% Cell type:markdown id: tags:
Create required *identity transformation*:
%% Cell type:code id: tags:
``` python
id_trsf = create_trsf(params='-identity')
```
%% Cell type:markdown id: tags:
Apply *identity transformation* with `-resize` parameter to given dimensions `-dim` using *linear* and *cspline* interpolation methods:
%% Cell type:code id: tags:
``` python
# Nearest interpolation:
nea_seg_img = apply_trsf(seg_img, id_trsf, params=f"-resize -dim {xs} {ys} {zs} -interpolation nearest")
# Cell-based interpolation:
ceb_seg_img = apply_trsf(seg_img, id_trsf, params=f"-resize -dim {xs} {ys} {zs} -interpolation cellbased")
```
%% Cell type:code id: tags:
``` python
fig = slice_show([nea_seg_img, ceb_seg_img], titles=['nearest', 'cellbased'], cmap='glasbey')
fig.show()
```
%% Output
Done registering the 'glasbey' colormap to matplotlib.
/home/jonathan/miniconda3/envs/vt-python/lib/python3.7/site-packages/ipykernel_launcher.py:2: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
%% Cell type:markdown id: tags:
## Transforming
%% Cell type:markdown id: tags:
In the following example, the *shape* & *voxelsize* of the image remains unchanged, but the information it contains undergoes a **rigid transformation**, *i.e.* is *translated* & *rotated*.
%% Cell type:code id: tags:
``` python
rig_params = " -trsf-type rigid -transformation-value random -srandom 2"
rig_trsf = create_trsf(params=rig_params)
print(rig_trsf.copy_to_array())
```
%% Output
[[ 0.98425008 0.14482898 0.1013723 -3.0338649 ]
[-0.13743065 0.98754926 -0.07654587 -1.56075997]
[-0.1111962 0.06140862 0.99189938 3.99610997]
[ 0. 0. 0. 1. ]]
%% Cell type:code id: tags:
``` python
csp_img = apply_trsf(img, rig_trsf, params=f"-interpolation cspline")
ceb_seg_img = apply_trsf(seg_img, rig_trsf, params=f"-interpolation cellbased")
```
%% Cell type:code id: tags:
``` python
fig = slice_show([csp_img, ceb_seg_img], titles=["Intensity", "Labelled"], cmap=['gray', 'glasbey'])
fig.show()
```
%% Output
Done registering the 'glasbey' colormap to matplotlib.
/home/jonathan/miniconda3/envs/vt-python/lib/python3.7/site-packages/ipykernel_launcher.py:2: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
%% Cell type:markdown id: tags:
Note that the *white area* for the labelled image is indicating a value of `0` that is distinct from the backgroung that is set to `1`. This is not seen (or less obvious) in the intesity image because `0` indicate *no signal* and is already present in this region of the image.
%% Cell type:code id: tags:
``` python
from vt import vtImage
from vt import vtTransformation
from vt import blockmatching
from vt.tools import shared_data
```
%% Cell type:markdown id: tags:
## Load two image for registration
%% Cell type:code id: tags:
``` python
from vt.tools import shared_data
from vt import blockmatching as vt_blockmatching
flo_path = shared_data('p58-t0_INT_down_interp_2x.inr')
ref_path = shared_data('p58-t1_INT_down_interp_2x.inr')
```
%% Cell type:code id: tags:
``` python
trsf_path = shared_data('p58-t0_on_t1.trsf')
cmd = vt_blockmatching(flo_path, ref_path, params="-trsf-type rigid -py-ll 2", out_file_path=trsf_path)
```
%% Cell type:code id: tags:
``` python
from vt import vtTransformation as Trsf
rig_trsf = Trsf(trsf_path)
```
%% Cell type:code id: tags:
``` python
```
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
%% Cell type:markdown id: tags:
# Transformation averaging
%% Cell type:code id: tags:
``` python
from vt import mean_trsfs
from vt import create_trsf
from vt import vtTransformation
```
%% Cell type:markdown id: tags:
## Mean rigid transformation
%% Cell type:markdown id: tags:
In this exemple, we create a list of *rigid* `vtTransformation` objects and we compute their mean average:
%% Cell type:code id: tags:
``` python
trsfs = [create_trsf(params='-trsf-type rigid -random') for i in range(3)]
```
%% Cell type:code id: tags:
``` python
av_trsf = mean_trsfs(trsfs, params='-mean -trsf-type rigid')
```
%% Cell type:code id: tags:
``` python
print(av_trsf)
```
%% Output
None
%% Cell type:markdown id: tags:
The average transformation seems empty and a look at the terminal running the notebook shows:
%% Cell type:raw id: tags:
LS_Rigid_3D_Average: not implemented yet
BAL_ComputeAverageTransformation: average linear transformation computation failed
API_meanTrsfs: unable to compute average transformation
API_meanTrsfs: unable to allocate output image
%% Cell type:markdown id: tags:
It is not possible to compute average transformation with `-trsf-type` set to *rigid*, use *affine* instead.
%% Cell type:code id: tags:
``` python
av_trsf = mean_trsfs(trsfs, params='-mean -trsf-type affine')
```
%% Cell type:code id: tags:
``` python
print(av_trsf)
```
%% Output
vtTransformation : {
type : AFFINE_3D,
unit : real,
}
%% Cell type:markdown id: tags:
## Mean affine transformation
%% Cell type:markdown id: tags:
In this exemple, we create a list of *affine* `vtTransformation` objects and we compute their mean average:
%% Cell type:code id: tags:
``` python
trsfs = [create_trsf(params='-trsf-type affine -random') for i in range(3)]
```
%% Cell type:code id: tags:
``` python
av_trsf = mean_trsfs(trsfs, params='-mean -trsf-type affine')
```
%% Cell type:code id: tags:
``` python
print(av_trsf)
```
%% Output
vtTransformation : {
type : AFFINE_3D,
unit : real,
}
%% Cell type:markdown id: tags:
## Mean vectorfield transformation
%% Cell type:markdown id: tags:
In this exemple, we create a list of *vectorfield* `vtTransformation` objects and we compute their mean average:
%% Cell type:code id: tags:
``` python
trsfs = [create_trsf(params='-trsf-type vectorfield -value sinus3D -template-dim 30 30 10 -voxel-size 0.2 0.2 0.5') for i in range(3)]
```
%% Cell type:code id: tags:
``` python
av_trsf = mean_trsfs(trsfs, params='-mean -trsf-type vectorfield')
```
%% Cell type:code id: tags:
``` python
print(av_trsf)
```
%% Output
None
%% Cell type:markdown id: tags:
The average transformation seems empty and a look at the terminal running the notebook shows:
%% Cell type:raw id: tags:
API_meanTrsfs_initTransformation: such transformation type (vector field) not handled yet
API_meanTrsfs: unable to allocate output transformation
%% Cell type:markdown id: tags:
## Mean vectorfield transformation with files
%% Cell type:markdown id: tags:
It is possible to compute a transformation average using files instead of a list of `vtTransformation` object loaded in python memory. This can be particulary useful for averaging large vectofields.
%% Cell type:code id: tags:
``` python
from tempfile import NamedTemporaryFile as Tmp
from tempfile import gettempdir
from os.path import join
```
%% Cell type:markdown id: tags:
We create *vectorfield transformations* with `sinus3D` method:
%% Cell type:code id: tags:
``` python
trsfs = [create_trsf(params='-trsf-type vectorfield -value sinus3D -template-dim 30 30 10 -voxel-size 0.2 0.2 0.5') for i in range(3)]
```
%% Cell type:markdown id: tags:
Now we save them in the **temporary directory** as \*.trsf files:
%% Cell type:code id: tags:
``` python
trsf_fnames = []
for trsf in trsfs:
trsf_fname = Tmp().name + '.trsf'
trsf_fnames.append(trsf_fname)
trsf.write(trsf_fname)
```
%% Cell type:markdown id: tags:
We defines the name of the output transformation file as `mean.trsf`, also in the temporary directory:
%% Cell type:code id: tags:
``` python
mean_fname = join(gettempdir(), 'mean.trsf')
```
%% Cell type:markdown id: tags:
We finally compute the mean *vectorfield transformation* for those files using the `out_file_path` keyword argument:
%% Cell type:code id: tags:
``` python
mean_trsfs(trsf_fnames, out_file_path=mean_fname, params='-mean -trsf-type vectorfield')
```
%% Output
1
%% Cell type:markdown id: tags:
The terminal running the notebook shows an error message:
%% Cell type:raw id: tags:
Error: error when allocating result transformation...
%% Cell type:code id: tags:
``` python
av_trsf = vtTransformation(mean_fname)
print(av_trsf)
```
%% Output
vtTransformation : {
type : UNDEF_TRANSFORMATION,
unit : real,
}
%% Cell type:markdown id: tags:
The terminal running the notebook shows an error message:
%% Cell type:raw id: tags:
BAL_ReadTransformation: an error occurs when accessing to '/tmp/mean.trsf'
vtTransformationBridge::vtTransformationBridge: cannot read file '/tmp/mean.trsf'
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import exists
from os.path import join
from os.path import split
from os.path import splitext
def get_pne(location):
"""Get the path, name and extension of an image file based on its location.
Parameters
----------
location : str
location of the image file
Returns
-------
str
the path to the file
str
the name of the file
str
the extension of the file
"""
(filepath, filename) = split(location)
(shortname, ext) = splitext(filename)
# Check for possible compression of the file:
if (ext == '.gz') or (ext == '.zip'):
compress_ext = ext
(shortname, format_ext) = splitext(shortname)
ext = format_ext + compress_ext
return filepath, shortname, ext
def save_url_temp_file(url, tmp_fname=None):
"""Save URL to a temporary file.
Parameters
----------
url : str
A valid URL pointing toward a file.
tmp_fname : str, optional
Path to the temporary file, else created.
Returns
-------
str
Path to the temporary file containing the retrieved image.
"""
import urllib3
from tempfile import gettempdir
if tmp_fname is None:
url_root, filename, ext = get_pne(url)
tmp_fname = join(gettempdir(), filename + ext)
# Check file has not been already downloaded:
if exists(tmp_fname):
print(f"File at URL has already been downloaded here: {tmp_fname}")
return tmp_fname
# Initialize an http request, but do not preload the file
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)
# Load the remote file to a local temporary file:
with open(tmp_fname, 'wb') as out:
while True:
data = r.read()
if not data:
break
out.write(data)
# Close HTTP(S) connection:
r.release_conn()
return tmp_fname
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment