Components module

SpatialImage class

digraph inheritancec878e632d9 { rankdir=LR; size="8.0, 12.0"; "components.spatial_image.SpatialImage" [URL="#components.spatial_image.SpatialImage",fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",target="_top",tooltip="Management of 2D and 3D images."]; "numpy.ndarray" -> "components.spatial_image.SpatialImage" [arrowsize=0.5,style="setlinewidth(0.5)"]; "numpy.ndarray" [fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",tooltip="ndarray(shape, dtype=float, buffer=None, offset=0,"]; }
class components.spatial_image.SpatialImage[source]

Management of 2D and 3D images.

A SpatialImage gathers a numpy array and some metadata (such as voxelsize, physical extent, origin, type, etc.).

Through a numpy.ndarray inheritance, all usual operations on numpy.ndarray objects (sum, product, transposition, etc.) are available.

All image processing operations are performed on this data structure, that is also used to solve inputs (read) and outputs (write).

We subclass ndarray using view casting in the ‘__new__’ section. View casting is the standard ndarray mechanism by which you take an ndarray of any subclass, and return a view of the array as another (specified) subclass, here a SpatialImage.

With an numpy array as input_array:
  • specify origin & voxelsize, else use DEFAULT_ORIG_2D & DEFAULT_VXS_2D or DEFAULT_ORIG_3D & DEFAULT_VXS_3D according to dimensionality;
With a SpatialImage instance or any other which inherit it:
  • its attributes ‘origin’, ‘voxelsize’ & ‘metadata’ are used whatever the values given as arguments when calling contructor;
In any case:
  • specifying dtype will change the array dtype to the given one;
  • attributes ‘shape’ and ‘ndim’ are taken from the array;
  • specifying ‘filename’ & ‘filepath’ in the metadata will allow to define them as attributes;
  • Images tags (IMAGE_MD_TAGS + ‘extent’) are set or updated if a metadata dictionary is given.

TODO: defines a ‘personal_metadata’ attribute to store other metadata ?

Modifying ‘ndim’ property is not possible, be serious now. Modifying ‘dtype’ property directly is not possible, use the astype method.

Modifying ‘origin’ property is not possible, do it at object instantiation. FIXME: This is not what its doing… yet! Modifying ‘voxelsize’ property will change the image ‘shape’ and preserve ‘extent’. FIXME: This is not what its doing… yet! Modifying ‘shape’ property will change the image ‘voxelsize’ and preserve ‘extent’. FIXME: This is not what its doing… yet! Modifying ‘extent’ property should resample the image. FIXME: This is not what its doing… yet!

metadata_image

A self generated list of attribute, contains basic image information such as: ‘shape’, ‘ndim’, ‘dtype’, ‘origin’, ‘voxelsize’ & ‘extent’. See ImageMetadata class docstring in timagetk.components.metadata.

Type:ImageMetadata
metadata_acquisition

Acquisition metadata is a list of attributes related to the measurement settings, the machine setup, or even used equipments and parameters. Use the ‘scan_info’ key in metadata dict to pass them to constructor.

Type:Metadata
metadata_processing

A self generated hierarchical dictionary of the algorithms applied to the image. It contains process names, the parameters use as well as their values and, if any, the sub-process called with the same degree of info.

Type:ProcessMetadata
__array_finalize__(obj)[source]

This is the mechanism that numpy provides to allow subclasses to handle the various ways that new instances get created.

Parameters:obj – the object returned by the __new__ method.

Examples

>>> from timagetk.test import make_random_spatial_image
>>> # Initialize a random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image()
>>> type(img)
timagetk.components.spatial_image.SpatialImage
>>> # Taking the first z-slice automatically return a SpatialImage instance:
>>> img2d = img[:, :, 0]
>>> type(img2d)
timagetk.components.spatial_image.SpatialImage
static __new__(cls, input_array, origin=None, voxelsize=None, dtype=None, metadata=None, **kwargs)[source]

Image object constructor (2D and 3D images)

Notes

To use ‘input_array’ dtype (from numpy), leave ‘dtype’ to None, else it will modify the dtype to the given values. Any key in kwargs matching a keyword argument (ie. ‘origin’, ‘dtype’ or ‘voxelsize’) will be ignored!

Parameters:
  • input_array (numpy.ndarray) – 2D or 3D array defining an image, eg. intensity or labelled image
  • origin (list, optional) – coordinates of the origin in the image, default: [0, 0] or [0, 0, 0]
  • voxelsize (list, optional.) – image voxelsize, default: [1.0, 1.0] or [1.0, 1.0, 1.0]
  • dtype (str, optional) – if given, should be in AVAIL_TYPES, and will modify the input_array type
  • metadata (dict, optional) – dictionary of image metadata, default is an empty dict
Returns:

image with metadata

Return type:

SpatialImage

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.random.random_sample((15, 15, 5)).astype(np.float16)
>>> img = SpatialImage(test_array, voxelsize=[0.5, 0.5, 1.])
>>> isinstance(img, SpatialImage)
True
>>> isinstance(img, np.ndarray)
True
>>> print(img.voxelsize)
[0.5, 0.5]
__str__()[source]

Method called when printing the object.

apply_trsf(trsf, trsf_unit='REAL', trsf_type='AFFINE_3D', interpolation='linear', **kwargs)[source]

Apply a known transformation trsf to the image.

Parameters:
  • trsf (np.array, BalTrsf) – transformation to apply to the image
  • trsf_unit (str, optional) – unit of the transformation, ‘real’ or ‘voxel’
Returns:

transformed SpatialImage

Return type:

SpatialImage

astype(dtype, **kwargs)[source]

Copy of the SpatialImage with updated data type.

Notes

kwargs are passed to numpy ‘astype’ method.

Parameters:dtype (str) – new type of data to apply
Returns:image with the new data type
Return type:SpatialImage

Examples

>>> import numpy as np
>>> from timagetk.test import make_random_spatial_image
>>> # Initialize a random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image()
>>> # Check the type:
>>> img.dtype
dtype('uint8')
>>> # Convert it to 16bits unsigned integers:
>>> img16 = img.astype(np.uint16)
>>> # Check the type:
>>> img16.dtype
dtype('uint16')
equal(sp_img, error=1e-09, method='max_error')[source]

Equality test between two SpatialImage

Uses array equality and metadata matching.

Parameters:
  • sp_img (SpatialImage) – another SpatialImage instance to test for array equality
  • error (float, optional) – maximum difference accepted between the two arrays (default=EPS)
  • method (str, optional) –
    type of “error measurement”, choose among (default=’max_error’):
    • max_error: max difference accepted for a given pixel
    • cum_error: max cumulative (sum) difference for the whole array
Returns:

True/False if (array and metadata) are equal/or not

Return type:

bool

Notes

Metadata equality test compare defined self.metadata keys to their counterpart in ‘sp_img’. Hence, a missing key in ‘sp_im’ or a different value will return False.

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image_1 = SpatialImage(test_array)
>>> image_1.equal(image_1)
True
>>> image_2 = SpatialImage(test_array, voxelsize=[0.5,0.5])
>>> image_1.equal(image_2)
SpatialImages metadata are different.
False
>>> image_2[1, 1] = 2
>>> image_1.equal(image_2)
Max difference between arrays is greater than '1e-09'.
SpatialImages metadata are different.
False
equal_array(sp_img, error=1e-09, method='max_error')[source]

Test array equality between two SpatialImage.

Parameters:
  • sp_img (SpatialImage) – another SpatialImage instance to test for array equality
  • error (float, optional) – maximum difference accepted between the two arrays, should be strictly inferior to this value to return True, default: EPS
  • method (str, optional) –
    type of “error measurement”, choose among:
    • max_error: max difference accepted for a given pixel
    • cum_error: max cumulative (sum) difference for the whole array
Returns:

True/False if arrays are equal/or not

Return type:

bool

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image_1 = SpatialImage(test_array)
>>> image_1.equal_array(image_1)
True
>>> # - Changing voxelsize does not affect array equality test:
>>> image_2 = SpatialImage(test_array, voxelsize=[0.5,0.5])
>>> image_1.equal_array(image_2)
True
>>> # - Changing array value does affect array equality test:
>>> image_2[0, 0] = 0
>>> image_1.equal_array(image_2)
False
>>> # - Changing accepted max difference affect array equality test:
>>> image_1.equal_array(image_2, error=2)
True
extent

Get SpatialImage physical extent.

It is related to the array shape and image voxelsize.

Returns:SpatialImage physical extent
Return type:list

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> print(image.extent)
[5.0, 5.0]
get_array(dtype=None)[source]

Get a numpy.ndarray from a SpatialImage

Returns:SpatialImage array
Return type:numpy.ndarray

Example

>>> from timagetk.test import make_random_spatial_image
>>> # Initialize a random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image()
>>> array = img.get_array()
>>> isinstance(array, SpatialImage)
False
>>> isinstance(array, np.ndarray)
True
get_available_types()[source]

Print the available bits type dictionary.

get_dim()[source]

Get SpatialImage number of dimensions (2D or 3D image)

Returns:SpatialImage dimensionality
Return type:int

Example

>>> from timagetk.test import make_random_spatial_image
>>> # Initialize a random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image()
>>> img.get_dim()
3
get_max()[source]

Get SpatialImage max value

Returns:SpatialImage max
Return type:*val*

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> image_max = image.get_max()
>>> print(image_max)
1
get_mean()[source]

Get SpatialImage mean

Returns:SpatialImage mean
Return type:*val*

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> image_mean = image.get_mean()
>>> print(image_mean)
1
get_min()[source]

Get SpatialImage min value

Returns:SpatialImage min
Return type:*val*

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> image_min = image.get_min()
>>> print(image_min)
1
get_pixel(indices)[source]

Get SpatialImage pixel value

Parameters:indices (list) – indices as list of integers
Returns:pixel value
Return type:*self.dtype*

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> indices = [1,1]
>>> pixel_value = image.get_pixel(indices)
>>> print(pixel_value)
1
get_region(indices)[source]

Extract a region using list of start & stop ‘indices’.

There should be two values per image dimension in ‘indices’. If the image is 3D and in one dimension, the start and stop are differ by one (on layer of voxels), the image is transformed to 2D!

Parameters:indices (list) – indices as list of integers
Returns:output SpatialImage
Return type:SpatialImage

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> indices = [1,3,1,3]
>>> out_sp_img = image.get_region(indices)
>>> isinstance(out_sp_img, SpatialImage)
True
get_z_slice(z_slice)[source]

Returns a SpatialImage with only one slice.

Parameters:z_slice (int) – z-slice to return
Returns:2D SpatialImage with only the required slice
Return type:SpatialImage
Raises:ValueError – if image is not 3D. if z-slice does not exists.

Examples

>>> from timagetk.test import make_random_spatial_image
>>> # Initialize a random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image()
>>> # Taking an existing z-slice from a 3D image works fine:
>>> img_z5 = img.get_z_slice(5)
>>> # Taking an NON existing z-slice from a 3D image raises an error:
>>> img_z50 = img.get_z_slice(50)
ValueError: Required z-slice (50) does not exists (max: 10)
>>> # Taking a z-slice from a 2D image raises an error:
>>> img_z5.get_z_slice(5)
ValueError: Can only extract z-slice from 3D images!
is2D()[source]

Returns True if the SpatialImage is 2D, else False.

Examples

>>> from timagetk.test import make_random_spatial_image
>>> # Initialize a random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image()
>>> img.is2D()
False
>>> # Take the first z-slice:
>>> img2d = img[:, :, 0]
>>> img2d.is2D()
True
is3D()[source]

Returns True if the SpatialImage is 3D, else False.

Examples

>>> from timagetk.test import make_random_spatial_image
>>> # Initialize a random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image()
>>> img.is3D()
True
is_available_types(dtype)[source]

Test if the given type is available.

Parameters:dtype (str) – name of the type to find in DICT_TYPES
is_isometric()[source]

Test image isometry.

Tests if the voxelsize values are the same for every axis or not.

Returns:is_iso – True if the image is isometric, else False.
Return type:bool

Examples

>>> from timagetk.test import make_random_spatial_image
>>> # Initialize anisotropic random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image(voxelsize=[0.5, 0.5, 1.])
>>> img.is_isometric()
False
>>> # Trasnform to isotropic 3D SpatialImage:
>>> img_iso = img.isometric_resampling()
>>> img_iso.is_isometric()
True
isometric_resampling(method='min', option='gray')[source]

Isometric resampling of the image.

Use either the min, the max or a a given voxelsize value.

Parameters:
  • method (str or float, optional) – change voxelsize to ‘min’ (default) or ‘max’ value of original voxelsize or to a given value.
  • option (str, optional) – option can be either ‘gray’ or ‘label’

Examples

>>> from timagetk.test import make_random_spatial_image
>>> # Initialize a random (uint8) 3D SpatialImage:
>>> img = make_random_spatial_image(voxelsize=[0.5, 0.5, 1.])
>>> # Test image isometry:
>>> img_iso.is_isometric()
False
>>> # Resample to isometric image:
>>> img_iso = img.isometric_resampling()
>>> # Test image isometry:
>>> img_iso.is_isometric()
True
mean_squared_difference(sp_img)[source]

Compute the mean squared difference between this image and another.

Parameters:sp_img (SpatialImage) – image to be compared to self
Returns:mse – the mean squared error
Return type:float
metadata

Get SpatialImage metadata dictionary.

Returns:metadata dictionary
Return type:dict
normalized_root_mean_squared_difference(sp_img, norm_type='Euclidean')[source]

Compute the mean squared difference between this image and another.

Parameters:
  • sp_img (SpatialImage) – image to be compared to self
  • norm_type ({'Euclidean', 'min-max', 'mean'}) – Controls the normalization method to use in the denominator of the NRMSE.

Notes

There is no standard method of normalization across the literature [3].

The methods available here are as follows:

  • Euclidean: normalize by the averaged Euclidean norm of im_true
  • min-max: normalize by the intensity range of im_true.
  • mean: normalize by the mean of im_true.

The averaged Euclidean norm is NRMSE = RMSE * sqrt(N) / ||im_true||, where || . || denotes the Frobenius norm and N = im_true.size.

This result is equivalent to: NRMSE = ||im_true - im_test|| / ||im_true||.

Returns:nrmse – The NRMSE metric.
Return type:float
origin

Get SpatialImage origin.

Returns:SpatialImage origin coordinates
Return type:list

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> print(image.origin)
[0, 0]
peak_signal_to_noise_ratio(sp_img)[source]

Compute the peak signal to noise ratio (PSNR) for an image.

Parameters:sp_img (SpatialImage) – image to be compared to self
Returns:psnr – The PSNR metric.
Return type:float
plot_cumulative_distribution(nbins=256)[source]

Plot cumulative distribution function of image.

Parameters:nbins (int) – number of bins

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.random.randint(0, 255, (5, 5)).astype(np.uint8)
>>> image = SpatialImage(test_array, voxelsize=[0.5, 0.5, 0.5])
>>> image.plot_cumulative_distribution()
plot_histogram(nbins=256)[source]

Plot histogram pixel intensity of image.

Parameters:nbins (int) – number of bins

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.random.randint(0, 255, (5, 5)).astype(np.uint8)
>>> image = SpatialImage(test_array, voxelsize=[0.5, 0.5, 0.5])
>>> image.plot_histogram()
plot_max_intensity_projection(threshold)[source]

Plot Maximum Intensity Projection.

Parameters:threshold (int) – intensity threshold to filter voxels during projection

Examples

>>> from timagetk.io import imread
>>> from timagetk.util import data_path
>>> im = imread(data_path('p58-t0-a0.lsm'))
>>> im.plot_max_intensity_projection(45)
resample(factor=None, voxelsize=None)[source]

Resample image, modify shape and voxelsize and preserve extent.

Choose only one parameter! Factor should be > 1 or < -1 !

Notes

Increasing the voxelsize, or using a negative factor, will reduce the shape of the array and result in a lower resolution image and loss of information. Decreasing the voxelsize, or using a positive factor, will in turn increase the shape of the array, and result in an image of higher resolution but with no gain of information since it will come from interpolation.

Parameters:
  • factor (int) – increase or decrease the voxelsize by given factor if positive, resp. negative
  • voxelsize (list) – list of float to which the image should be resampled to
Returns:

resampled image

Return type:

SpatialImage

Examples

>>> from timagetk.test import make_random_spatial_image
>>> img = make_random_spatial_image()
>>> print(img.metadata)
>>> # Resample changing voxelsize:
>>> res_img = img.resample(voxelsize=[0.5, 0.5, 0.5])
>>> print(res_img.metadata)
>>> # Resample by a given factor:
>>> res_img = img.resample(factor=2)
>>> print(res_img.metadata)
resolution

Ensure backward compatibility with older openalea.image package.

revert_axis(axis)[source]

Revert given axis.

Notes

x, y, or z axis if the object is in 3D, limited to x and y in 2D.

Parameters:axis (str) – can be either ‘x’, ‘y’ or ‘z’ (if 3D)
Returns:reverted array for selected axis
Return type:SpatialImage

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.random.randint(0, 255, (5, 5)).astype(np.uint8)
>>> image = SpatialImage(test_array, voxelsize=[0.5, 0.5, 0.5])
>>> print(image.get_array())
>>> image.revert_axis(axis='y')
set_pixel(indices, value)[source]

Set SpatialImage pixel value at given array coordinates.

Parameters:
  • indices (list) – indices as list of integers
  • value (array.dtype) – new value for the selected pixel, type of SpatialImage array

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> image.set_pixel([1,1], 2)
>>> image.get_array()
array([[1, 1, 1, 1, 1],
       [1, 2, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1]], dtype=uint8)
set_region(indices, val)[source]

Replace a region

Parameters:
  • indices (list) – indices as list of integers
  • val (array.dtype or numpy.array) – new value for the selected pixels, type of SpatialImage array
Returns:

SpatialImage instance

Return type:

SpatialImage

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> indices = [1,3,1,3]
>>> out_sp_img = image.set_region(indices, 3)
shannon_entropy(base=2)[source]

Calculate the Shannon entropy of an image [4].

The Shannon entropy is defined as S = -sum(pk * log(pk)), where pk are frequency/probability of pixels of value k.

Parameters:base (float, optional) – The logarithmic base to use.
Returns:entropy
Return type:float

Notes

The returned value is measured in bits or shannon (Sh) for base=2, natural unit (nat) for base=np.e and hartley (Hart) for base=10.

structural_similarity_index(sp_img, full_ssim=False)[source]

Compute the mean structural similarity index between this image and another.

When comparing images, the mean squared error (MSE)–while simple to implement–is not highly indicative of perceived similarity. Structural similarity aims to address this shortcoming by taking texture into account [1], [2].

Parameters:
  • sp_img (SpatialImage) – image to be compared to self
  • full_ssim (bool, optional) – if True, return the full structural similarity image instead of the mean value.
Returns:

  • mssim (float) – the mean structural similarity, ranging between O (low similarity) to 1 (high similarity)
  • ss_img (SpatialImage) – the full SSIM image

References

[1]
  1. Wang, A.C. Bovik, Mean squared error: Love it or leave it? A new look at Signal Fidelity Measures, Signal Processing Magazine, IEEE, vol. 26, no. 1, pp. 98-117, Jan. 2009.
[2]
  1. Wang, A. C. Bovik, H. R. Sheikh & E. P. Simoncelli, Image quality assessment: From error visibility to structural similarity, IEEE Transactions on Image Processing, vol. 13, no. 4, pp. 600-612, Apr. 2004.
to_2D()[source]

Convert a 3D SpatialImage to a 2D SpatialImage.

Conversion is possible only if there is a “flat” axis (ie. with only one slice in this axis).

Returns:the 2D SpatialImage
Return type:SpatialImage
to_3D()[source]

Convert a 2D SpatialImage to a 3D SpatialImage.

Obtained 3D SpatialImage has a “flat” z-axis (ie. with only one slice in this axis).

Returns:the 3D SpatialImage
Return type:SpatialImage
transpose(*axes)[source]
Parameters:axes
voxelsize

Get SpatialImage voxelsize.

Returns:SpatialImage voxelsize
Return type:list

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> test_array = np.ones((5,5), dtype=np.uint8)
>>> image = SpatialImage(test_array)
>>> print(image.voxelsize)
[1.0, 1.0]

LabelledImage class

digraph inheritance96d1d4c769 { rankdir=LR; size="8.0, 12.0"; "components.labelled_image.LabelledImage" [URL="#components.labelled_image.LabelledImage",fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",target="_top",tooltip="Class to manipulate labelled SpatialImage, eg. a segmented image."]; "timagetk.components.spatial_image.SpatialImage" -> "components.labelled_image.LabelledImage" [arrowsize=0.5,style="setlinewidth(0.5)"]; "numpy.ndarray" [fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",tooltip="ndarray(shape, dtype=float, buffer=None, offset=0,"]; "timagetk.components.spatial_image.SpatialImage" [fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",tooltip="Management of 2D and 3D images."]; "numpy.ndarray" -> "timagetk.components.spatial_image.SpatialImage" [arrowsize=0.5,style="setlinewidth(0.5)"]; }

This module implement the LabelledImage class and most of its functionnalities.

class components.labelled_image.LabelledImage(image, no_label_id=None, **kwargs)[source]

Class to manipulate labelled SpatialImage, eg. a segmented image.

__init__(image, no_label_id=None, **kwargs)[source]

LabelledImage initialisation method.

Parameters:
  • image (numpy.array or SpatialImage) – a numpy array or a SpatialImage containing a labelled array
  • no_label_id (int, optional) – if given define the “unknown label” (ie. not a label)
static __new__(cls, image, **kwargs)[source]

LabelledImage construction method.

Parameters:
  • image (numpy.array or SpatialImage) – a numpy array or a SpatialImage containing a labelled array
  • kwargs
  • ------
  • origin (list, optional) – coordinates of the origin in the image, default: [0,0] or [0,0,0]
  • voxelsize (list, optional.) – image voxelsize, default: [1.0,1.0] or [1.0,1.0,1.0]
  • dtype (str, optional) – image type, default dtype = input_array.dtype
  • metadata= (dict, optional) – dictionary of image metadata, default is an empty dict

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> from timagetk.components import LabelledImage
>>> test_array = np.random.randint(0, 255, (5, 5)).astype(np.uint8)
>>> test_array[0,:] = np.ones((5,), dtype=np.uint8)
>>> # - Construct from a NumPy array:
>>> lab_image = LabelledImage(test_array, voxelsize=[0.5,0.5], no_label_id=0)
>>> # - Construct from a SpatialImage:
>>> image_1 = SpatialImage(test_array, voxelsize=[0.5,0.5])
>>> lab_image = LabelledImage(image_1, no_label_id=0)
>>> isinstance(lab_image, np.ndarray)
True
>>> isinstance(lab_image, SpatialImage)
True
>>> isinstance(lab_image, LabelledImage)
True
>>> print(lab_image.voxelsize)
[0.5, 0.5]
>>> print(lab_image.no_label_id)
0
apply_trsf(trsf, trsf_unit='real', trsf_type='affine', **kwargs)[source]

Apply a known transformation to the image.

Parameters:
  • trsf (np.array, BalTrsf) – transformation to apply to the image
  • trsf_unit (str, optional) – unit of the transformation, ‘real’ or ‘voxel’
Returns:

transformed LabelledImage

Return type:

LabelledImage

boundingbox(labels=None, real=False, verbose=False)[source]

Return the bounding-box of a cell for given ‘labels’.

Parameters:
  • labels (None|int|list(int) or str, optional) – if None (default) returns all labels. if an integer, make sure it is in self.labels() if a list of integers, make sure they are in self.labels() if a string, should be in LABEL_STR to get corresponding list of cells (case insensitive)
  • real (bool, optional) – if False (default), return the bounding-boxes in voxel units, else in real units.
  • verbose (bool, optional) – control verbosity of the function

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a)
>>> im.boundingbox(7)
(slice(0, 3), slice(2, 4), slice(0, 1))
>>> im.boundingbox([7,2])
[(slice(0, 3), slice(2, 4), slice(0, 1)), (slice(0, 3), slice(0, 2), slice(0, 1))]
>>> im.boundingbox()
[(slice(0, 4), slice(0, 6), slice(0, 1)),
(slice(0, 3), slice(0, 2), slice(0, 1)),
(slice(1, 3), slice(4, 6), slice(0, 1)),
(slice(3, 4), slice(3, 4), slice(0, 1)),
(slice(1, 2), slice(2, 3), slice(0, 1)),
(slice(1, 2), slice(1, 2), slice(0, 1)),
(slice(0, 3), slice(2, 4), slice(0, 1))]
edge_coordinates(edges=None)[source]

Get a dictionary of edge coordinates.

Parameters:edges (len-3 tuple or list(tuple), optional) – if given, used to filter the returned list, else return all edges defined in the image by default
Returns:dictionary of len-3 labels with their voxel coordinates
Return type:dict
edges(edges=None)[source]

Get the list of edges found in the image, or make sure provided edges exists.

Parameters:edges (len-3 tuple or list(tuple), optional) – if given, used to filter the returned list, else return all edges defined in the image by default
Returns:list of edges found in the image
Return type:list
face_coordinates(faces=None)[source]

Get a dictionary of face coordinates.

Parameters:faces (len-2 tuple or list(tuple), optional) – if given, used to filter the returned list, else return all faces defined in the image by default
Returns:dictionary of len-2 labels with their voxel coordinates
Return type:dict
faces(faces=None)[source]

Get the list of faces found in the image, or make sure provided faces exists.

Parameters:faces (len-2 tuple or list(tuple), optional) – if given, used to filter the returned list, else return all faces defined in the image by default
Returns:list of faces found in the image
Return type:list
fuse_labels_in_image(labels, new_value='min', verbose=True)[source]

Fuse the provided list of labels to a given new_value, or the min or max of the list of labels.

Parameters:
  • labels (list) – list of labels to fuse
  • new_value (int or str, optional) – value used to replace the given list of labels, by default use the min value of the labels list. Can also be the max value.
  • verbose (bool, optional) – control verbosity
Returns:

Return type:

Nothing, modify the LabelledImage array (re-instantiate the object)

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a, no_label_id=0)
>>> im.fuse_labels_in_image([6, 7], new_value=8)
LabelledImage([[1, 2, 8, 8, 1, 1],
               [1, 8, 5, 8, 3, 3],
               [2, 2, 1, 8, 3, 3],
               [1, 1, 1, 4, 1, 1]])
>>> im.fuse_labels_in_image([6, 7], new_value='min')
LabelledImage([[1, 2, 6, 6, 1, 1],
               [1, 6, 5, 6, 3, 3],
               [2, 2, 1, 6, 3, 3],
               [1, 1, 1, 4, 1, 1]])
>>> im.fuse_labels_in_image([6, 7], new_value='max')
LabelledImage([[1, 2, 7, 7, 1, 1],
               [1, 7, 5, 7, 3, 3],
               [2, 2, 1, 7, 3, 3],
               [1, 1, 1, 4, 1, 1]])
get_image_with_labels(labels)[source]

Returns a LabelledImage with only the selected ‘labels’, the rest are replaced by “self._no_label_id”.

Parameters:labels (int or list(int)) – if None (default) returns all labels. if an integer, make sure it is in self.labels() if a list of integers, make sure they are in self.labels() if a string, should be in LABEL_STR to get corresponding list of cells (case insensitive)
Returns:labelled image with ‘labels’ only
Return type:LabelledImage

Notes

Require property ‘no_label_id’ to be defined!

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a, no_label_id=0)
>>> im.get_image_with_labels([2, 5])
LabelledImage([[0, 2, 0, 0, 0, 0],
               [0, 0, 5, 0, 0, 0],
               [2, 2, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0]])
get_image_without_labels(labels)[source]

Returns a LabelledImage without the selected labels.

Parameters:labels (None|int|list or str) – label or list of labels to keep in the image. if None, neighbors for all labels found in self.image will be returned. strings might be processed trough ‘self.labels_checker()’
Returns:labelled image with ‘labels’ only
Return type:LabelledImage

Notes

Require property ‘no_label_id’ to be defined!

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a, no_label_id=0)
>>> im.get_image_without_labels([2, 5])
LabelledImage([[1, 0, 7, 7, 1, 1],
               [1, 6, 0, 7, 3, 3],
               [0, 0, 1, 7, 3, 3],
               [1, 1, 1, 4, 1, 1]])
get_wall_image(labels=None, **kwargs)[source]

Get an image made of walls only (hollowed out cells).

Parameters:
  • labels (list, optional) – list of labels to return in the wall image, by default (None) return all labels
  • kwargs (dict, optional) – given to ‘hollow_out_cells’, ‘verbose’ accepted
Returns:

the labelled wall image

Return type:

LabelledImage

is_label_in_image(label)[source]

Returns True if the label is found in the image, else False.

Parameters:label (int) – label to check

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a)
>>> im.is_label_in_image(7)
True
>>> im.is_label_in_image(10)
False
isometric_resampling(method='min', **kwargs)[source]

Performs isometric resampling of the image using either the min, the max or a a given voxelsize value.

Parameters:method (str or float, optional) – change voxelsize to ‘min’ (default) or ‘max’ value of original voxelsize or to a given value.
label_array(label, dilation=None)[source]

Returns an array made from the labelled image cropped around the label bounding box.

Parameters:
  • label (int) – label for which to extract the neighbors
  • dilation (int, optional) – if defined (default is None), use this value as a dilation factor (in every directions) to be applied to the label boundingbox
Returns:

labelled array cropped around the label bounding box

Return type:

numpy.array

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a)
>>> im.label_array(7)
array([[7, 7],
       [5, 7],
       [1, 7]])
>>> im.label_array(7, dilation=1)
array([[2, 7, 7, 1],
       [6, 5, 7, 3],
       [2, 1, 7, 3],
       [1, 1, 4, 1]])
labels(labels=None)[source]

Get the list of labels found in the image, or make sure provided labels exists.

Parameters:labels (int or list, optional) – if given, used to filter the returned list, else return all labels defined in the image by default
Returns:list of label found in the image, except for ‘no_label_id’ (if defined)
Return type:list

Notes

Value defined for ‘no_label_id’ is removed from the returned list of labels since it does not refer to one.

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a)
>>> im.labels()
[1, 2, 3, 4, 5, 6, 7]
nb_labels()[source]

Return the number of labels.

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a)
>>> im.nb_labels()
7
>>> im = LabelledImage(a, no_label_id=1)
>>> im.nb_labels()
6
neighbors(labels=None, verbose=True)[source]

Return the dictionary of neighbors of each label. Except for ‘self.background’ & ‘self.no_label_id’, which are filtered out from the ‘labels’ list!

Parameters:
  • labels (None|int|list(int) or str, optional) – if None (default) returns all labels. if an integer, make sure it is in self.labels() if a list of integers, make sure they are in self.labels() if a string, should be in LABEL_STR to get corresponding list of cells (case insensitive)
  • verbose (bool, optional) – control verbosity

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a)
>>> im.neighbors(7)
[1, 2, 3, 4, 5]
>>> im.neighbors([7,2])
{7: [1, 2, 3, 4, 5], 2: [1, 6, 7] }
>>> im.neighbors()
{1: [2, 3, 4, 5, 6, 7],
 2: [1, 6, 7],
 3: [1, 7],
 4: [1, 7],
 5: [1, 6, 7],
 6: [1, 2, 5],
 7: [1, 2, 3, 4, 5] }
no_label_id

Get the value associated to no label. This is used as “unknown label” or “erase value”.

Returns:no_label_id – the value defined as the “no_label_id”
Return type:int

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a)
>>> im.labels()
[1, 2, 3, 4, 5, 6, 7]
>>> im.no_label_id
WARNING : no value defined for the 'no label' id!
>>> im = LabelledImage(a, no_label_id=1)
>>> im.labels()
[2, 3, 4, 5, 6, 7]
>>> im.no_label_id
1
node_coordinates(nodes=None)[source]

Get a dictionary of node coordinates.

Parameters:nodes (len-4 tuple or list(tuple), optional) – if given, used to filter the returned list, else return all nodes defined in the image by default
Returns:dictionary of len-4 labels with their voxel coordinates
Return type:dict
nodes(nodes=None)[source]

Get the list of nodes found in the image, or make sure provided nodes exists.

Parameters:nodes (len-4 tuple or list(tuple), optional) – if given, used to filter the returned list, else return all nodes defined in the image by default
Returns:list of nodes found in the image
Return type:list
relabel_from_mapping(mapping, clear_unmapped=False, **kwargs)[source]

Relabel the image following a given mapping indicating the original label as keys and their new labels as values. It is possible to get rid of all other label by setting clear_unmapped to True.

Parameters:
  • mapping (dict) – a dictionary indicating the original label as keys and their new labels as values
  • clear_unmapped (bool, optional) – if True (default False), only the mapped labels are kept in the returned image
Other Parameters:
 

verbose (bool, optional) – control code verbosity; default = False

Returns:

Return type:

Nothing, modify the LabelledImage array (re-instantiate the object)

remove_labels_from_image(labels, verbose=True)[source]

Remove ‘labels’ from self.image using ‘no_label_id’.

Parameters:
  • labels (list) – list of labels to remove from the image
  • verbose (bool, optional) – control verbosity
Returns:

Return type:

Nothing, modify the LabelledImage array (re-instantiate the object)

Notes

Require property ‘no_label_id’ to be defined!

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = LabelledImage(a, no_label_id=0)
>>> im.remove_labels_from_image([6, 7])
LabelledImage([[1, 2, 0, 0, 1, 1],
               [1, 0, 5, 0, 3, 3],
               [2, 2, 1, 0, 3, 3],
               [1, 1, 1, 4, 1, 1]])
topological_elements(element_order=None)[source]

Extract the coordinates of topological elements of order 2 (ie. face), 1 (ie. edge) and 0 (ie. node). Return their coordinates grouped by pair, triplet and quadruplet of labels.

Parameters:element_order (int or list, optional) – list of dimensional order of the elements to return
Returns:topo_elem – dictionary with topological elements order as key, each containing dictionaries of n-uplets as keys and coordinates array as values
Return type:dict

Notes

The order of the labels in the tuple defining the key is irrelevant, ie. coordinates of face (2, 5) is the same than (5, 2).

components.labelled_image.array_replace_label(array, label, new_label, bbox=None)[source]

Replace a label by a new one in a numpy array, may use boundingbox if provided.

Parameters:
  • array (numpy.array) – labelled array with integer values
  • label (int) – label value to replace
  • new_label (int) – label value to use for replacement
  • bbox (tuple(slice), optional) – tuple of slice indicating the location of the label within the image
Returns:

array – the modified array

Return type:

numpy.array

components.labelled_image.array_unique(array, return_index=False)[source]

Return an array made of the unique occurrence of each rows.

Parameters:
  • array (numpy.array) – the array to compare by rows
  • return_index (bool, optional) – if False (default) do NOT return the index of the unique rows, else do return them
Returns:

  • array_unique (numpy.array) – the array made of unique rows
  • unique_rows (numpy.array, if return_index == True) – index of the unique rows

Example

>>> from timagetk.components.labelled_image import array_unique
>>> a = np.array([[0, 1, 2, 3, 4],
                  [0, 1, 2, 3, 4],
                  [0, 1, 2, 3, 4],
                  [1, 2, 3, 4, 5],
                  [1, 2, 3, 4, 5]])
>>> array_unique(a)
array([[0, 1, 2, 3, 4],
       [1, 2, 3, 4, 5]])
components.labelled_image.connectivity_18()[source]

Create a 3D structuring element (array) of radius 1 with a 18-neighborhood.

Returns:a boolean numpy.array defining the 3D structuring element
Return type:numpy.array
components.labelled_image.connectivity_26()[source]

Create a 3D structuring element (array) of radius 1 with a 26-neighborhood.

Returns:a boolean numpy.array defining the 3D structuring element
Return type:numpy.array
components.labelled_image.connectivity_4()[source]

Create a 2D structuring element (array) of radius 1 with a 4-neighborhood.

Returns:a boolean numpy.array defining the 2D structuring element
Return type:numpy.array
components.labelled_image.connectivity_6()[source]

Create a 3D structuring element (array) of radius 1 with a 6-neighborhood.

Returns:a boolean numpy.array defining the 3D structuring element
Return type:numpy.array
components.labelled_image.connectivity_8()[source]

Create a 2D structuring element (array) of radius 1 with a 8-neighborhood.

Returns:a boolean numpy.array defining the 2D structuring element
Return type:numpy.array
components.labelled_image.default_structuring_element2d()[source]

Default 2D structuring element. This is a square (6-connectivity) of radius 1.

components.labelled_image.default_structuring_element3d()[source]

Default 3D structuring element. This is a cube (26-connectivity) of radius 1.

components.labelled_image.hollow_out_labels(image, **kwargs)[source]

Returns a labelled image containing only the wall, the rest is set to ‘image.no_label_id’.

Parameters:image (LabelledImage) – labelled image to transform
Returns:labelled image containing hollowed out cells (only walls).
Return type:LabelledImage

Notes

The Laplacian filter is used to detect wall positions, as it highlights regions of rapid intensity change.

components.labelled_image.image_with_labels(image, labels)[source]

Create a new image containing only the given labels. Use image as template (shape, origin, voxelsize & metadata).

Parameters:
  • image (LabelledImage) – labelled spatial image to use as template for labels extraction
  • labels (list) – list of labels to keep in the image
Returns:

the image containing only the given ‘labels’

Return type:

LabelledImage

components.labelled_image.image_without_labels(image, labels)[source]

Create a new image without the given labels. Use self.image as template (shape, origin, voxelsize & metadata).

Parameters:
  • image (LabelledImage) – labelled spatial image to use as template for labels deletion
  • labels (list) – list of labels to remove from the image
Returns:

an image without the given ‘labels’

Return type:

LabelledImage

components.labelled_image.label_inner_wall(labelled_img, label_id, struct=None, connectivity_order=1)[source]

Detect inner-wall position of a given ‘label_id’ within a segmented image ‘labelled_img’.

Parameters:
  • labelled_img (numpy.array or LabelledImage) – a labelled image containing ‘label_id’
  • label_id (int) – label to use for outer-wall detection
  • struct (numpy.array, optional) – a binary structure to use for erosion
  • connectivity_order (int, optional) – connectivity order determines which elements of the output array belong to the structure, i.e. are considered as neighbors of the central element. Elements up to a squared distance of connectivity from the center are considered neighbors, thus it may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors), with rank the number of dimensions of the image.
Returns:

a labelled array with only the inner-wall position as non-null value

Return type:

numpy.array|LabelledImage

components.labelled_image.label_outer_wall(labelled_img, label_id, struct=None, connectivity_order=1)[source]

Detect outer-wall position of a given ‘label_id’ within a segmented image ‘labelled_img’.

Parameters:
  • labelled_img (numpy.array or LabelledImage) – a labelled image containing ‘label_id’
  • label_id (int) – label to use for outer-wall detection
  • struct (numpy.array, optional) – a binary structure to use for dilation
  • connectivity_order (int, optional) – connectivity order determines which elements of the output array belong to the structure, i.e. are considered as neighbors of the central element. Elements up to a squared distance of connectivity from the center are considered neighbors, thus it may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors), with rank the number of dimensions of the image.
Returns:

a labelled array with only the outer-wall position as non-null value

Return type:

numpy.array|LabelledImage

components.labelled_image.neighbors_from_image(labelled_img, label_id)[source]

List neighbors of ‘label_id’ in ‘labelled_img’ as found in its outer-wall.

Parameters:
  • labelled_img (numpy.array or LabelledImage) – a labelled image containing ‘label_id’
  • label_id (int or list(int)) – label to use for neighbors detection
Returns:

neighbors label of ‘label_id’

Return type:

list

components.labelled_image.structuring_element(connectivity=26)[source]

Create a structuring element (array) Connectivity is among the 4-, 6-, 8-, 18-, 26-neighborhoods. 4 and 8 are 2-D elements, the others being 3-D (default = 26).

Parameters:connectivity (int, optional) – connectivity or neighborhood of the structuring element, default 26
Returns:a boolean numpy.array defining the required structuring element
Return type:numpy.array
components.labelled_image.test_structuring_element(array, struct)[source]

Test if the array and the strucutring element are compatible, ie. of same dimensionality.

Parameters:
  • array (numpy.array) – array on wich the structuring element should be applied
  • struct (numpy.array) – array defining the structuring element
Returns:

True if compatible, False otherwise

Return type:

bool

components.labelled_image.topological_elements_extraction2D(img, elem_order=None)[source]

Extract the topological elements of order 2 (ie. wall) and 1 (ie. wall-edge) by returning their coordinates grouped by pair or triplet of labels.

Parameters:
  • img (numpy.array) – numpy array representing a labelled image
  • elem_order (list, optional) – list of dimensional order of the elements to return, should be in [2, 1]
Returns:

topological_elements – dictionary with topological elements order as key, each containing dictionaries of n-uplets as keys and coordinates array as values

Return type:

dict

Example

>>> import numpy as np
>>> from timagetk.components.labelled_image import topological_elements_extraction2D
>>> im = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
                   [1, 2, 2, 3, 3, 3, 3, 1],
                   [1, 2, 2, 2, 3, 3, 3, 1],
                   [1, 2, 2, 2, 3, 3, 3, 1],
                   [1, 2, 2, 2, 3, 3, 3, 1],
                   [1, 4, 4, 4, 4, 4, 4, 1],
                   [1, 4, 4, 4, 4, 4, 4, 1],
                   [1, 4, 4, 4, 4, 4, 4, 1]])
>>> im.shape
(8, 8)
>>> # Extract topological elements coordinates:
>>> elem = topological_elements_extraction2D(im)
>>> # Get the wall-edge voxel coordinates between labels 1, 2 and 3:
>>> elem[1][(2, 3, 4)]
array([[ 0.5,  2.5,  0.5],
       [ 1.5,  2.5,  0.5],
       [ 1.5,  3.5,  0.5],
       [ 2.5,  3.5,  0.5],
       [ 3.5,  3.5,  0.5]])
>>> # Get the wall voxel coordinates between labels 2 and 3:
>>> elem[2][(2, 43)]
array([[ 5.5,  0.5,  0.5],
       [ 5.5,  1.5,  0.5],
       [ 5.5,  2.5,  0.5],
       [ 5.5,  3.5,  0.5],
       [ 5.5,  4.5,  0.5],
       [ 5.5,  5.5,  0.5],
       [ 5.5,  6.5,  0.5],
       [ 6.5,  0.5,  0.5],
       [ 6.5,  1.5,  0.5],
       [ 6.5,  2.5,  0.5],
       [ 6.5,  3.5,  0.5],
       [ 6.5,  4.5,  0.5],
       [ 6.5,  5.5,  0.5],
       [ 6.5,  6.5,  0.5]])
components.labelled_image.topological_elements_extraction3D(img, elem_order=None)[source]

Extract the topological elements of order 2 (ie. wall), 1 (ie. wall-edge) and 0 (ie. cell vertex) by returning their coordinates grouped by pair, triplet and quadruplet of labels.

Parameters:
  • img (numpy.array) – numpy array representing a labelled image
  • elem_order (list, optional) – list of dimensional order of the elements to return, should be in [2, 1, 0]
Returns:

topological_elements – dictionary with topological elements order as key, each containing dictionaries of n-uplets as keys and coordinates array as values

Return type:

dict

Example

>>> import numpy as np
>>> from timagetk.components.labelled_image import topological_elements_extraction3D
>>> a = np.array([[2, 2, 2, 3, 3, 3, 3, 3],
                  [2, 2, 2, 3, 3, 3, 3, 3],
                  [2, 2, 2, 2, 3, 3, 3, 3],
                  [2, 2, 2, 2, 3, 3, 3, 3],
                  [2, 2, 2, 2, 3, 3, 3, 3],
                  [4, 4, 4, 4, 4, 4, 4, 4],
                  [4, 4, 4, 4, 4, 4, 4, 4],
                  [4, 4, 4, 4, 4, 4, 4, 4]])
>>> bkgd_im = np.ones_like(a)
>>> # Create an image by adding a background and repeat the previous array 6 times as a Z-axis:
>>> im = np.array([bkgd_im, a, a, a, a, a, a]).transpose(1, 2, 0)
>>> im.shape
(8, 8, 7)
>>> # Extract topological elements coordinates:
>>> elem = topological_elements_extraction3D(im)
>>> # Get the cell-vertex coordinates between labels 1, 2, 3 and 4
>>> elem[0]
{(1, 2, 3, 4): array([[ 4.5,  3.5,  0.5]])}
>>> # Get the wall-edge voxel coordinates between labels 1, 2 and 3:
>>> elem[1][(1, 2, 3)]
array([[ 0.5,  2.5,  0.5],
       [ 1.5,  2.5,  0.5],
       [ 1.5,  3.5,  0.5],
       [ 2.5,  3.5,  0.5],
       [ 3.5,  3.5,  0.5]])
>>> # Get the wall voxel coordinates between labels 1 and 4:
>>> elem[2][(1, 4)]
array([[ 5.5,  0.5,  0.5],
       [ 5.5,  1.5,  0.5],
       [ 5.5,  2.5,  0.5],
       [ 5.5,  3.5,  0.5],
       [ 5.5,  4.5,  0.5],
       [ 5.5,  5.5,  0.5],
       [ 5.5,  6.5,  0.5],
       [ 6.5,  0.5,  0.5],
       [ 6.5,  1.5,  0.5],
       [ 6.5,  2.5,  0.5],
       [ 6.5,  3.5,  0.5],
       [ 6.5,  4.5,  0.5],
       [ 6.5,  5.5,  0.5],
       [ 6.5,  6.5,  0.5]])

TissueImage class

digraph inheritancebf234a53a0 { rankdir=LR; size="8.0, 12.0"; "components.tissue_image.TissueImage" [URL="#components.tissue_image.TissueImage",fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",target="_top",tooltip="Class to manipulate biological tissues, made of cells and potentially a"]; "timagetk.components.labelled_image.LabelledImage" -> "components.tissue_image.TissueImage" [arrowsize=0.5,style="setlinewidth(0.5)"]; "components.tissue_image.TissueImage2D" [fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",tooltip="Class specific to 2D multi-cellular tissues."]; "components.tissue_image.TissueImage" -> "components.tissue_image.TissueImage2D" [arrowsize=0.5,style="setlinewidth(0.5)"]; "components.tissue_image.TissueImage3D" [fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",tooltip="Class specific to 3D multi-cellular tissues."]; "components.tissue_image.TissueImage" -> "components.tissue_image.TissueImage3D" [arrowsize=0.5,style="setlinewidth(0.5)"]; "timagetk.components.labelled_image.LabelledImage" [fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5)",tooltip="Class to manipulate labelled SpatialImage, eg. a segmented image."]; }
class components.tissue_image.TissueImage(image, background=None, **kwargs)[source]

Class to manipulate biological tissues, made of cells and potentially a background.

__init__(image, background=None, **kwargs)[source]

TissueImage initialisation method.

Parameters:
  • image (LabelledImage) – the image containing the labelled tissue
  • background (int, optional) – if given define the label of the background (ie. space surrounding the tissue)
static __new__(cls, image, **kwargs)[source]

TissueImage construction method.

Parameters:
  • image (numpy.array|SpatialImage or LabelledImage) – a numpy array or a SpatialImage containing a labelled array
  • kwargs
  • ------
  • origin (list, optional) – coordinates of the origin in the image, default: [0,0] or [0,0,0]
  • voxelsize (list, optional.) – image voxelsize, default: [1.0,1.0] or [1.0,1.0,1.0]
  • dtype (str, optional) – image type, default dtype = input_array.dtype
  • metadata= (dict, optional) – dictionary of image metadata, default is an empty dict
  • no_label_id (int, optional) – if given define the “unknown label” (ie. not a label)

Example

>>> import numpy as np
>>> from timagetk.components import SpatialImage
>>> from timagetk.components import LabelledImage
>>> from timagetk.components import TissueImage
>>> test_array = np.random.randint(0, 255, (5, 5)).astype(np.uint8)
>>> test_array[0,:] = np.ones((5,), dtype=np.uint8)
>>> # - Construct from a NumPy array:
>>> tissue = TissueImage(test_array, voxelsize=[0.5,0.5], no_label_id=0, background=1)
>>> print(tissue.background)
1
>>> # - Construct from a SpatialImage:
>>> image = SpatialImage(test_array, voxelsize=[0.5,0.5])
>>> tissue = TissueImage(image, no_label_id=0, background=1)
>>> print(tissue.background)
1
>>> # - Construct from a LabelledImage:
>>> lab_image = LabelledImage(test_array, voxelsize=[0.5,0.5], no_label_id=0)
>>> tissue = TissueImage(lab_image, background=1)
>>> print(tissue.background)
1
background

Get the background label, can be None.

Returns:the label value for the background
Return type:int
cell_first_layer(**kwargs)[source]

List cells corresponding to the first layer of cells (epidermis). It is possible to provide an epidermal area threshold (minimum area in contact with the background) to consider a cell as in the first layer.

Returns:list of L1-cells
Return type:list
cells(cells=None)[source]

Get the list of cells found in the image, or make sure provided list of cells exists.

Parameters:cells (int or list, optional) – if given, used to filter the returned list, else return all cells defined in the image by default
Returns:list of cells found in the image, except for ‘background’ (if defined)
Return type:list

Notes

Value defined for ‘background’ is removed from the returned list of cells since it does not refer to one.

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import TissueImage
>>> im = TissueImage(a, background=1)
>>> im.labels()
[1, 2, 3, 4, 5, 6, 7]
>>> im.cells()
[2, 3, 4, 5, 6, 7]
fuse_cells_in_image(cells, value='min', verbose=True)[source]

Fuse the provided list of cells to its minimal value.

Parameters:
  • cells (list) – list of cells to fuse
  • value (str, optional) – value used to replace the given list of cells, by default use the min value of the cells list. Can also be the max value.
  • verbose (bool, optional) – control verbosity
Returns:

Return type:

Nothing, modify the TissueImage array (re-instantiate the object)

get_image_with_cells(cells, keep_background=True)[source]

Returns a LabelledImage with only the selected ‘cells’, the rest are replaced by “self._no_label_id”.

Parameters:
  • cells (int or list(int)) – if None (default) returns all cells. if an integer, make sure it is in self.cells() if a list of integers, make sure they are in self.cells() if a string, should be in LABEL_STR to get corresponding list of cells (case insensitive)
  • keep_background (bool, optional) – indicate if background label should be kept in the returned image
Returns:

template_im – labelled image with ‘cells’ only

Return type:

TissueImage

get_image_without_cells(cells, keep_background=True)[source]

Returns a SpatialImage without the selected cells.

Parameters:
  • cells (None|int|list or str) – label or list of cells to keep in the image. if None, neighbors for all cells found in self.image will be returned.
  • keep_background (bool, optional) – indicate if background label should be kept in the returned image
Returns:

template_im – labelled image with ‘cells’ only

Return type:

SpatialImage

nb_cells()[source]

Return the number of cells.

Example

>>> import numpy as np
>>> a = np.array([[1, 2, 7, 7, 1, 1],
                  [1, 6, 5, 7, 3, 3],
                  [2, 2, 1, 7, 3, 3],
                  [1, 1, 1, 4, 1, 1]])
>>> from timagetk.components import LabelledImage
>>> im = TissueImage(a, background=None)
>>> im.nb_cells()
7
>>> im = TissueImage(a, background=1)
>>> im.nb_cells()
6
relabelling_cells_from_mapping(mapping, clear_unmapped=False, **kwargs)[source]

Relabel the image following a given mapping indicating the original cell id as keys and their new id as value. It is possible to get rid of all unmapped cells by setting clear_unmapped to True.

Parameters:
  • mapping (dict) – a dictionary indicating the original cell id as keys and their new id as value
  • clear_unmapped (bool, optional) – if True (default False), only the mapped cells are kept in the returned image (unmapped set to ‘no_label_id’)
Other Parameters:
 

verbose (bool, optional) – control code verbosity; default = False

Returns:

Return type:

Nothing, modify the LabelledImage array (re-instantiate the object)

remove_cells_from_image(cells, verbose=True)[source]

Remove ‘cells’ from self.image using ‘erase_value’.

Parameters:
  • cells (list or str) – list of cells to remove from the image
  • verbose (bool, optional) – control verbosity
Returns:

Return type:

Nothing, modify the LabelledImage array (re-instantiate the object)

voxel_first_layer(connectivity, keep_background=True, **kwargs)[source]

Extract the first layer of non-background voxels in contact with the background as a LabelledImage.

Parameters:
  • connectivity (int) – connectivity or neighborhood of the structuring element
  • keep_background (bool, optional) – if true the LabelledImage returned contains the background in addition of the first layer of labelled voxels
Returns:

labelled image made of the first layer of voxel in contact with the background

Return type:

TissueImage

voxel_first_layer_coordinates(**kwargs)[source]

Returns an (Nxd) array of coordinates indicating voxels first layer position.

voxel_n_first_layer(n_voxel_layer, connectivity, keep_background=True, **kwargs)[source]

Extract the n-first layer of non-background voxels in contact with the background as a TissueImage.

Parameters:
  • n_voxel_layer (int) – number of layer of voxel from the background to get
  • connectivity (int) – connectivity or neighborhood of the structuring element
  • keep_background (bool, optional) – if true the LabelledImage returned contains the background in addition of the first layer of labelled voxels
Returns:

labelled image made of the selected number of voxel layers

Return type:

TissueImage