Components¶
SpatialImage class¶
Base image data structure.
- timagetk.components.spatial_image.AVAIL_TYPES = ['cdouble', 'cfloat', 'clongdouble', 'clongfloat', 'complex', 'complex128', 'complex256', 'complex64', 'double', 'float', 'float128', 'float16', 'float32', 'float64', 'int', 'int16', 'int32', 'int64', 'int8', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'short', 'single', 'singlecomplex', 'uint', 'uint16', 'uint32', 'uint64', 'uint8', 'ulonglong', 'ushort']¶
List of valid data type names.
- timagetk.components.spatial_image.DEFAULT_AXES_2D = 'YX'¶
Default axes order for 2D image.
- timagetk.components.spatial_image.DEFAULT_AXES_3D = 'ZYX'¶
Default axes order for 3D image.
- timagetk.components.spatial_image.DEFAULT_AXIS_ORDER_2D = {'X': 1, 'Y': 0}¶
Dictionary of default axes order for 2D image.
- timagetk.components.spatial_image.DEFAULT_AXIS_ORDER_3D = {'X': 2, 'Y': 1, 'Z': 0}¶
Dictionary of default axes order for 3D image.
- timagetk.components.spatial_image.DEFAULT_DTYPE¶
Default data type.
- timagetk.components.spatial_image.DEFAULT_ORIG_2D = [0, 0]¶
Default origin for 2D image.
- timagetk.components.spatial_image.DEFAULT_ORIG_3D = [0, 0, 0]¶
Default origin for 3D image.
- timagetk.components.spatial_image.DEFAULT_SIZE_UNIT = 1e-06¶
Default image size unit is micrometer (1e-6).
- timagetk.components.spatial_image.DEFAULT_VXS_2D = [1.0, 1.0]¶
Default voxels size for 2D image.
- timagetk.components.spatial_image.DEFAULT_VXS_3D = [1.0, 1.0, 1.0]¶
Default voxels size for 3D image.
- timagetk.components.spatial_image.DICT_TYPES = {'cdouble': <class 'numpy.complex128'>, 'cfloat': <class 'numpy.complex128'>, 'clongdouble': <class 'numpy.complex128'>, 'clongfloat': <class 'numpy.complex128'>, 'complex': <class 'numpy.complex128'>, 'complex128': <class 'numpy.complex128'>, 'complex256': <class 'numpy.complex128'>, 'complex64': <class 'numpy.complex64'>, 'double': <class 'numpy.float64'>, 'float': <class 'numpy.float64'>, 'float128': <class 'numpy.float64'>, 'float16': <class 'numpy.float16'>, 'float32': <class 'numpy.float32'>, 'float64': <class 'numpy.float64'>, 'int': <class 'numpy.int64'>, 'int16': <class 'numpy.int16'>, 'int32': <class 'numpy.int32'>, 'int64': <class 'numpy.int64'>, 'int8': <class 'numpy.int8'>, 'longcomplex': <class 'numpy.complex128'>, 'longdouble': <class 'numpy.float64'>, 'longfloat': <class 'numpy.float64'>, 'longlong': <class 'numpy.int64'>, 'short': <class 'numpy.int16'>, 'single': <class 'numpy.float32'>, 'singlecomplex': <class 'numpy.complex64'>, 'uint': <class 'numpy.uint64'>, 'uint16': <class 'numpy.uint16'>, 'uint32': <class 'numpy.uint32'>, 'uint64': <class 'numpy.uint64'>, 'uint8': <class 'numpy.uint8'>, 'ulonglong': <class 'numpy.uint64'>, 'ushort': <class 'numpy.uint16'>, 0: <class 'numpy.uint8'>, 1: <class 'numpy.int8'>, 10: <class 'numpy.float64'>, 11: <class 'numpy.complex64'>, 12: <class 'numpy.complex128'>, 13: <class 'numpy.complex128'>, 2: <class 'numpy.uint16'>, 3: <class 'numpy.int16'>, 4: <class 'numpy.uint32'>, 5: <class 'numpy.int32'>, 6: <class 'numpy.uint64'>, 7: <class 'numpy.int64'>, 8: <class 'numpy.float32'>, 9: <class 'numpy.float64'>}¶
//docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html
- Type:
Valid data type dictionary for images, for details about numpy types, see here https
- timagetk.components.spatial_image.PROTECT_PPTY = ['shape', 'min', 'max', 'mean']¶
List of protected image attribute or property.
- class timagetk.components.spatial_image.SpatialImage(array, origin=None, voxelsize=None, dtype=None, metadata=None, **kwargs)[source]¶
Data structure of 2D and 3D images.
A
SpatialImage
gathers a numpy array and some metadata (such as voxel size, 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 standardndarray
mechanism by which you take anndarray
of any subclass, and return a view of the array as another (specified) subclass, here aSpatialImage
.Warning
Modification of a property, when possible, will change the object, not return a new one!
Attributes
shape
andndim
are defined by the input array.Specifying
dtype
at object instantiation will change the array dtype to the given one.Images tags can be set or updated by a metadata dictionary.
- _extent¶
The physical extent of the image, sorted as (planes,) rows & columns [(Z,) Y, X].
- _origin¶
The coordinates of origin, sorted as (planes,) rows & columns [(Z,) Y, X].
- _voxelsize¶
The size of the pixels or voxels (2D/3D), sorted as (planes,) rows & columns [(Z,) Y, X].
- axes_order¶
Dictionary of axes order, e.g. {‘x’: 2, ‘y’: 1, ‘z’: 0} by default for 3D image.
- Type:
- metadata_image¶
A self generated list of attribute, contains basic image information such as: ‘shape’, ‘ndim’, ‘dtype’, ‘origin’, ‘voxelsize’ & ‘extent’. See
ImageMetadata
class docstring intimagetk.components.metadata
.- Type:
- 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_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:
- .. todo::
Add a
metric_unit
attribute and associated methods.Defines a
personal_metadata
attribute to store other metadata ?
- __array_finalize__(obj)[source]¶
Mechanism provided by numpy to allow subclasses instanciation.
- Parameters:
obj (object) – The object returned by the
__new__
method.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> 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, array, origin=None, voxelsize=None, dtype=None, metadata=None, **kwargs)[source]¶
Data structure of 2D and 3D images.
- Parameters:
array (numpy.ndarray or timagetk.SpatialImage) – 2D (YX) or 3D (ZYX) array defining an image, e.g. intensity or labelled image.
origin (list, optional) – (Z)YX coordinates of the origin in the image, default is
[0, 0]
if 2D or[0, 0, 0]
if 3D.voxelsize (list, optional.) – (Z)YX image voxelsize, default is
[1.0, 1.0]
if 2D or[1.0, 1.0, 1.0]
if 3D.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.
unit (float) – The size unit, in International System of Units (meters), associated to the image.
axes_order (dict) – Dictionary of axes orders, e.g. {‘x’: 2, ‘y’: 1, ‘z’: 0} by default for 3D image.
- Returns:
timagetk.SpatialImage – Image with metadata.
Notes
By default numpy arrays are C-contiguous with index starting at
0
. We follow this convention, meaning that 2D images are column then row sorted. For 3D images planes are thus the first index, i.e. to access plane 3 of aSpatialImage
namedimg
, do:plane = img[2]
. To use the array dtype (from numpy), leavedtype
toNone
.Example
>>> import numpy as np >>> from timagetk.io import imread >>> from timagetk.io.util import shared_dataset >>> from timagetk import SpatialImage >>> image_path = shared_dataset("p58", "intensity")[0] >>> spim = imread(image_path) >>> im = SpatialImage(spim, voxelsize=[1., 1., 1.])
>>> from timagetk.array_util import random_spatial_image >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], unit=1e-6) >>> isinstance(img, SpatialImage) # Test `SpatialImage` type True >>> isinstance(img, np.ndarray) # Test `np.ndarray` type => INHERITANCE True >>> print(img.voxelsize) # Access the voxel size information [1., 0.5, 0.5] >>> print(img.unit) # Access the unit information micrometer >>> print(img.shape) # Access the plane information (3, 5, 5) >>> img[0] # Access the first plane
- __reduce_ex__(_SpatialImage__protocol)[source]¶
Returns reconstruction info for pickle serialization
- astype(dtype, **kwargs)[source]¶
Copy of the SpatialImage with updated data type.
- Parameters:
dtype (str) – New type of data to apply.
- Returns:
SpatialImage – Image with the new data type.
Notes
Keyword arguments are passed to
numpy.astype()
method.Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((5, 5), voxelsize=[0.5, 0.5], dtype='uint8') >>> # Check the type: >>> img.dtype dtype('uint8') >>> print(img) SpatialImage object with following metadata: - shape: (5, 5) - ndim: 2 - dtype: uint8 - axes_order: YX - voxelsize: [0.5, 0.5] - unit: 1e-06 - origin: [0, 0] - extent: [2.0, 2.0] - acquisition_date: None >>> # Convert it to 16bits unsigned integers: >>> img16 = img.astype('uint16') >>> # Check the type: >>> img16.dtype dtype('uint16') >>> print(img16) SpatialImage object with following metadata: - shape: (5, 5) - ndim: 2 - dtype: uint16 - axes_order: YX - voxelsize: [0.5, 0.5] - unit: 1e-06 - origin: [0, 0] - extent: [2.0, 2.0] - acquisition_date: None
- property axes_order¶
Get
SpatialImage
physical axes ordering.- Returns:
str –
SpatialImage
physical axes ordering.
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> print(img.axes_order) ZYX
- property axes_order_dict¶
Get
SpatialImage
physical axes ordering.- Returns:
dict –
SpatialImage
physical axes ordering.
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> print(img.axes_order_dict) {'Z': 0, 'Y': 1, 'X': 2}
- crop(start, stop, axis='z')[source]¶
Crop the selected axis and preserve data between given start & stop slice id.
- startint
The slice id to start cropping.
- stopint
The slice id to stop cropping.
- axis{‘x’, ‘y’, ‘z’} or int, optional
Name of the axis to crop, or its index. By default, the
z
axis.
- SpatialImage
The cropped image
- ValueError
If the image is not 3D and
axis='z'
. Ifstart
and/orstop
indexes does not exist on this axis.
>>> from timagetk.io.util import shared_dataset >>> from timagetk.io import imread >>> from timagetk.visu.stack import orthogonal_view >>> img = imread(shared_dataset("p58", "intensity")[0]) >>> # Example - Get the first half of the image on the x-axis >>> cropped_x = img.crop(0, img.get_shape('x')//2, 'x' ) >>> print(img.get_extent('x')) 91.74656248092651 >>> print(cropped_x.get_extent('x')) 45.67296123504639 >>> print(img) SpatialImage object with following metadata:
shape: (160, 230, 230)
ndim: 3
dtype: uint8
axes_order: ZYX
voxelsize: [0.40064001083374023, 0.40064001083374023, 0.40064001083374023]
unit: 1e-06
origin: [0, 0, 0]
extent: [63.7017617225647, 91.74656248092651, 91.74656248092651]
acquisition_date: None
>>> print(cropped_x) SpatialImage object with following metadata: - shape: (160, 230, 115) - ndim: 3 - dtype: uint8 - axes_order: ZYX - voxelsize: [0.40064001083374023, 0.40064001083374023, 0.40064001083374023] - unit: 1e-06 - origin: [0, 0, 0] - extent: [63.7017617225647, 91.74656248092651, 45.67296123504639] - acquisition_date: None >>> orthogonal_view(img) >>> orthogonal_view(cropped_x)
- property extent¶
Get
SpatialImage
physical extent.- Returns:
list –
SpatialImage
physical extent.
Notes
It is related to the array shape and image voxelsize.
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> print(img.extent) [3.0, 2.5, 2.5]
- get_array(dtype=None)[source]¶
Return a copy of the image as a
numpy.ndarray
object.- Parameters:
dtype (str or numpy.dtype, optional) – If specified, default is
None
, change the dtype of the returned array.- Returns:
numpy.ndarray – Numpy array linked to the object (Z)YX sorted.
Notes
Changing the dtype of the array force the return of a copy.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> from timagetk import SpatialImage >>> isinstance(img, SpatialImage) True >>> # Get the array linked to the SpatialImage: >>> array = img.get_array() >>> isinstance(array, SpatialImage) False >>> import numpy as np >>> isinstance(array, np.ndarray) True
>>> # Return the pointer: >>> array.fill(0) >>> print(array) >>> print(img.get_array())
- static get_available_types()[source]¶
Print the available bits type dictionary.
See also
DICT_TYPES
dict Dictionary of available bits type.
- Returns:
dict – Dictionary of available bits type.
- get_dtype()[source]¶
Get the human-readable image type.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5]) >>> img.get_dtype() 'uint8'
- get_extent(axis=None)[source]¶
Return the extent of the image or of the selected axis, if any.
- Parameters:
axis ({'x', 'y', 'z'}, optional) – If specified, axis for which the extent should be returned.
- Returns:
list of float or float – The extent of the image or of the selected axis, if any. The list is sorted like the physical axes order.
Notes
The extent of an image is related to its shape and voxelsize.
See also
timagetk.util.compute_extent
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5]) >>> img.get_extent() [2., 2., 2.] >>> img.get_extent('x') 2.0 >>> img.get_extent('y') 2.0 >>> img.get_extent('z') 2.0
- get_pixel(idx)[source]¶
Get
SpatialImage
pixel value at given array coordinates.- Parameters:
idx (list) – Indices as list of integers.
- Returns:
value – Pixel value.
- Raises:
TypeError – If the given idx is not a list.
ValueError – If the number of idx is wrong, should be the image dimensionality. If the idx coordinates are not within the image boundaries.
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> img.get_pixel([1,1])
- get_region(region)[source]¶
Extract a region using list of start & stop indexes.
There should be two values per dimension in region, e.g.
region=[5, 8, 5, 8]
for a 2D image. If the image is 3D and, in one dimension the start and stop indexes only differ by one (one layer of voxels), the returned image will be transformed to 2D!- Parameters:
region (list) – Indexes as list of integers, e.g. [y-start, y-stop, x-start, x-stop] for a 2D image.
- Returns:
SpatialImage – Output image.
- Raises:
TypeError – If the given region is not a list.
ValueError – If the number of indexes in region is wrong, should be twice the image dimensionality. If the region coordinates are not within the array boundaries.
Example
>>> from timagetk import SpatialImage >>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 2D SpatialImage: >>> img = random_spatial_image((5, 5), voxelsize=[0.5, 0.5], dtype='uint8') >>> region = [1, 3, 1, -1] # y-start, y-stop, x-start, x-stop >>> out_img = img.get_region(region) >>> isinstance(out_img, SpatialImage) True >>> out_img.get_array() >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((5, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> region = [1, 2, 1, 3, 1, 3] # z-start, z-stop, y-start, y-stop, x-start, x-stop >>> out_img = img.get_region(region) >>> isinstance(out_img, SpatialImage) True >>> out_img.is2D() True
- get_shape(axis=None)[source]¶
Return the shape of the image or of the selected axis, if any.
- Parameters:
axis ({'x', 'y', 'z'}, optional) – If specified, axis for which the shape should be returned.
- Returns:
list of int or int – The shape of the image or of the selected axis, if any. The list is sorted like the physical axes order.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> img.get_shape() [3, 5, 5] >>> img.get_shape('z') 3
- get_slice(slice_id, axis='z')[source]¶
Return a SpatialImage with only one slice for given axis.
- Parameters:
- Returns:
SpatialImage – 2D SpatialImage with only the required slice.
- Raises:
ValueError – If the image is not 3D and
axis='z'
. Ifslice_id
does not exist, i.e. should satisfy:0 < slice_id < max(len(axis))
.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> print(img.axes_order_dict) {'Z': 0, 'Y': 1, 'X': 2} >>> print(img.get_shape()) [3, 5, 5] >>> # Taking an existing z-slice from a 3D image works fine: >>> img_z = img.get_slice(1, 'z') >>> print(img_z.axes_order_dict) {'Y': 0, 'X': 1} >>> print(img_z.get_shape()) [5, 5] >>> # Taking an existing x-slice from a 3D image works fine: >>> img_x = img.get_slice(3, 'x') >>> print(img_x.axes_order_dict) {'Z': 0, 'Y': 1} >>> print(img_x.get_shape()) [3, 5]
>>> # Down-sampling x-axis of a 3D image: >>> nx = img.get_shape('x') >>> img_ds_x2 = img.get_slice(range(0, nx, 2), 'x')
>>> # Taking an NON-existing z-slice from a 3D image raises an error: >>> img.get_slice(50, 'z')
>>> # Taking a z-slice from a 2D image raises an error: >>> img_z.get_slice(5, 'z')
- get_unit(short=False)[source]¶
Get the human-readable image unit in International System of Units (SI).
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5]) >>> print(img.get_unit()) micrometer >>> print(img.get_unit(short=True)) µm
- get_voxelsize(axis=None)[source]¶
Return the voxel-size of the image or of the selected axis, if any.
- Parameters:
axis ({'x', 'y', 'z'}, optional) – If specified, axis for which the voxel-size should be returned.
- Returns:
list of float or float – The voxel-size of the image or of the selected axis, if any. The list is sorted like the physical axes order.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> img.get_voxelsize() [1., 0.5, 0.5] >>> img.get_voxelsize('z') 1.0
- get_xyz_array(dtype=None)[source]¶
Get an XY(Z) sorted
numpy.ndarray
from aSpatialImage
.- Parameters:
dtype (str or numpy.dtype, optional) – If specified, default is
None
, change the dtype of the returned array.- Returns:
numpy.ndarray – Numpy array linked to the SpatialImage, XY(Z) sorted.
.. deprecated:: – This method should be removed for the next major release
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> from timagetk import SpatialImage >>> isinstance(img, SpatialImage) True >>> # Get the array linked to the SpatialImage: >>> array = img.get_xyz_array() >>> print(array.shape)
- invert_axis(axis)[source]¶
Revert given axis.
- Parameters:
axis ({'x', 'y', 'z'}) – Axis to invert, can be either ‘x’, ‘y’ or ‘z’ (if 3D).
- Returns:
SpatialImage – Image with reverted array for selected axis.
- Raises:
ValueError – If given
axis
is not in {‘x’, ‘y’, ‘z’} for 3D images or not in {‘x’, ‘y’} for 2D images.
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> print(img.get_slice(0, "z").get_array()) >>> inv_img = img.invert_axis(axis='z') >>> print(inv_img.get_slice(0, "z").get_array())
- is2D()[source]¶
Return True if the SpatialImage is 2D, else
False
.Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> img.is2D() False >>> # Take the first z-slice: >>> img2d = img.get_slice(0, 'z') # Equivalent to img[0] >>> img2d.is2D() True
- is3D()[source]¶
Return True if the SpatialImage is 3D, else
False
.Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> img.is3D() True
- is_isometric()[source]¶
Test image isometry.
Tests if the voxelsize values are the same for every axis or not.
- Returns:
bool –
True
if the image is isometric, elseFalse
.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5),voxelsize=[1., 0.5, 0.5],dtype='uint8') >>> img.is_isometric() False >>> from timagetk.algorithms.resample import isometric_resampling >>> # Transform to small isometric 3D SpatialImage: >>> img_iso = isometric_resampling(img, method='max') >>> img_iso.is_isometric() True >>> img_iso.voxelsize [1.0, 1.0, 1.0]
- property metadata¶
Get
SpatialImage
metadata dictionary.- Returns:
dict – Metadata dictionary.
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5),voxelsize=[1., 0.5, 0.5],dtype='uint8',metadata={'info': "test OK"}) >>> print(img.metadata['info']) 'test OK' >>> print(img.metadata) {'info': 'test OK', 'shape': (3, 5, 5), 'ndim': 3, 'dtype': dtype('uint8'), 'origin': [0, 0, 0], 'voxelsize': [1.0, 0.5, 0.5], 'get_extent': [3.0, 2.5, 2.5]}
- property origin¶
Get
SpatialImage
origin.- Returns:
list –
SpatialImage
origin coordinates.
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5),voxelsize=[1., 0.5, 0.5],dtype='uint8') >>> print(img.origin) [0, 0, 0]
- set_pixel(idx, value)[source]¶
Change
SpatialImage
pixel|voxel value at given array coordinates.- Parameters:
idx (list) – Array coordinates as list of integers.
value (array.dtype) – New value for the pixel|voxel, should be compatible with the array dtype.
- Raises:
TypeError – If the given idx is not a list.
ValueError – If the number of idx is wrong, should be the image dimensionality. If the idx coordinates are not within the image boundaries.
Example
>>> import numpy as np >>> from timagetk import SpatialImage >>> test_array = np.ones((3,3), dtype=np.uint8) >>> image = SpatialImage(test_array) >>> image.set_pixel([1, 1], 2) >>> image.get_array() array([[1, 1, 1], [1, 2, 1], [1, 1, 1]], dtype=uint8) >>> # Trying to set a value not compatible with the array.dtype: >>> image.set_pixel([2, 2], 0.5) >>> image.get_array() array([[1, 1, 1], [1, 2, 1], [1, 1, 0]], dtype=uint8) >>> # Trying to set a value not compatible with the array.dtype: >>> image.set_pixel([0, 0], -6) >>> image.get_array() array([[250, 1, 1], [ 1, 2, 1], [ 1, 1, 0]], dtype=uint8) >>> image.set_pixel([0, 0], -6)
- set_region(region, value)[source]¶
Replace a region of the image by given value.
- Parameters:
region (list) – Indices as list of integers.
value (array.dtype or ndarray) – New value for the selected pixels, type of
SpatialImage
array.
- Returns:
SpatialImage –
SpatialImage
instance.- Raises:
TypeError – If the given region is not a list.
ValueError – If the number of indexes in region is wrong, should be twice the image dimensionality. If the region coordinates are not within the array boundaries. If the region and value shape mismatch. If the given value is not of the same dtype as the array or not a ndarray.
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((5, 5), voxelsize=[0.5, 0.5], dtype='uint8') >>> region = [1, 3, 1, 3] >>> img.set_region(region, 3) >>> img.get_array()
- set_slice(slice_id, array, axis='z')[source]¶
Set the values of an axis slice to given array.
- Parameters:
slice_id (int) – Slice number to modify.
array (numpy.ndarray or int) – Values that replace those at given slice id, if an integer make an array with this value.
axis (str in {'x', 'y', 'z'}, optional) – Axis to use for slicing, default to ‘z’.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> sl = img.get_slice(0, axis='z') >>> print(sl.get_array()) >>> new_sl = random_spatial_image((5, 5), voxelsize=[0.5, 0.5], dtype='uint8') >>> img.set_slice(0, new_sl, axis='z') >>> print(new_sl) >>> print(img.get_slice(0, 'z'))
- to_2d()[source]¶
Convert a 3D SpatialImage to a 2D SpatialImage.
Conversion is possible only if there is a “flat” axis (i.e. with only one slice along this axis).
- Returns:
SpatialImage – The 2D SpatialImage.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage with one z-slice: >>> img = random_spatial_image((1, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> img.to_2d() >>> # Initialize a random (uint8) 3D SpatialImage with one y-slice: >>> img = random_spatial_image((5, 1, 5), voxelsize=[0.5, 1., 0.5], dtype='uint8') >>> img.to_2d() >>> # Initialize a random (uint8) 3D SpatialImage with one x-slice: >>> img = random_spatial_image((5, 5, 1), voxelsize=[0.5, 0.5, 1.], dtype='uint8') >>> img.to_2d()
- to_3d(flat_axis='z')[source]¶
Convert a 2D SpatialImage to a 3D SpatialImage.
- Parameters:
flat_axis ({'x', 'y', 'z'}, optional) – Flat axis to add to the 2D image. By default, ‘z’ axis.
- Returns:
SpatialImage – The 3D image with a flat axis.
Notes
Obtained 3D SpatialImage has a “flat” axis (i.e. with only one slice along this axis). The voxelsize of this axis is set to
1.
. The origin of this axis is set to0
.Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 2D SpatialImage: >>> img = random_spatial_image((5, 5), voxelsize=[0.5, 0.5], dtype='uint8') >>> z_flat = img.to_3d(flat_axis='z') >>> z_flat.get_shape() >>> y_flat = img.to_3d(flat_axis='y') >>> y_flat.get_shape() >>> x_flat = img.to_3d(flat_axis='x') >>> x_flat.get_shape() >>> x_flat.origin >>> x_flat.voxelsize
- to_vtimage()[source]¶
Return the same object converted as
vtImage
instance.- Returns:
vtImage – A vtImage object.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 4, 5), voxelsize=[1., 0.51, 0.5], dtype='uint8') >>> vt_im = img.to_vtimage() >>> from vt import vtImage >>> isinstance(vt_im, vtImage) True >>> vt_im.shape() >>> vt_im.spacing()
>>> # Initialize a random (uint8) 2D SpatialImage: >>> img = random_spatial_image((4, 5), voxelsize=[0.51, 0.5], dtype='uint8') >>> vt_im = img.to_vtimage() >>> from vt import vtImage >>> isinstance(vt_im, vtImage) True >>> vt_im.shape() >>> vt_im.spacing()
- transpose(*axes)[source]¶
Permute image axes to given order, reverse by default.
- Parameters:
axes (list of int or list of str, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.
- Returns:
SpatialImage – The image with permuted axes.
Examples
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 4, 5), voxelsize=[0.51, 0.52, 0.53], dtype='uint8') >>> img.metadata {'shape': (3, 4, 5), 'ndim': 3, 'dtype': dtype('uint8'), 'axes_order': 'ZYX', 'voxelsize': [0.51, 0.52, 0.53], 'unit': 1e-06, 'origin': (0.0, 0.0, 0.0), 'extent': [1.02, 1.56, 2.12], 'acquisition_date': None} >>> img_t = img.transpose() >>> img_t.metadata {'shape': (5, 4, 3), 'ndim': 3, 'dtype': dtype('uint8'), 'axes_order': 'XYZ', 'voxelsize': [0.53, 0.52, 0.51], 'unit': 1e-06, 'origin': [0.0, 0.0, 0.0], 'extent': [2.12, 1.56, 1.02], 'acquisition_date': None} >>> print(img_t.shape) # `shape` attribute has been updated (5, 4, 3) >>> print(img_t.voxelsize) # `voxelsize` attribute has been updated [0.53, 0.52, 0.51] >>> # Method `transpose` accept axes names as input >>> img_t = img.transpose('xzy') >>> print(img_t.shape) (5, 3, 4) >>> # Method `transpose` accept a tuple of axes names as input >>> img_t = img.transpose('x', 'z', 'y') >>> print(img_t.shape) (5, 3, 4) >>> # Initialize a random (uint8) 2D SpatialImage: >>> img = random_spatial_image((4, 5), voxelsize=[0.52, 0.53], dtype='uint8') >>> img_t = img.transpose() >>> # Transpose update the shape attribute of the image (here reversed): >>> print(img_t.shape) (5, 4)
- property unit¶
Return the unit in International System of Units (SI).
- Returns:
float – The unit in International System of Units (SI).
- property voxelsize¶
Get
SpatialImage
voxelsize, sorted as planes, columns & rows.- Returns:
list –
SpatialImage
voxelsize
Example
>>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5),voxelsize=[1., 0.5, 0.5],dtype='uint8') >>> print(img.voxelsize) [1., 0.5, 0.5]
- timagetk.components.spatial_image.compare_kwargs_metadata(kwd_val, md_val, dim, kwd_name)[source]¶
Compare two values, usually keyword or attribute against metadata.
- timagetk.components.spatial_image.default_axes_order(input_array)[source]¶
Return the default physical axes order depending on the array dimensionality.
- Parameters:
input_array (numpy.ndarray) – 2D or 3D array defining an image, e.g. intensity or labelled image.
- Returns:
str – Default physical axes ordering.
- timagetk.components.spatial_image.default_origin(input_array)[source]¶
Return the default origin depending on the array dimensionality.
- Parameters:
input_array (numpy.ndarray) – 2D or 3D array defining an image, e.g. intensity or labelled image.
- Returns:
list – Default origin coordinates.
- timagetk.components.spatial_image.default_voxelsize(input_array)[source]¶
Return the default pixel or voxel size depending on the array dimensionality.
- Parameters:
input_array (numpy.ndarray) – 2D or 3D array defining an image, e.g. intensity or labelled image.
- Returns:
list – Default voxel size.
LabelledImage class¶
LabelledImage class and associated functionalities.
- Return rule according to object (label, surfel, linel, pointel) input type:
if a list of ids is given, a dictionary with the ids as keys & the features (bounding-box, neighbors,…) as values is returned
if a single id is given, the corresponding feature is return, type depending on feature type.
- Id rules according to object type:
all ‘label features’ have a unique id represented by an integer;
all ‘surfel features’ have a unique id represented by a len-2 unordered tuple made of the two label ids defining it;
all ‘linel features’ have a unique id represented by a len-3 unordered tuple made of the three label ids defining it;
all ‘pointel features’ have a unique id represented by a len-4 unordered tuple made of the four label ids defining it;
The term ‘unordered tuple’ means that the order of ids defining the tuple does not matter: (i,j) == (j,i)
.
The ids are sorted by ascending order anyway.
- class timagetk.components.labelled_image.LabelledImage(image, **kwargs)[source]¶
Class to manipulate labelled image, aka. segmented image.
- __init__(image, not_a_label=None, **kwargs)[source]¶
LabelledImage initialisation method.
- Parameters:
image (numpy.ndarray or timagetk.SpatialImage) – An array or
SpatialImage
containing a labelled array.not_a_label (int, optional) – If given define the value that is not a label. Can be set later with the not_a_label property.
- static __new__(cls, image, **kwargs)[source]¶
LabelledImage construction method.
- Parameters:
image (numpy.ndarray or timagetk.SpatialImage) – A numpy array or a SpatialImage containing a labelled array.
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. Defaults to the input image type.
metadata (dict, optional) – Dictionary of image metadata. Defaults to an empty dict.
Examples
>>> import numpy as np >>> from timagetk import SpatialImage >>> from timagetk import LabelledImage >>> from timagetk.array_util import DUMMY_SEG_2D >>> # Example #1 - Construct from a NumPy array: >>> lab_image = LabelledImage(DUMMY_SEG_2D, voxelsize=[0.5,0.5], not_a_label=0) >>> print(lab_image) LabelledImage object with following metadata: - shape: (13, 12) - ndim: 2 - dtype: uint8 - origin: [0, 0] - voxelsize: [0.5, 0.5] - unit: 1e-06 - acquisition_date: None - extent: [6.0, 5.5] - not_a_label: 0 >>> # Example #2 - Construct from a SpatialImage: >>> image_1 = SpatialImage(DUMMY_SEG_2D, voxelsize=[0.5,0.5]) >>> lab_image = LabelledImage(image_1, not_a_label=0) >>> isinstance(lab_image, np.ndarray) # show inheritance True >>> isinstance(lab_image, SpatialImage) # show inheritance True >>> isinstance(lab_image, LabelledImage) True >>> print(lab_image.voxelsize) [0.5, 0.5] >>> print(lab_image.not_a_label) 0
- boundingbox(labels=None, real=False)[source]¶
Return the bounding-box of a single or a list of labels.
- Parameters:
- Returns:
dict – Label indexed bounding-boxes dictionary:
{l: bounding-box(l)}
forl
in 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 import LabelledImage >>> im = LabelledImage(a) >>> im.boundingbox(7) {7: (slice(0, 3, None), slice(2, 4, None))} >>> im.boundingbox([7, 2]) {2: (slice(0, 3, None), slice(0, 2, None)), 7: (slice(0, 3, None), slice(2, 4, None))} >>> im.boundingbox() {1: (slice(0, 4, None), slice(0, 6, None)), 2: (slice(0, 3, None), slice(0, 2, None)), 3: (slice(1, 3, None), slice(4, 6, None)), 4: (slice(3, 4, None), slice(3, 4, None)), 5: (slice(1, 2, None), slice(2, 3, None)), 6: (slice(1, 2, None), slice(1, 2, None)), 7: (slice(0, 3, None), slice(2, 4, None))}
- fuse_labels_in_image(labels, new_value='min')[source]¶
Fuse the provided list of labels to a given new_value, or the min or max of the list of labels.
- Parameters:
Notes
When manually specifing a new_value, beware that it is not already defined in the labelled image, except if that what you want.
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 import LabelledImage >>> im = LabelledImage(a, not_a_label=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]¶
Return a copy of the labelled image with only the selected labels.
- Parameters:
labels (int or list of int) – A list of labels to keep in the returned copy.
- Returns:
LabelledImage – Labelled image with only the selected labels.
Notes
Require the definition of the not_a_label property!
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 import LabelledImage >>> im = LabelledImage(a, not_a_label=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]¶
Return a copy of the labelled image without the selected labels.
- Parameters:
labels (int or list of int) – Label or list of labels to remove in the returned copy.
- Returns:
LabelledImage – Labelled image without the selected labels.
Notes
Require the definition of the not_a_label property!
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 import LabelledImage >>> im = LabelledImage(a, not_a_label=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_label_margin_image(labels=None, **kwargs)[source]¶
Return a hollow labelled image, i.e. with label margins only.
- Parameters:
labels (int or list of int, optional) – If
None
(default), returns values for all known labels. If an integer or a list of integers, make sure they are in self.labels().- Returns:
LabelledImage – The labelled margin image.
Notes
The “inside” of each label is replaced with self.not_a_label. Keyword arguments are passed to hollow_out_labelled_image.
Example
>>> import numpy as np >>> a = np.array([[1, 2, 2, 2, 2, 3, 3, 3], [1, 2, 2, 2, 2, 3, 3, 3], [1, 2, 2, 2, 2, 3, 3, 3], [1, 2, 2, 2, 2, 3, 3, 3]]) >>> from timagetk import LabelledImage >>> im = LabelledImage(a, not_a_label=0) >>> im.get_label_margin_image([2, 3]) LabelledImage([[0, 2, 0, 0, 2, 3, 0, 0], [0, 2, 0, 0, 2, 3, 0, 0], [0, 2, 0, 0, 2, 3, 0, 0], [0, 2, 0, 0, 2, 3, 0, 0]])
- get_region(region)[source]¶
Extract a region using list of start & stop indexes.
There should be two values per dimension in region, e.g.
region=[5, 8, 5, 8]
for a 2D image. If the image is 3D and, in one dimension the start and stop indexes only differ by one (one layer of voxels), the returned image will be transformed to 2D!- Parameters:
region (list) – Indexes as list of integers, e.g.
[y-start, y-stop, x-start, x-stop]
for a 2D image.- Returns:
timagetk.LabelledImage – Output image.
- Raises:
TypeError – If the given region is not a list.
ValueError – If the number of indexes in region is wrong, should be twice the image dimensionality. If the region coordinates are not within the array boundaries.
Example
>>> from timagetk import LabelledImage >>> from timagetk.array_util import dummy_labelled_image_2D >>> # Initialize a dummy (uint8) 2D LabelledImage with a YX shape of 13x12: >>> img = dummy_labelled_image_2D([0.5, 0.5]) >>> region = [1, 5, 1, 5] # y-start, y-stop, x-start, x-stop >>> out_img = img.get_region(region) >>> isinstance(out_img, LabelledImage) True >>> out_img LabelledImage([[2, 4, 4, 4], [2, 2, 4, 4], [2, 2, 2, 4], [2, 2, 2, 3]], dtype=uint8) >>> from timagetk.array_util import dummy_labelled_image_3D >>> # Initialize a dummy (uint8) 3D LabelledImage with a ZYX shape of 5x13x12: >>> img = dummy_labelled_image_3D([1.0, 0.5, 0.5]) >>> region = [2, 3, 1, 5, 1, 5] # z-start, z-stop, y-start, y-stop, x-start, x-stop >>> out_img = img.get_region(region) >>> isinstance(out_img, LabelledImage) True >>> out_img.is2D() True >>> out_img LabelledImage([[2, 4, 4, 4], [2, 2, 4, 4], [2, 2, 2, 4], [2, 2, 2, 3]], dtype=uint8)
- get_slice(slice_id, axis='z')[source]¶
Return a LabelledImage with only one slice for given axis.
- Parameters:
- Returns:
timagetk.LabelledImage – 2D LabelledImage with only the required slice.
- Raises:
ValueError – If the image is not 3D and
axis='z'
. Ifslice_id
does not exist, i.e. should satisfy:0 < slice_id < max(len(axis))
.
Examples
>>> from timagetk.array_util import dummy_labelled_image_3D >>> # Initialize a dummy 3D LabelledImage with a ZYX shape of 5x13x12: >>> img = dummy_labelled_image_3D([1., 0.5, 0.5]) >>> print(img.axes_order) {'Z': 0, 'Y': 1, 'X': 2} >>> print(img) # print a summary of the dummy labelled image LabelledImage object with following metadata: - shape: (5, 13, 12) - ndim: 3 - dtype: uint8 - origin: [0, 0, 0] - voxelsize: [1.0, 0.5, 0.5] - extent: [4.0, 6.0, 5.5] - not_a_label: 0 >>> # Taking an existing z-slice from a 3D image works fine: >>> img_z = img.get_slice(1, 'z') >>> print(img_z.axes_order) {'Y': 0, 'X': 1} >>> print(img_z) LabelledImage object with following metadata: - not_a_label: 0 - shape: (13, 12) - ndim: 2 - dtype: uint8 - origin: [0, 0] - voxelsize: [0.5, 0.5] - extent: [6.0, 5.5] >>> # Taking an existing x-slice from a 3D image works fine: >>> img_x = img.get_slice(3, 'x') >>> print(img_x.axes_order) {'Z': 0, 'Y': 1}
>>> # Down-sampling x-axis of a 3D image: >>> nx = img.get_shape('x') >>> img_ds_x2 = img.get_slice(range(0, nx, 2), 'x') >>> print(img_ds_x2.axes_order) {'Z': 0, 'Y': 1, 'X': 2} >>> print(img_ds_x2) LabelledImage object with following metadata: - shape: (5, 13, 6) - ndim: 3 - dtype: uint8 - origin: [0, 0, 0] - unit: 1e-06 - acquisition_date: None - not_a_label: 0 - voxelsize: [1.0, 0.5, 1.0] - extent: [4.0, 6.0, 5.0]
>>> # Taking an NON-existing z-slice from a 3D image raises an error: >>> img.get_slice(50, 'z')
>>> # Taking a z-slice from a 2D image raises an error: >>> img_z.get_slice(5, 'z')
- invert_axis(axis)[source]¶
Revert given axis.
- Parameters:
axis ({'x', 'y', 'z'}) – Axis to invert, can be either ‘x’, ‘y’ or ‘z’ (if 3D).
- Returns:
timagetk.LabelledImage – Image with reverted array for selected axis.
- Raises:
ValueError – If given
axis
is not in {‘x’, ‘y’, ‘z’} for 3D images or not in {‘x’, ‘y’} for 2D images.
Example
>>> from timagetk.array_util import dummy_labelled_image_3D >>> # Initialize a dummy (uint8) 3D LabelledImage with a ZYX shape of 5x13x12: >>> img = dummy_labelled_image_3D([1.0, 0.5, 0.5]) >>> print(img.get_array()) >>> inv_img = img.invert_axis(axis='z') >>> print(inv_img.get_array())
- is_label_in_image(label)[source]¶
Test wheter the given label is in the image or not.
- Parameters:
label (int) – Value that should be present in the labelled image.
- Returns:
bool –
True
if the label is found in the image, elseFalse
.
Examples
>>> 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 import LabelledImage >>> im = LabelledImage(a) >>> im.is_label_in_image(7) True >>> im.is_label_in_image(10) False
- label_array(label, dilation=0)[source]¶
Return the array of the cropped labelled image by the label’s bounding-box.
- Parameters:
- Returns:
timagetk.LabelledImage – Labelled image cropped around the label bounding-box.
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 import LabelledImage >>> im = LabelledImage(a, not_a_label=0) >>> im.label_array(7) LabelledImage([[7, 7], [5, 7], [1, 7]]) >>> im.label_array(7, dilation=1) LabelledImage([[2, 7, 7, 1], [6, 5, 7, 3], [2, 1, 7, 3], [1, 1, 4, 1]])
- label_coordinates(labels=None, real=True, axes_order=None)[source]¶
Return the coordinates of each voxels representing a label.
- Parameters:
labels (int or list of int, optional) – If
None
(default), returns values for all known labels. If an integer or a list of integers, make sure they are in self.labels().real (bool, optional) – If
True
(default), returns the coordinates in real world units, else in voxel units.axes_order (str, optional) – Order of the axes or dimension to use for returned coordinates.
- Returns:
dict – Label indexed coordinates dictionary:
{l: coordinates(l)}
forl
in labels.
Example
>>> from timagetk import LabelledImage >>> from timagetk.array_util import dummy_labelled_image_3D >>> im = LabelledImage(dummy_labelled_image_3D()) >>> im.label_coordinates(7) >>> im.label_coordinates([7, 2])
- labels(labels=None)[source]¶
Get the list of labels found in the image, or filter given labels list by those.
- Parameters:
labels (int or list of int, optional) – If an integer or a list of integers, make sure they are in the image.
- Returns:
list – List of labels found in the image.
Notes
If defined, the attribute
self.not_a_label
is excluded from the returned list 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 import LabelledImage >>> im = LabelledImage(a) >>> im.labels() [1, 2, 3, 4, 5, 6, 7] >>> im = LabelledImage(a, not_a_label=1) >>> im.labels() [2, 3, 4, 5, 6, 7] >>> im.labels(7) [7]
- linel_coordinates(linel_ids=None, real=False, axes_order=None)[source]¶
Get a dictionary of linel coordinates.
- Parameters:
linel_ids (len-3 tuple or list(tuple), optional) – If given, filter the returned dictionary of linel coordinates. Else returns it for all linels found in the image (default).
real (bool, optional) – If
True
(default), returns the coordinates in real world units, else in voxel units.axes_order (str, optional) – Order of the axes or dimension to use for returned coordinates. By default, use the same order as the image axes order.
- Returns:
dict – Linel sorted dictionary of coordinates:
{(i, j, k): coordinates(i, j, k)}
for(i, j, k)
in linel_ids.
Examples
>>> from timagetk.array_util import dummy_labelled_image_3D >>> im = dummy_labelled_image_3D() >>> im.linel_coordinates([(1, 3, 7)], True) {(1, 3, 7): array([[ 4.5, 8. , 0.5], [ 4.5, 9. , 0.5], [ 5.5, 10. , 0.5], [ 4. , 7.5, 0.5], [ 5. , 9.5, 0.5], [ 6. , 10.5, 0.5]])}
- linels(linel_ids=None)[source]¶
Get the list of linels found in the image, or filter the list with those found in the image.
- Parameters:
linel_ids (len-3 tuple or list(tuple), optional) – If given, filter the returned list of linels. Else returns the list of all linels found in the image (default).
- Returns:
list of tuples – List of linel ids, expressed as len-3 tuples of integers.
Example
>>> from timagetk.array_util import dummy_labelled_image_3D >>> im = dummy_labelled_image_3D() >>> im.linels() [(1, 3, 7), (1, 3, 6), (1, 2, 7), (1, 2, 3), (1, 3, 5), (1, 4, 5), (1, 5, 6), (1, 6, 7), (2, 3, 7), (3, 5, 6), (1, 2, 4), (1, 3, 4), (3, 4, 5), (2, 3, 4), (3, 6, 7)]
- nb_labels()[source]¶
Return the number of labels found in the labelled image.
- Returns:
int – The number of labels found in the labelled image.
Examples
>>> 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 import LabelledImage >>> im = LabelledImage(a) >>> im.nb_labels() 7 >>> im = LabelledImage(a, not_a_label=1) >>> im.nb_labels() 6
- neighbors(labels=None)[source]¶
Return the neighbors list of labels.
- Parameters:
labels (None or int or list of int, optional) – If
None
(default), returns values for all known labels. If an integer or a list of integers, make sure they are in self.labels().- Returns:
dict – Label indexed neighborhood dictionary:
{l: neighbors(l)}
forl
in labels.
Example
>>> import numpy as np >>> a = np.array([[1, 2, 7, 7, 1, 1], [1, 6, 5, 7, 3, 3], [2, 2, 2, 7, 3, 3], [1, 1, 1, 4, 1, 1]]) >>> from timagetk 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] } >>> im = LabelledImage(a, not_a_label=1) >>> im.neighbors(1) [2, 3, 4, 7] >>> im.neighbors([1, 2]) {1: [2, 3, 4, 7], 2: [1, 5, 7]}
- property not_a_label¶
Get the value associated to not a label state.
This is used as “unknown label” or “erase value”.
- Returns:
int – The value defined as not a label.
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 import LabelledImage >>> im = LabelledImage(a) >>> im.labels() [1, 2, 3, 4, 5, 6, 7] >>> im.not_a_label WARNING : no value defined for the 'not a label' id! >>> im = LabelledImage(a, not_a_label=1) >>> im.labels() [2, 3, 4, 5, 6, 7] >>> im.not_a_label 1
- pointel_coordinates(pointel_ids=None, real=False, axes_order='xyz')[source]¶
Get a dictionary of pointel coordinates.
- Parameters:
pointel_ids (len-4 tuple or list(tuple), optional) – If given, filter the returned dictionary of pointel coordinates. Else returns it for all pointels found in the image (default).
real (bool, optional) – If
True
(default), returns the coordinates in real world units, else in voxel units.axes_order (str, optional) – Order of the axes or dimension to use for returned coordinates.
- Returns:
dict – Pointel sorted dictionary of coordinates:
{(i, j, k, l): coordinates(i, j, k, l)}
for(i, j, k, l)
in pointel_ids.
Examples
>>> from timagetk.array_util import dummy_labelled_image_3D >>> im = dummy_labelled_image_3D() >>> im.pointel_coordinates() {(1, 3, 6, 7): array([[6.5, 10.5, 0.5]]), (1, 3, 5, 6): array([[9.5, 7.5, 0.5]]), (1, 2, 3, 4): array([[3.5, 3.5, 0.5]]), (1, 2, 3, 7): array([[3.5, 7.5, 0.5]]), (1, 3, 4, 5): array([[8.5, 3.5, 0.5]])}
- pointels(pointel_ids=None)[source]¶
Get the list of pointels found in the image, or filter the list with those found in the image.
- Parameters:
pointel_ids (len-4 tuple or list(tuple), optional) – If given, filter the returned list of pointels. Else returns the list of all pointels found in the image (default).
- Returns:
list of tuples – List of pointel ids, expressed as len-4 tuples of integers.
Example
>>> from timagetk.array_util import dummy_labelled_image_3D >>> im = dummy_labelled_image_3D() >>> im.pointels() [(1, 3, 6, 7), (1, 3, 5, 6), (1, 2, 3, 4), (1, 2, 3, 7), (1, 3, 4, 5)]
- remove_labels_from_image(labels)[source]¶
Remove labels from image using by setting them to not_a_label.
Notes
Require the definition of the not_a_label attribute!
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 import LabelledImage >>> im = LabelledImage(a, not_a_label=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]])
- surfel_coordinates(surfel_ids=None, real=False, axes_order=None)[source]¶
Get a dictionary of surfel coordinates.
- Parameters:
surfel_ids (len-2 tuple or list(tuple), optional) – If given, filter the returned dictionary of surfel coordinates. Else returns it for all surfels found in the image (default).
real (bool, optional) – If
True
(default), returns the coordinates in real world units, else in voxel units.axes_order (str, optional) – Order of the axes or dimension to use for returned coordinates.
- Returns:
dict – Surfel sorted dictionary of coordinates:
{(i, j): coordinates(i, j)}
for(i, j)
in surfel_ids.
Examples
>>> from timagetk.array_util import dummy_labelled_image_3D >>> im = dummy_labelled_image_3D() >>> surfel_coords = im.surfel_coordinates() >>> surfel_coords[(6, 7)] array([[ 6.5, 11. , 1. ], [ 6.5, 12. , 1. ], [ 6.5, 11. , 2. ], [ 6.5, 12. , 2. ], [ 6.5, 11. , 3. ], [ 6.5, 12. , 3. ], [ 6.5, 11. , 4. ], [ 6.5, 12. , 4. ]])
- surfels(surfel_ids=None)[source]¶
Get the list of surfels found in the image, or filter the list with those found in the image.
- Parameters:
surfel_ids (len-2 tuple or list(tuple), optional) – If given, filter the returned list of surfels. Else returns the list of all surfels found in the image (default).
- Returns:
list of tuples – List of surfel ids, expressed as len-2 tuples of integers
Example
>>> from timagetk.array_util import dummy_labelled_image_3D >>> im = dummy_labelled_image_3D() >>> all_surfels = im.surfels() >>> print(all_surfels) [(1, 2), (2, 7), (1, 3), (6, 7), (4, 5), (5, 6), (1, 4), (1, 5), (1, 6), (2, 3), (3, 6), (1, 7), (3, 7), (3, 4), (2, 4), (3, 5)]
- topological_elements(element_order=None, verbose=True)[source]¶
Extract the topological elements coordinates of a labelled image.
- Parameters:
element_order (int or list of int, optional) – List of dimensional order of the elements to return, should be in [2, 1, 0]. Defaults to
None
, returns a dictionary with every order of topological elements.- Returns:
dict – Dictionary with topological elements order as key, each containing dictionaries of n-uplets as keys and coordinates array as values.
Notes
A “surfel” is a dimension 2 element with a neighborhood size equal to 2. A “linel” is a dimension 1 element with a neighborhood size equal to 3. A “pointel” is a dimension 0 element with a neighborhood size equal to 4. The order of the labels in the tuple defining the key is irrelevant, i.e. coordinates of surfel
(2, 5)
is the same as the one of(5, 2)
.Examples
>>> from timagetk.array_util import dummy_labelled_image_3D >>> im = dummy_labelled_image_3D() >>> topo = im.topological_elements() >>> topo[0] # access "pointel" positions {(1, 2, 3, 4): array([[0.5, 3.5, 3.5]]), (1, 2, 3, 7): array([[0.5, 7.5, 3.5]]), (1, 3, 4, 5): array([[0.5, 3.5, 8.5]]), (1, 3, 5, 6): array([[0.5, 7.5, 9.5]]), (1, 3, 6, 7): array([[ 0.5, 10.5, 6.5]])} >>> from timagetk.array_util import dummy_labelled_image_2D >>> im = dummy_labelled_image_2D() >>> topo = im.topological_elements() >>> topo[1] # access "pointel" positions
- transpose(*axes)[source]¶
Permute image axes to given order, reverse by default.
- Parameters:
axes (list of int or list of str, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.
- Returns:
timagetk.LabelledImage – The image with permuted axes.
Examples
>>> from timagetk.array_util import dummy_labelled_image_3D >>> # -- Transpose works with 3D images: >>> # Initialize a dummy (uint8) 3D LabelledImage with a ZYX shape of 5x13x12: >>> img = dummy_labelled_image_3D([1.0, 0.5, 0.5]) >>> img_t = img.transpose() >>> # Transpose update the shape attribute of the image (here reversed): >>> print(img_t.shape) (12, 13, 5) >>> # Transpose update the voxelsize attribute of the image (here reversed): >>> print(img_t.voxelsize) [0.5, 0.5, 1.0] >>> # Transpose update the metadata dictionary of the image: >>> print(img_t.metadata) {'shape': (12, 13, 5), 'ndim': 3, 'dtype': dtype('uint8'), 'unit': 1e-06, 'acquisition_date': None, 'not_a_label': 0, 'origin': [0, 0, 0], 'voxelsize': [0.5, 0.5, 1.0], 'extent': [5.5, 6.0, 4.0]} >>> # -- Transpose accept axe names as input: >>> img_t = img.transpose('xyz') >>> print(img_t.shape) (12, 13, 5) >>> img_t = img.transpose('x', 'y', 'z') >>> print(img_t.shape) (5, 4, 3)
>>> from timagetk.array_util import dummy_labelled_image_2D >>> # -- Transpose works with 2D images: >>> # Initialize a dummy (uint8) 2D LabelledImage with a YX shape of 13x12: >>> img = dummy_labelled_image_2D([0.5, 0.5]) >>> img_t = img.transpose() >>> # Transpose update the shape attribute of the image (here reversed): >>> print(img_t.shape) (5, 4)
- timagetk.components.labelled_image.array_replace_label(array, label, new_label, bbox=None)[source]¶
Replace a label by a new one in a numpy array.
Providing a bounding-box of the label should speed up the process.
- Parameters:
array (numpy.ndarray) – Labelled array with integer values.
label (int) – Label to replace.
new_label (int) – New label to use as replacement.
bbox (tuple of slice, optional) – Tuple of slices indicating the location of the label within the image.
- Returns:
numpy.ndarray – The modified array.
Examples
>>> import numpy as np >>> a = np.array([[1, 2, 2, 2, 2, 3, 3, 3], [1, 2, 2, 2, 2, 3, 3, 3], [1, 2, 2, 2, 2, 3, 3, 3], [1, 2, 2, 2, 2, 3, 3, 3]]) >>> from timagetk.components.labelled_image import array_replace_label >>> array_replace_label(a, label=1, new_label=0) array([[0, 2, 2, 2, 2, 3, 3, 3], [0, 2, 2, 2, 2, 3, 3, 3], [0, 2, 2, 2, 2, 3, 3, 3], [0, 2, 2, 2, 2, 3, 3, 3]])
- timagetk.components.labelled_image.assert_labelled_image(obj, obj_name=None)[source]¶
Tests whether given object is a LabelledImage.
- Parameters:
obj (instance) – Object to test.
obj_name (str, optional) – If given used as object name for
TypeError
printing.
- Raises:
TypeError – If obj is not a
LabelledImage
instance.
Examples
>>> from timagetk.components.labelled_image import assert_labelled_image >>> from timagetk import LabelledImage >>> from timagetk.array_util import DUMMY_SEG_2D >>> # Example 1 - NumPy array: >>> assert_labelled_image(DUMMY_SEG_2D, "dummy labelled array") TypeError: Input 'dummy labelled array' is not a `LabelledImage` instance. >>> # Example 2 - LabelledImage: >>> lab_image = LabelledImage(DUMMY_SEG_2D, voxelsize=[0.5,0.5], not_a_label=0) >>> assert_labelled_image(lab_image, "dummy labelled array")
- timagetk.components.labelled_image.connectivity_18()[source]¶
Create a 3D structuring element (array) of radius 1 with a 18-neighborhood.
- Returns:
numpy.ndarray – A boolean array defining the 3D structuring element.
- timagetk.components.labelled_image.connectivity_26()[source]¶
Create a 3D structuring element (array) of radius 1 with a 26-neighborhood.
- Returns:
numpy.ndarray – A boolean array defining the 3D structuring element.
- timagetk.components.labelled_image.connectivity_4()[source]¶
Create a 2D structuring element (array) of radius 1 with a 4-neighborhood.
- Returns:
numpy.ndarray – A boolean array defining the 2D structuring element.
- timagetk.components.labelled_image.connectivity_6()[source]¶
Create a 3D structuring element (array) of radius 1 with a 6-neighborhood.
- Returns:
numpy.ndarray – A boolean array defining the 3D structuring element.
- timagetk.components.labelled_image.connectivity_8()[source]¶
Create a 2D structuring element (array) of radius 1 with a 8-neighborhood.
- Returns:
numpy.ndarray – A boolean array defining the 2D structuring element.
- timagetk.components.labelled_image.default_structuring_element2d()[source]¶
Default 2D structuring element.
- timagetk.components.labelled_image.default_structuring_element3d()[source]¶
Default 3D structuring element.
- timagetk.components.labelled_image.hollow_out_labelled_image(image, **kwargs)[source]¶
Return a labelled image containing only the label margins.
- Parameters:
image (timagetk.LabelledImage) – Labelled image to transform.
- Returns:
timagetk.LabelledImage – Labelled image containing hollowed out labels (only their margins).
Notes
The ‘non-margin voxels’ are set to image.not_a_label. The Laplacian filter is used to detect label margins, as it highlights regions of rapid intensity change.
Examples
>>> from timagetk.components.labelled_image import hollow_out_labelled_image >>> from timagetk import LabelledImage >>> from timagetk.io import imread >>> from timagetk.io.util import shared_dataset >>> from timagetk.visu.stack import orthogonal_view >>> seg_img_path = shared_dataset("sphere", "segmented")[0] >>> seg_img = imread(seg_img_path, rtype=LabelledImage, not_a_label=0) >>> hollow_seg = hollow_out_labelled_image(seg_img) >>> orthogonal_view(hollow_seg, cmap='glasbey', val_range='auto')
>>> # Create a membrane image from the labelled image >>> hollow_seg = hollow_out_labelled_image(seg_img) >>> from skimage import img_as_ubyte >>> from timagetk import SpatialImage >>> membrane_img = SpatialImage(img_as_ubyte(hollow_seg), voxelsize=seg_img.get_voxelsize()) # convert image to unsigned 8bits >>> membrane_img[membrane_img != 0] = 255 >>> orthogonal_view(membrane_img,cmap='gray') >>> # Make it a bit more realistic: >>> from timagetk.algorithms.linearfilter import gaussian_filter >>> real_membrane_img = gaussian_filter(membrane_img, sigma=0.5, real=True) >>> orthogonal_view(real_membrane_img, cmap='gray')
- timagetk.components.labelled_image.image_with_labels(image, labels, erase_value=None)[source]¶
Create a new image containing only the given labels.
Use image as template to get shape, origin, voxel-size & metadata.
- Parameters:
- Returns:
timagetk.LabelledImage – The image containing only the given labels.
Examples
>>> from timagetk.components.labelled_image import image_with_labels >>> from timagetk.synthetic_data.labelled_image import example_layered_sphere_labelled_image >>> im = example_layered_sphere_labelled_image(n_points=10, n_layers=1, extent=50.) >>> print(im.labels()) # `1` is background and `12` is the central round 'core' label [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> im2 = image_with_labels(im, [1, 2, 3, 4, 5]) >>> print(im2.labels()) [1, 2, 3, 4, 5]
- timagetk.components.labelled_image.image_without_labels(image, labels, erase_value=None)[source]¶
Create a new image without the given labels.
Use image as template to get shape, origin, voxelsize & metadata.
- Parameters:
- Returns:
timagetk.LabelledImage – An image without the given labels.
Examples
>>> from timagetk.components.labelled_image import image_without_labels >>> from timagetk.synthetic_data.labelled_image import example_layered_sphere_labelled_image >>> from timagetk.io import imread >>> from timagetk import TissueImage3D >>> im = example_layered_sphere_labelled_image(n_points=10, n_layers=1, extent=50.) >>> print(im.labels()) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> im2 = image_without_labels(im, [1, 2, 3, 4, 5]) >>> print(im2.labels()) [6, 7, 8, 9, 10, 11, 12]
- timagetk.components.labelled_image.label_inner_margin(labelled_img, label, struct=None, connectivity_order=1)[source]¶
Return an array with only inner-margin values of a label.
- Parameters:
labelled_img (numpy.ndarray or timagetk.LabelledImage) – A labelled image containing the given label.
label (int) – Label to use for inner-margin detection.
struct (numpy.ndarray, 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:
numpy.ndarray or timagetk.LabelledImage – A labelled array with only the inner-margin position as non-null value.
Examples
>>> 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 import LabelledImage >>> from timagetk.components.labelled_image import label_inner_margin >>> im = LabelledImage(a) >>> label_inner_margin(im, 7) LabelledImage([[0, 0, 7, 7, 0, 0], [0, 0, 0, 7, 0, 0], [0, 0, 0, 7, 0, 0], [0, 0, 0, 0, 0, 0]])
- timagetk.components.labelled_image.label_neighbors(labelled_img, label, **kwargs)[source]¶
List neighbors of label in labelled image.
List of unique non-null labels as found in label outer-margin.
- Parameters:
labelled_img (numpy.ndarray or timagetk.LabelledImage) – A labelled image containing the given label.
label (int or list of int) – Label to use for neighbors detection.
struct (numpy.ndarray, 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:
list – Neighbors of given label.
Examples
>>> import numpy as np >>> from timagetk.components.labelled_image import label_neighbors >>> arr = 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]]) >>> label_neighbors(arr, 7) # works with a numpy array [1, 2, 3, 4, 5] >>> from timagetk import LabelledImage >>> from timagetk.components.labelled_image import connectivity_8 >>> im = LabelledImage(arr) >>> label_neighbors(im, 7) # works with a LabelledImage [1, 2, 3, 4, 5] >>> label_neighbors(im, 5) [1, 6, 7] >>> label_neighbors(im, 5, struct=connectivity_8()) # `struct=connectivity_4()` by default [1, 2, 6, 7] >>> label_neighbors(im, 5, connectivity_order=2) # `connectivity_order=1` by default [1, 2, 6, 7] >>> label_neighbors(arr, [5, 6]) # works with a list of labels {5: [1, 6, 7], 6: [1, 2, 5]}
- timagetk.components.labelled_image.label_outer_margin(labelled_img, label, struct=None, connectivity_order=1)[source]¶
Return an array with only outer-margin values of a label.
- Parameters:
labelled_img (numpy.ndarray or timagetk.LabelledImage) – A labelled image containing the given label.
label (int) – Label to use for its outer-margin detection.
struct (numpy.ndarray, 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:
numpy.ndarray or timagetk.LabelledImage – A labelled array with only the outer-margin position as non-null value.
Examples
>>> 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 import LabelledImage >>> from timagetk.components.labelled_image import label_outer_margin >>> im = LabelledImage(a) >>> label_outer_margin(im, 7) LabelledImage([[0, 2, 0, 0, 1, 0], [0, 0, 5, 0, 3, 0], [0, 0, 1, 0, 3, 0], [0, 0, 0, 4, 0, 0]])
- timagetk.components.labelled_image.labels_at_stack_margins(labelled_img, voxel_distance_from_margin=1, labels_to_keep=None)[source]¶
Return a list of labels in contact with the margins of the stack.
All ids within a defined (1 by default) voxel_distance_from_margin will be considered.
- Parameters:
- Returns:
list – The list of labels in contact with the margins of the stack.
Examples
>>> from timagetk import LabelledImage >>> from timagetk.io import imread >>> from timagetk.io.util import shared_dataset >>> from timagetk.components.labelled_image import labels_at_stack_margins >>> seg_im = LabelledImage(imread(shared_dataset("p58", "segmented")[0])) >>> margin_labels = labels_at_stack_margins(seg_im, 5, labels_to_keep=[1]) >>> print(f"Found {len(margin_labels)} labels at the stack margins!") >>> print(margin_labels)
- timagetk.components.labelled_image.relabel_from_mapping(image, mapping, clear_unmapped=True, **kwargs)[source]¶
Relabel the image using a mapping.
The mapping is a dictionary indicating the original label as keys and their new labels as values.
- Parameters:
image (timagetk.LabelledImage or timagetk.TissueImage2D or timagetk.TissueImage3D) – The labelled image to relabel.
mapping (dict) – The dictionary indicating the original label as keys and their new labels as values.
clear_unmapped (bool, optional) – If
True
(default), only the mapped labels are kept in the returned image.dtype (str) – The dtype of returned array. Defaults to
image.dtype
.rtype (Any) – The image type to return, e.g.
SpatialImage
,LabelledImage
.
Notes
It is possible to get rid of all other label by setting
clear_unmapped
toTrue
. Setting clear_unmapped toFalse
, there is no guaranty that the new label value is different from those of its neighbors, resulting in a label ‘fusion’.- Returns:
timagetk.LabelledImage or timagetk.TissueImage2D or timagetk.TissueImage3D – The relabelled image, image type will be the same as input.
Examples
>>> import numpy as np >>> a = np.array([[1, 1, 7, 7, 1, 1], [1, 6, 5, 7, 3, 3], [2, 2, 1, 7, 3, 3], [1, 1, 1, 4, 1, 1]], dtype='uint8') >>> from timagetk import LabelledImage >>> from timagetk.components.labelled_image import relabel_from_mapping >>> im = LabelledImage(a, not_a_label=0) >>> mapping = {6:5, 5:6} >>> relab_im = relabel_from_mapping(im, mapping) >>> print(relab_im.get_array()) [[0 0 0 0 0 0] [0 5 6 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0]] >>> relab_im = relabel_from_mapping(im, mapping, clear_unmapped=False) >>> print(relab_im.get_array()) [[1 1 7 7 1 1] [1 5 6 7 3 3] [2 2 1 7 3 3] [1 1 1 4 1 1]]
- timagetk.components.labelled_image.structuring_element(connectivity=26)[source]¶
Create a structuring element.
Connectivity is among the 4-, 6-, 8-, 18-, 26-neighborhoods.
4
and8
are 2D elements, the others are 3D.- Parameters:
connectivity (int, optional) – Connectivity or neighborhood of the structuring element, default is
26
.- Returns:
numpy.ndarray – A boolean array defining the required structuring element.
MultiAngleImage class¶
Important
This is a work in progress!
Multi-angle image class.
Since they can be made of a great number of images, and that these can be too big to save them all in memory we use disk file access instead of loading everything in memory.
- timagetk.components.multi_angle.DEF_DICT_TRSF = {'affine': {}, 'rigid': {}, 'vectorfield': {}}¶
Default transformations dictionary.
- timagetk.components.multi_angle.DEF_IMG_EXT = 'mha'¶
Default extension for image files.
- timagetk.components.multi_angle.MEAN_IMG_FNAME = '{}-mean_image-iter{}.{}'¶
Naming convention for mean image files.
- class timagetk.components.multi_angle.MultiAngleImage(list_img, prefix='', **kwargs)[source]¶
Multi-angles image data structure.
This data structure rely on filenames to save some memory during the registration process, especially for large images.
- trsfs¶
Dictionary of transformation files location structured as {‘<trsf_type>’: {n_iter : {(flo_angle, ref_angle): ‘<path_to_Trsf>’}}}, with:
'<trsf_type>'
the type of transformationn_iter
the iteration idflo_angle
&ref_angle
the floating and reference angle-id, use ‘mean_<n_iter>’ when using mean image as reference'<path_to_Trsf>'
the corresponding transformation file location
- Type:
- .. todo::
Use saved ‘acquisition_time’ to check images are indeed multiple angle of the same object!
Examples
>>> from timagetk.components.multi_angle import MultiAngleImage >>> from timagetk.io.util import shared_data >>> from timagetk.io import imread >>> list_fnames = [shared_data(f'p58-t0-a{idx}.lsm', "p58") for idx in range(3)] >>> # Step 1: Create the MultiAngle object >>> ma = MultiAngleImage(list_fnames)
>>> # Manual creation of a rigid trsf to generate an artificial multi-angles image: >>> from timagetk.algorithms.trsf import create_trsf >>> from timagetk.algorithms.trsf import apply_trsf >>> trsf = create_trsf('random', trsf_type='rigid', angle_range=[0.2, 0.25], translation_range=[0.2, 1.2]) >>> trsf.print() >>> float_img = apply_trsf(ref_img, trsf)
>>> # Step 1: Create the MultiAngle object >>> ma = MultiAngleImage([ref_img, float_img])
- __init__(list_img, prefix='', **kwargs)[source]¶
MultiAngleImage object constructor.
- Parameters:
- Raises:
IOError – If not all image files can be found.
- __weakref__¶
list of weak references to the object (if defined)
- get_angle_image(angle_id)[source]¶
Return SpatialImage for given angle-id.
- Parameters:
angle_id (int) – Angle-id of the image, i.e. same order as given list.
- Returns:
SpatialImage – Image of given angle-id
- get_average_image(iter_id)[source]¶
Return the average image corresponding to the iteration.
- Parameters:
iter_id (int) – Iteration step to get the image from.
- Returns:
SpatialImage – The corresponding averaged intensity image.
- get_images()[source]¶
Return all SpatialImage as a list.
- Returns:
list of SpatialImage – List with all SpatialImages
- timagetk.components.multi_angle.TRSF_FNAME = '{}t{}_on_t{}-{}-{}.trsf'¶
Naming convention for transformation files.
MultiChannelImage class¶
Important
This is a work in progress!
MultiChannel images module.
- class timagetk.components.multi_channel.BlendImage(*images, **kwargs)[source]¶
RGB image class used to represent blended images like
MultiChannelImage
.- _extent¶
The physical extent of the image, sorted as (planes,) rows & columns [(Z,) Y, X].
- _origin¶
The coordinates of origin, sorted as (planes,) rows & columns [(Z,) Y, X].
- _voxelsize¶
The size of the pixels or voxels (2D/3D), sorted as (planes,) rows & columns [(Z,) Y, X].
- axes_order¶
Dictionary of axes orders, e.g. {‘x’: 2, ‘y’: 1, ‘z’: 0} by default for 3D image.
- Type:
- __array_finalize__(obj)[source]¶
Mechanism provided by numpy to allow subclasses instanciation.
- Parameters:
obj (object) – The object returned by the __new__ method.
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> type(blend_img) timagetk.components.multi_channel.BlendImage >>> # Taking the first z-slice automatically return a BlendImage instance: >>> blend_img2d = blend_img[3, :, :, :][0] >>> type(blend_img2d) timagetk.components.multi_channel.BlendImage
- static __new__(cls, *images, **kwargs)[source]¶
Blend image constructor.
YX sorted if images are 2D, ZYX sorted if images are 3D.
- Parameters:
images (numpy.ndarray or list of SpatialImage) – SpatialImages to blend. If a
numpy.ndarray
, last dimension should be of size 3 (RGB dim).axes_order (str) – The physical axes ordering to use with this array. Defaults to
default_axes_order(array)
.origin (list of int) – The coordinate of the origin for this array. Defaults to
default_origin(array)
.unit (float) – The units associated to the voxel-sizes to use with this array. Defaults to
DEFAULT_SIZE_UNIT
.voxelsize (list of float) – The voxel-sizes to use with this array. Defaults to
default_voxelsize(array)
.metadata (dict) – The dictionary of metadata to use with this array. Defaults to
{}
.colors (list of str) – List of color names to apply to each image, they can be one of the 140 standard HTML colors or an hexadecimal value like ‘#ff0000’ for ‘red’.
rtype ({'uint8', 'uint16', 'float64'}) – Type of RGB array to return, set to the type of the first image on the list by default.
See also
timagetk.visu.util.DEF_CHANNEL_COLORS
,timagetk.visu.util.combine_channels
Examples
>>> from timagetk.components.multi_channel import BlendImage >>> # Example 1 - Initialize with some random 3D RGB array: >>> from timagetk.array_util import random_array >>> rand_image = random_array([7, 15, 15, 3], dtype='uint8') >>> rand_image.shape (7, 15, 15, 3) >>> blend_img = BlendImage(rand_image, axes_order='ZYXB') >>> blend_img.shape (7, 15, 15, 3) >>> blend_img.axes_order 'ZYXB' >>> blend_img.voxelsize # Unspecified, so set to default value [1.0, 1.0, 1.0] >>> # Example 2 - Initialize with some random SpatialImages >>> from timagetk.array_util import random_spatial_image >>> imgA = random_spatial_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> imgB = random_spatial_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> blend_img = BlendImage(imgA, imgB) >>> blend_img.shape # the last dimension is of size 3, for RGB (5, 10, 10, 3) >>> blend_img.dtype dtype('uint8') >>> # Example 3 - Initialize from an RGB numpy.ndarray slice >>> import numpy as np >>> rgb_arr2d = np.array(blend_img[3, :, :, :]) >>> type(rgb_arr2d) numpy.ndarray >>> blend_img2d = BlendImage(rgb_arr2d, voxelsize=blend_img.voxelsize[1:]) >>> blend_img2d.voxelsize [0.5, 0.5]
- property axes_order¶
Get
BlendImage
physical axes ordering.- Returns:
str –
BlendImage
physical axes ordering.
Example
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> print(blend_img.axes_order) ZYX
- property axes_order_dict¶
Get
BlendImage
physical axes ordering.- Returns:
dict –
BlendImage
physical axes ordering.
Example
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> print(blend_img.axes_order_dict) {'Z': 0, 'Y': 1, 'X': 2}
- property extent¶
Get
BlendImage
physical extent.- Returns:
list –
BlendImage
physical extent.
Notes
It is related to the array shape and image voxelsize.
Example
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> print(blend_img.extent) [3.0, 2.5, 2.5]
- get_array(dtype=None)[source]¶
Return a copy of the image as a
numpy.ndarray
object.- Parameters:
dtype (str or numpy.dtype, optional) – If specified, default is
None
, change the dtype of the returned array.- Returns:
numpy.ndarray – Numpy array linked to the object (Z)YX sorted.
Notes
Changing the dtype of the array force the return of a copy.
- get_dtype()[source]¶
Get the human-readable image type.
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> blend_img.get_dtype() 'uint8'
- get_extent(axis=None)[source]¶
Return the get_extent of the given axis.
- Parameters:
axis (str, in {'x', 'y', 'z'}) – Axis for which the get_extent should be returned.
- Returns:
list of float or float – The get_extent of the axis.
Notes
It is related to the array shape and image voxelsize.
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> blend_img.get_extent() [4. , 4.5, 4.5] >>> blend_img.get_extent('x') 4.5 >>> blend_img.get_extent('y') 4.5 >>> blend_img.get_extent('z') 4.0
- get_shape(axis=None)[source]¶
Return the shape of the image or of an axis.
- Parameters:
axis (str in {'x', 'y', 'z'}, optional) – If specified, axis to use for shape dimension, else the shape of the image
- Returns:
list or int – The shape of the array or an integer if an axis is specified.
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> blend_img.get_shape() [3, 5, 5] >>> blend_img.get_shape('z') 5 >>> blend_img.get_shape('x') 10
- get_slice(slice_id, axis='z')[source]¶
Return a
BlendImage
with only one slice for given axis.- Parameters:
- Returns:
BlendImage – 2D BlendImage with only the required slice.
- Raises:
ValueError – If the image is not 3D and
axis='z'
. Ifslice_id
does not exist, i.e. should satisfy:0 < slice_id < max(len(axis))
.
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> blend_img.axes_order_dict {'Z': 0, 'Y': 1, 'X': 2, 'B': 3} >>> blend_img.get_shape() [5, 10, 10] >>> # Taking an existing z-slice from a 3D image works fine: >>> blend_img_z = blend_img.get_slice(1, 'z') >>> blend_img_z.axes_order_dict {'Y': 0, 'X': 1, 'B': 2} >>> blend_img_z.shape (10, 10, 3) >>> blend_img_z.get_shape() [10, 10] >>> # Taking an existing x-slice from a 3D image works fine: >>> blend_img_x = blend_img.get_slice(3, 'x') >>> blend_img_x.get_shape() [5, 10] >>> # Down-sampling x-axis of a 3D image: >>> nx = blend_img.get_shape('x') >>> img_ds_x2 = blend_img.get_slice(range(0, nx, 2), 'x') >>> img_ds_x2.get_shape() [5, 10, 5] >>> # Taking an NON-existing z-slice from a 3D image raises an error: >>> blend_img.get_slice(50, 'z') ValueError: Required z-slice (50) does not exists (max: 5) >>> # Taking a z-slice from a 2D image raises an error: >>> blend_img_z.get_slice(5, 'z')
- get_voxelsize(axis=None)[source]¶
Return the voxelsize of the image or of an axis.
- Parameters:
axis ({'x', 'y', 'z'}, optional) – If specified, axis to use for voxel-size, else the voxel-size of the image.
- Returns:
list or float – The voxel-size of the image or of the axis (if specified).
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> blend_img.get_voxelsize() [1. , 0.5, 0.5] >>> blend_img.get_voxelsize('z') 1.0
- is2D()[source]¶
Return True if the BlendImage is 2D, else
False
.Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> blend_img.is2D() False >>> # Take the first z-slice: >>> blend_img2d = blend_img.get_slice(0, 'z') # Equivalent to img[0] >>> blend_img2d.is2D() True
- is3D()[source]¶
Return True if the BlendImage is 3D, else
False
.Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> blend_img.is3D() True
- is_isometric()[source]¶
Test image isometry.
Tests if the voxelsize values are the same for every axis or not.
- Returns:
is_iso (bool) – True if the image is isometric, else
False
.
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5],dtype='uint8') >>> blend_img.is_isometric() False >>> blend_img.voxelsize = [1., 1., 1.] >>> blend_img.is_isometric() True
- property origin¶
Get
BlendImage
origin.- Returns:
list –
BlendImage
origin coordinates
Example
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5],dtype='uint8') >>> print(blend_img.origin) [0, 0, 0]
- transpose(*axes)[source]¶
Permute image axes to given order, reverse by default.
- Parameters:
axes (list of int or list of str, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.
- Returns:
BlendImage – The image with permuted axes.
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 6, 7), voxelsize=[1., 0.51, 0.52], dtype='uint8') >>> blend_img.axes_order 'ZYXB' >>> blend_img_t = blend_img.transpose() >>> blend_img_t.axes_order 'XYZB' >>> # Transpose update the shape attribute of the image (here reversed): >>> print(img_t.get_shape()) [7, 6, 5] >>> # Transpose update the voxelsize attribute of the image (here reversed): >>> print(img_t.get_voxelsize()) [0.52, 0.51, 1.0]
>>> # -- Transpose accept axe names as input: >>> blend_img_t = blend_img.transpose('xzy') # transpose ZYXB to XZYB >>> blend_img_t.axes_order 'XZYB' >>> print(img_t.get_shape()) [7, 6, 5] >>> img_t = blend_img.transpose('x', 'y', 'z') # transpose ZYXB to XYZB >>> print(img_t.shape) [7, 6, 5]
- property unit¶
Return the unit in International System of Units (SI).
- Returns:
float – The unit in International System of Units (SI).
- property voxelsize¶
Get
BlendImage
voxelsize, sorted as planes, columns & rows.- Returns:
list –
BlendImage
voxelsize
Example
>>> from timagetk.components.multi_channel import random_blend_image >>> # Initialize a random (uint8) 3D BlendImage: >>> blend_img = random_blend_image((5, 10, 10), voxelsize=[1., 0.5, 0.5],dtype='uint8') >>> print(blend_img.voxelsize) [1., 0.5, 0.5]
- class timagetk.components.multi_channel.MultiChannelImage(image, channel_names=None, metadata=None, **kwargs)[source]¶
Multichannel image data structure.
- extent¶
The physical extent of the image, sorted as (planes,) rows & columns [(Z,) Y, X].
- origin¶
The coordinates of origin, sorted as (planes,) rows & columns [(Z,) Y, X].
- voxelsize¶
The size of the pixels or voxels (2D/3D), sorted as (planes,) rows & columns [(Z,) Y, X].
Notes
TODO: Add a
metric_unit
attribute and associated methods to handle this!Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_url = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> # IO example #1 - `imread` method can read CZI and return a MultiChannelImage: >>> im = imread(im_url, channel_names=ch_names) >>> im.channel_names >>> isinstance(im, MultiChannelImage) True >>> from timagetk.visu.stack import orthogonal_view >>> orthogonal_view(im.to_blend_image())
>>> # IO example #2 - MultiChannelImage can be instantiated from a filename: >>> im = MultiChannelImage(im_url, channel_names=ch_names, czi_pattern='.C.ZXY') >>> print(im) >>> # Access the channels as you would with a dictionary: >>> print(im["DII-VENUS-N7"]) SpatialImage object with following metadata: - shape: (65, 1024, 1024) - ndim: 3 - dtype: uint16 - origin: [0, 0, 0] - voxelsize: (6.771450737227882e-07, 2.075664593629475e-07, 2.075664593629475e-07) - extent: [4.4014429791981236e-05, 0.00021254805438765823, 0.00021254805438765823] >>> # Access the channels using the `get_channel` method: >>> ahp6_img = im.get_channel("AHP6")
>>> # Get the name of the multichannel image: >>> print(im.name) qDII-CLV3-PIN1-PI-E35-LD-SAM4 >>> # Add or change the name of the multichannel image: >>> im.set_name("my_experiment1_rep2") >>> print(im.name) my_experiment1_rep2
>>> from timagetk.visu.stack import channels_stack_browser >>> channels_stack_browser(im, im.name)
- __init__(image, channel_names=None, metadata=None, **kwargs)[source]¶
Constructor.
- Parameters:
image (str or list of str or list of SpatialImage or dict) – If an str, should be a multichannel image file name. If a list of str, should be a list of single channel file names. Lists of SpatialImage are also accepted, they should be of same shape. If a
dict
, keys are used aschannel_names
and values should beSpatialImage
.channel_names (list of str, optional) – List of names to use as channel names.
metadata (dict, optional) – Dictionary of image metadata. An empty dictionary by default.
name (str) – Name of the multichannel image.
czi_pattern (str) – Pattern used to read the CZI file,
".C.ZXY."
by default.filepath (str) – The directory where to find the image, if any.
filename (str) – The file name of the image.
- get_array(return_order=None)[source]¶
Return a NumPy array.
- Parameters:
return_order (str, optional) – Order of the dimension for returned array, same as the
axes_order
attribute by default.- Returns:
numpy.ndarray – The array that correspond to the requested axes ordering.
Examples
>>> # Example #1: Use a dummy multichannel image: >>> from timagetk.array_util import dummy_multichannel_image >>> img = dummy_multichannel_image() >>> print(img.axes_order) >>> arr = img.get_array() >>> print(arr.shape) # same as the ``axes_order`` attribute (5, 11, 11, 2) >>> arr = img.get_array("CXYZ") # specify the axes return order >>> print(arr.shape) (2, 11, 11, 5)
>>> # Example #2: Use a real multichannel image (downloaded from Zenodo.org): >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> img = imread(im_fname, channel_names=ch_names) >>> arr = img.get_array() >>> print(arr.shape) (40, 1024, 1024, 4) >>> arr = img.get_array("CXYZ") >>> print(arr.shape) (4, 1024, 1024, 40)
- get_channel(channel_name)[source]¶
Return the intensity image for given channel.
- Parameters:
channel_name (str) – Name of the channel to returns.
- Returns:
SpatialImage – The intensity image for given channel.
Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> im = imread(im_fname, channel_names=ch_names) >>> # Access the channels as you would with a dictionary: >>> print(im["CLV3"]) SpatialImage object with following metadata: - shape: (1024, 1024, 40) - ndim: 3 - dtype: uint16 - origin: [0, 0, 0] - voxelsize: [0.208, 0.208, 1.171] - extent: [212.992, 212.992, 46.84] >>> # Access the channels using the `get_channel` method: >>> ahp6_img = im.get_channel("AHP6") >>> print(ahp6_img) SpatialImage object with following metadata: - shape: (1024, 1024, 40) - ndim: 3 - dtype: uint16 - origin: [0, 0, 0] - voxelsize: [0.208, 0.208, 1.171] - extent: [212.992, 212.992, 46.84]
- get_channel_names()[source]¶
Return the list of channel names.
- Returns:
list – The list of channel names.
Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ["qDII", "AHP6", "tagBFP", "CLV3"] >>> img = imread(im_fname, channel_names=ch_names) >>> img.get_channel_names() ['qDII', 'AHP6', 'tagBFP', 'CLV3']
- get_extent(axis=None)[source]¶
Return the get_extent of the given axis.
- Parameters:
axis (str, in {'x', 'y', 'z'}) – Axis for which the get_extent should be returned.
- Returns:
list of float or float – The get_extent of the axis.
Notes
It is related to the array shape and image voxelsize.
Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ["qDII", "AHP6", "tagBFP", "CLV3"] >>> img = imread(im_fname, channel_names=ch_names) >>> img.get_extent() [43.337284718258445, 212.3404879282953, 212.3404879282953] >>> img.get_extent('x') 212.3404879282953
- get_shape(axis=None)[source]¶
Return the shape of the image or of an axis.
- Parameters:
axis (str in {'x', 'y', 'z', 'c'}, optional) – If specified, axis to use for shape dimension, else the shape of the image
- Returns:
list or int – The shape of the array or an integer if an axis is specified.
Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ["qDII", "AHP6", "tagBFP", "CLV3"] >>> img = imread(im_fname, channel_names=ch_names) >>> img.get_shape() [65, 1024, 1024, 4] >>> img.get_shape('z') 65 >>> img.get_shape('c') 4
- get_slice(slice_id, axis='z')[source]¶
Return a MultiChannelImage with only one slice for given axis.
- Parameters:
- Returns:
MultiChannelImage – 2D MultiChannelImage with only the required slice
- Raises:
ValueError – If the image is not 3D and
axis='z'
. Ifslice_id
does not exist, i.e. should satisfy:0 < slice_id < max(len(axis))
.
Examples
>>> # Example #1: Use a dummy multichannel image: >>> from timagetk.array_util import dummy_multichannel_image >>> img = dummy_multichannel_image() >>> img_z = img.get_slice(1, 'z') >>> print(img_z.shape) (11, 11) >>> print(img_z.axes_order_dict) {'Y': 0, 'X': 1, 'C': 2} >>> # Taking an existing x-slice from a 3D image works fine: >>> img_x = img.get_slice(3, 'x') >>> print(img_x.axes_order_dict) {'Z': 0, 'Y': 1, 'C': 2}
>>> # Example #2: Use a real multichannel image (downloaded from Zenodo.org): >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ["qDII", "AHP6", "tagBFP", "CLV3"] >>> img = imread(im_fname, channel_names=ch_names) >>> # Taking an existing z-slice from a 3D image works fine: >>> img_z = img.get_slice(1, 'z') >>> img_z.is2D() True >>> img_z.is3D() False >>> # Taking an existing x-slice from a 3D image works fine: >>> img_x = img.get_slice(3, 'x') >>> print(img_x.axes_order_dict) {'Z': 0, 'Y': 1, 'C': 2} >>> # Down sampling x-axis of a 3D image: >>> img_ds_x2 = img.get_slice(range(0, img.get_shape('x'), 2), 'x') >>> img_ds_x2.is3D() True >>> print(img.get_shape('x')) 1024 >>> print(img_ds_x2.get_shape('x')) 512 >>> print(img.voxelsize) [1.1712524251243286e-06, 2.075664593629475e-07, 2.075664593629475e-07] >>> print(img_ds_x2.voxelsize) [1.1712524251243286e-06, 2.075664593629475e-07, 4.15132918725895e-07]
>>> # Taking an NON-existing z-slice from a 3D image raises an error: >>> img.get_slice(50, 'z')
>>> # Taking a z-slice from a 2D image raises an error: >>> img_z.get_slice(5, 'z')
- get_voxelsize(axis=None)[source]¶
Return the voxelsize of the image or of an axis.
- Parameters:
axis ({'x', 'y', 'z'}, optional) – If specified, axis to use for voxel-size, else the voxel-size of the image.
- Returns:
list or float – The voxel-size of the image or of the axis (if specified).
Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ["qDII", "AHP6", "tagBFP", "CLV3"] >>> img = imread(im_fname, channel_names=ch_names) >>> img.get_voxelsize() [0.6771450737227882, 0.2075664593629475, 0.2075664593629475] >>> img.get_voxelsize('z') 0.6771450737227882
- invert_axis(axis)[source]¶
Revert given axis for all channels.
- Parameters:
axis (str in {'x', 'y', 'z'}) – Axis to invert, can be either ‘x’, ‘y’ or ‘z’ (if 3D)
- Returns:
MultiChannelImage – Image with reverted array for selected axis.
- Raises:
ValueError – If given axis is not in {‘x’, ‘y’, ‘z’} for 3D images or not in {‘x’, ‘y’} for 2D images.
Example
>>> from timagetk.array_util import random_spatial_image >>> from timagetk import MultiChannelImage >>> # Initialize a random (uint8) 3D SpatialImage with one z-slice: >>> img_a = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> img_b = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5], dtype='uint8') >>> img = MultiChannelImage([img_a, img_b]) >>> img.get_channel_names() ['CH_0', 'CH_1'] >>> print(img_a.get_array()) >>> img.invert_axis('z') >>> print(img['CH_0'].get_array())
- is2D()[source]¶
Return True if the SpatialImage is 2D, else
False
.Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> img = imread(im_fname, channel_names=ch_names) >>> img.is2D() False >>> # Take the first z-slice: >>> img2d = img.get_slice(0, 'z') # Equivalent to img[0] >>> img2d.is2D() True
- is3D()[source]¶
Return True if the SpatialImage is 3D, else
False
.Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> img = imread(im_fname, channel_names=ch_names) >>> img.is3D() True
- is_isometric()[source]¶
Test image isometry.
Tests if the voxelsize values are the same for every axis or not.
- Returns:
is_iso (bool) – True if the image is isometric, else
False
.
Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> img = imread(im_fname, channel_names=ch_names) >>> img.is_isometric() False
- property metadata¶
Get
MultiChannelImage
metadata dictionary.- Returns:
dict – Metadata dictionary.
- to_blend_image(**kwargs)[source]¶
Return an RGB BlendImage object used for plotting.
- Parameters:
- Returns:
BlendImage – The RGB image resulting in the blending of channels.
Examples
>>> from timagetk.io.image import imread >>> # We use a freely available multichannel image from an online database >>> url = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> ch_colors = ['yellow', 'green', 'red', 'blue', 'purple'] >>> mch_img = imread(url, channel_names=ch_names)
>>> rgb_img = mch_img.to_blend_image(colors=ch_colors, rtype='uint8') >>> from timagetk.visu.stack import orthogonal_view >>> orthogonal_view(rgb_img)
- transpose(*axes)[source]¶
Permute image axes to given order, reverse by default.
- Parameters:
axes (list of int or list of str, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.
- Returns:
SpatialImage – The image with permuted axes.
Examples
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imread >>> im_fname = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> ch_names = ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> img = imread(im_fname, channel_names=ch_names) >>> print(img.shape) (5, 4, 3) >>> img_t = img.transpose() >>> # Transpose update the shape attribute of the image (here reversed): >>> print(img_t.shape) (5, 4, 3) >>> # Transpose update the voxelsize attribute of the image (here reversed): >>> print(img_t.voxelsize) [0.53, 0.52, 0.51] >>> # Transpose update the metadata dictionary of the image: >>> print(img_t.metadata)
>>> # -- Transpose accept axe names as input: >>> img_t = img.transpose('xyz') >>> print(img_t.shape) (5, 4, 3) >>> img_t = img.transpose('x', 'y', 'z') >>> print(img_t.shape) (5, 4, 3)
- timagetk.components.multi_channel.check_image_axes_order(image)[source]¶
Check that all images have the same
axes_order
attribute.- Parameters:
image (dict of SpatialImage) – A dictionary of SpatialImage.
- Raises:
ValueError – If not all images have the same
axes_order
attribute.
- timagetk.components.multi_channel.check_image_shape(image)[source]¶
Check that all images have the same shape.
- Parameters:
image (dict of timagetk.SpatialImage) – A dictionary of
SpatialImage
.- Raises:
ValueError – If not all images are of same shape.
- timagetk.components.multi_channel.check_image_voxelsize(image, rtol=1e-05)[source]¶
Check that all images have the same voxel size.
- Parameters:
image (dict of SpatialImage) – A dictionary of SpatialImage.
rtol (float, optional) – The relative tolerance parameter, i.e. the maximum relative difference allowed.
- Raises:
ValueError – If not all images are of same voxel size.
- timagetk.components.multi_channel.check_images_channels(image, channel_names)[source]¶
Check that there is the same number of images and channel names.
- timagetk.components.multi_channel.chnames_generator(n_imgs)[source]¶
Generate channel names as CH_i with i in range(n_imgs).
- Parameters:
n_imgs (int) – Number of images or channels to generate names for.
Examples
>>> from timagetk.components.multi_channel import chnames_generator >>> chnames_generator(5) ['CH_0', 'CH_1', 'CH_2', 'CH_3', 'CH_4']
- timagetk.components.multi_channel.combine_channels(images, colors=None, rtype='uint8', **kwargs)[source]¶
Return an RGB image combining the given channels after RGB coloring.
Example of available
colors
are: ‘red’, ‘green’, ‘blue’, ‘yellow’, ‘cyan’, ‘magenta’.- Parameters:
images (list(array), shape (M[, N][, P])) – List of grayscale images to blend
colors (list of str, optional) – List of color names to apply to each image, they can be one of the 140 standard HTML colors or an hexadecimal value like ‘#ff0000’ for ‘red’.
rtype (str in {'uint8', 'uint16', 'float64'}) – Type of array to return, ‘uint8’ by default.
- Returns:
BlendImage – An RGB array obtained by combining each image with their assigned
colors
, of shape (M[, N][, P], 3).
See also
timagetk.visu.util.DEF_CHANNEL_COLORS
,timagetk.visu.util.color_code
Notes
Beware that channels with co-localized signals will lead to “new color” by combination, e.g. by combinations of red and green, yellow will appear. Matplotlib method
imshow
acceptfloat
oruint8
data types for RGB images. In this method we use afloat64
array to combine the images. Since this method is mostly used for image representation, it is converted back touint8
in order to save some memory.Examples
>>> from timagetk.synthetic_data.wall_image import example_layered_sphere_wall_image >>> from timagetk.synthetic_data.nuclei_image import nuclei_image_from_point_positions >>> from timagetk.components.multi_channel import combine_channels >>> from timagetk.visu.mplt import grayscale_imshow >>> from timagetk.visu.stack import orthogonal_view >>> # EXAMPLE - Synthetic wall (green) & nuclei (red) image >>> kwargs = {"extent": 50., "voxelsize": (0.5, 0.25, 0.25), "dtype": 'uint8'} >>> wall_img, pts = example_layered_sphere_wall_image(return_points=True, wall_intensity=250, **kwargs) >>> nuclei_img = nuclei_image_from_point_positions(pts, nuclei_intensity=250., **kwargs) >>> blend = combine_channels([nuclei_img, wall_img]) >>> blend.get_dtype() 'uint8' >>> # Get the middle z-slice and plot it: >>> z_sh = blend.get_shape('z') >>> z_sl = z_sh // 2 >>> grayscale_imshow(blend.get_slice(50), title=f"z-slice{z_sl}/{z_sh}") >>> # Show an orthogonal view: >>> orthogonal_view(blend, suptitle="Synthetic wall (green) & nuclei (red) image")
- timagetk.components.multi_channel.label_blending(label, image, colors=None, alpha=0.3, bg_label=1, bg_color=(0, 0, 0))[source]¶
Return an RGB image where color-coded labels are painted over the image.
This is a shorter version of ‘skimage.color’ module ‘label2rgb’ function.
- Parameters:
label (numpy.ndarray, shape (M, N [, P])) – Integer array of labels with the same shape as image.
image (numpy.ndarray, shape (M, N [, P])) – Image used as underlay for labels.
colors (list, optional) – List of colors. If the number of labels exceeds the number of colors, then the colors are cycled.
alpha (float [0, 1], optional) – Opacity of colorized labels. Ignored if image is
None
.bg_label (int, optional) – Label that’s treated as the background.
bg_color (str or array, optional) – Background color. Must be a name in color_dict or RGB float values between [0, 1].
- Returns:
BlendImage – The result of blending a cycling colormap (colors) for each distinct value in label with the image, at a certain alpha value. An array of float of shape (M, N, 3)
Notes
Compared to the label2rgb function of
skimage
, we set the image_alpha to 1 - alpha.Examples
>>> from timagetk import LabelledImage >>> from timagetk.components.multi_channel import label_blending >>> from timagetk.io import imread >>> from timagetk.io.util import shared_dataset >>> from timagetk.visu.stack import rgb_stack_browser >>> from timagetk.visu.stack import stack_panel >>> int_path = shared_dataset("sphere", 'intensity')[0] >>> seg_path = shared_dataset("sphere", 'segmented')[0] >>> int_img = imread(int_path) >>> seg_img = LabelledImage(imread(seg_path), not_a_label=0) >>> blend = label_blending(seg_img, int_img) >>> rgb_stack_browser(blend, "Intensity & segmentation blending", val_range=[None, None]) >>> stack_panel(blend, step=10, suptitle="Intensity & segmentation blending", val_range=[None, None])
- timagetk.components.multi_channel.random_blend_image(size, n_spimg=2, **kwargs)[source]¶
Generate a random
BlendImage
fromSpatialImage
.- Parameters:
size (iterable) – Shape of the image to generate. ZYX sorted if 3D else YX sorted.
n_spimg (int, optional) – Number of random SpatialImage to generate to create
origin (list) – Coordinates of the origin in the image, default: [0, 0] or [0, 0, 0]
voxelsize (list) – Image voxelsize, default: [1.0, 1.0] or [1.0, 1.0, 1.0]
dtype (str or numpy.dtype) – If specified, default is
np.float32
, change the dtype of the returned image.
- Returns:
BlendImage – A random blend image from a list of random spatial images.
See also
timagetk.components.spatial_image.random_spatial_image
Examples
>>> from timagetk.components.multi_channel import random_blend_image >>> # Example 1 - Generates a BlendImage using 3D SpatialImages: >>> blend_img = random_blend_image([5, 10, 10], voxelsize=[1., 0.5, 0.5]) >>> type(blend_img) timagetk.components.multi_channel.BlendImage >>> blend_img.shape # the last dimension is of size 3, for RGB (5, 10, 10, 3) >>> blend_img.axes_order # the last dimension is RGB 'ZYXB' >>> blend_img.is3D() True
>>> # Example 2 - Generates a BlendImage using 2D SpatialImages: >>> blend_img = random_blend_image([10, 10], voxelsize=[0.5, 0.5]) >>> blend_img.shape # the last dimension is of size 3, for RGB (10, 10, 3) >>> blend_img.is2D() True
TimeSeries class¶
Important
This is a work in progress!
This module implement a class dedicated to time series analysis.
Since they can be made of a great number of images, and that these can be too big to save them all in memory we use disk file access instead of loading everything in memory.
- class timagetk.components.time_series.TimeSeries(list_img, time_points, list_lineages=None, time_unit='h', name='', **kwargs)[source]¶
Implementation of a time series as a temporal succession of SpatialImages.
- TODO:
use saved ‘acquisition_time’ to compute time intervals between successive images
- __init__(list_img, time_points, list_lineages=None, time_unit='h', name='', **kwargs)[source]¶
TimeSeries constructor.
- Parameters:
list_img (list of str or list of timagetk.components.spatial_image.SpatialImage) – List of images to use
time_points (list of int) – Acquisition time steps, starting from t0 = 0, e.g. [0, 5, 10] for acquisitions every 5h.
list_lineages (list(Lineage), optional) – If you already have cell lineages, provide them here
time_unit (str, optional) – Indicate the time unit of the time-points, e.g.
'h'
for hours (default),'m'
for minutes, ect.name (str, optional) – Name to give to this TimeSeries
ext (str) – Extension to use to save images, default is
DEF_IMG_EXT
Notes
If a list of
SpatialImage
is given as input, we use the filename and filepath attributes and discard the rest of the object.Examples
>>> from timagetk.components.time_series import TimeSeries >>> from timagetk.io.util import shared_data >>> # Using shared data as example, images where taken every 12 hours: >>> fname = 'p58-t{}_INT_down_interp_2x.inr.gz' >>> list_img = [shared_data(fname.format(t), "p58") for t in range(3)] >>> ts = TimeSeries(list_img, [0, 12, 24], name="p58")
>>> from timagetk.io.image import imread >>> list_img = [imread(img) for img in list_img] >>> ts = TimeSeries(list_img, [0, 12, 24], name="p58")
- __weakref__¶
list of weak references to the object (if defined)
- get_registered_image(method, t_float, t_ref)[source]¶
Return an image instance for given transformation index and method.
- Parameters:
- Returns:
SpatialImage – Corresponding image object
Examples
>>> from timagetk.components.time_series import TimeSeries >>> from timagetk.io.util import shared_data >>> # Using shared data as example, images where taken every 12 hours: >>> fname = 'p58-t{}_INT_down_interp_2x.inr.gz' >>> list_img = [shared_data(fname.format(t), "p58") for t in range(3)] >>> ts = TimeSeries(list_img, [0, 12, 24], name="p58") >>> # - Register the first image on the last one and return it: >>> ts.get_registered_image('rigid', 0, 2)
TissueImage class¶
Important
This is a work in progress!
Biology oriented class to represent cell segmented tissue image.
As opposed to nuclei images, these images are labelled at the cell level and thus have topological information.
- class timagetk.components.tissue_image.AbstractTissueImage(image, **kwargs)[source]¶
Biology oriented class to manipulate dense tissues made of cells and potentially a background.
- _epidermal_cells¶
The list of ids referring to epidermal cells, i.e. those in contact with the background.
- _voxel_layer1¶
The array made of the first layer of voxels in contact with the background.
- Type:
- __init__(image, background=None, **kwargs)[source]¶
Abstract tissue image initialisation method.
- Parameters:
image (numpy.ndarray or timagetk.SpatialImage or timagetk.LabelledImage) – A labelled array defining a dense multicellular tissue.
background (int, optional) – If given, define the id of the background, that is the “space” surrounding the tissue.
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 = image.dtype
metadata (dict, optional) – Dictionary of image metadata, default is an empty dict
not_a_label (int, optional) – If specified, it defines the “unknown label” (i.e. a value that is not a label)
- static __new__(cls, image, **kwargs)[source]¶
Abstract tissue image construction method.
- Parameters:
image (numpy.ndarray or timagetk.components.spatial_image.SpatialImage or timagetk.components.labelled_image.LabelledImage) – A dense tissue image, i.e. a cell-based segmented array with connected labels.
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 = image.dtype
metadata (dict, optional) – Dictionary of image metadata, default is an empty dict
not_a_label (int, optional) – If given, define the “unknown label” i.e. the value that does not refers to a label
Example
>>> import numpy as np >>> from timagetk import SpatialImage >>> from timagetk import LabelledImage >>> from timagetk.components.tissue_image import AbstractTissueImage >>> 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 = AbstractTissueImage(test_array, voxelsize=[0.5, 0.5], not_a_label=0, background=1) >>> print(tissue) >>> # - Construct from a SpatialImage: >>> image = SpatialImage(test_array, voxelsize=[0.5, 0.5]) >>> tissue = AbstractTissueImage(image, not_a_label=0, background=1) >>> print(tissue) >>> # - Construct from a LabelledImage: >>> lab_image = LabelledImage(test_array, voxelsize=[0.5, 0.5], not_a_label=0) >>> tissue = AbstractTissueImage(lab_image, background=1) >>> print(tissue)
- property background¶
Get the background label, can be
None
.- Returns:
int – The label value for the background
- cell_ids(cells=None)[source]¶
Get the list of cells found in the image, or filter given list of cell ids with those that exists.
- Parameters:
cells (int or list, optional) – If given, used to filter the returned list of ids. By default, return all cell ids defined in the tissue.
- Returns:
list – List of cells found in the image, except for background (if defined)
Notes
Value defined for background is removed from the returned list of cells as 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.tissue_image import AbstractTissueImage >>> im = AbstractTissueImage(a, background=1) >>> im.labels() [1, 2, 3, 4, 5, 6, 7] >>> im.cell_ids() [2, 3, 4, 5, 6, 7]
- epidermal_cell_ids()[source]¶
List epidermal cell, i.e cells in contact with the background.
- Returns:
list – List of epidermal cell, also knwon as L1-cells
Example
>>> from timagetk.io import imread >>> from timagetk.io.util import shared_data >>> from timagetk.components.tissue_image import AbstractTissueImage >>> tissue = AbstractTissueImage(imread(shared_data('sphere_membrane_0.0_seg.inr.gz', "sphere")), background=1, not_a_label=0) >>> tissue.epidermal_cell_ids()
- fuse_cells_in_image(cells, value='min')[source]¶
Fuse the provided list of cells to its minimal value.
- get_image_with_cells(cells, keep_background=True, erase_value=None)[source]¶
Return an AbstractTissueImage with only the selected cells, the rest are replaced by “self._not_a_label”.
- Parameters:
- Returns:
AbstractTissueImage – Tissue image with the selected cells.
- get_image_without_cells(cells, keep_background=True)[source]¶
Return a tissue image without the selected cells.
- nb_cells()[source]¶
Return the number of cells found in the image.
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.tissue_image import AbstractTissueImage >>> im = AbstractTissueImage(a, background=None) >>> im.nb_cells() 7 >>> im = AbstractTissueImage(a, background=1) >>> im.nb_cells() 6
- relabelling_cells_from_mapping(mapping, clear_unmapped=False)[source]¶
Relabel the image following a given mapping indicating the original cell id as keys and their new id as value.
- Parameters:
- Returns:
Nothing, modify the LabelledImage array (re-instantiate the object)
- voxel_first_layer(connectivity, keep_background=True)[source]¶
Extract the first layer of non-background voxels in contact with the background as a TissueImage.
- Parameters:
- Returns:
TissueImage – Labelled image made of the first layer of voxel in contact with the background
- voxel_first_layer_coordinates()[source]¶
Return an (Nxd) array of coordinates indicating voxels first layer position.
- voxel_n_first_layer(n_voxel_layer, connectivity, keep_background=True)[source]¶
Extract the n-first layer of non-background voxels in contact with the background as a TissueImage.
- Parameters:
- Returns:
TissueImage – Labelled image made of the selected number of voxel layers
- wall_ids(walls=None)[source]¶
Get the list of cell-walls found in the image, or filter given list of cell-wall ids with those that exists.
- Parameters:
walls (tuple of int or list of tuple of int, optional) – If given, used to filter the returned list of ids. By default, return all wall ids defined in the tissue.
- Returns:
list of tuples – List of cell-walls found in the image, returned as tuples of cell ids defining them.
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.tissue_image import AbstractTissueImage >>> im = AbstractTissueImage(a, background=1) >>> im.wall_ids() [(1, 2), (3, 7), (1, 3), (5, 7)]
- class timagetk.components.tissue_image.TissueImage2D(image, **kwargs)[source]¶
Class specific to 2D dense multicellular tissues.
- __init__(image, background=None, **kwargs)[source]¶
2D dense multicellular tissue constructor.
- Parameters:
image (numpy.ndarray or timagetk.SpatialImage or timagetk.LabelledImage) – A 2D labelled array defining a dense multicellular tissue.
background (int, optional) – If given, define the id of the background, that is the “space” surrounding the tissue.
- epidermal_cell_ids(min_length=None)[source]¶
List epidermal cell, i.e cells in contact with the background.
- Parameters:
min_area (float, optional) – The minimum real contact length with the background necessary to be defined as epidermal cell. No minimum by default.
TODO (It is possible to provide an epidermal length threshold (minimum length in contact with the background) to consider a cell as in the first layer.)
- Returns:
list – List of epidermal cell, also knwon as L1-cells
Example
>>> from timagetk.io import imread >>> from timagetk.io.util import shared_data >>> from timagetk import TissueImage3D >>> tissue = imread(shared_data('sphere_membrane_0.0_seg.inr.gz', "sphere"), TissueImage3D, background=1, not_a_label=0) >>> tissue.epidermal_cell_ids()
- get_region(region)[source]¶
Extract a region using list of start & stop indices.
There should be two values per image dimension in ‘indices’.
- Parameters:
region (list) – Indices as list of integers.
- Returns:
TissueImage2D – Output image.
- Raises:
TypeError – If the given region is not a list.
ValueError – If the number of region is wrong, should be twice the image dimensionality. If the region coordinates are not within the image boundaries.
Example
>>> from timagetk import TissueImage2D >>> from timagetk.array_util import dummy_labelled_image_2D >>> img = TissueImage2D(dummy_labelled_image_2D([0.5, 0.5]), background=1) >>> region = [1, 5, 1, 5] >>> out_img = img.get_region(region) >>> isinstance(out_img, TissueImage2D) True >>> out_img TissueImage2D([[2, 4, 4, 4], [2, 2, 4, 4], [2, 2, 2, 4], [2, 2, 2, 3]], dtype=uint8)
- voxel_first_layer(connectivity=4, keep_background=True, **kwargs)[source]¶
Extract the first layer of non-background voxels in contact with the background.
- Parameters:
- Returns:
TissueImage2D – Image made of the first layer of voxel in contact with the background
- class timagetk.components.tissue_image.TissueImage3D(image, **kwargs)[source]¶
Class specific to 3D dense multicellular tissues.
Examples
>>> from timagetk.io import imread >>> from timagetk.io.util import shared_dataset >>> from timagetk import TissueImage3D >>> tissue = TissueImage3D(imread(shared_dataset("p58", "intensity")[0]), background=1, not_a_label=0) >>> tissue.cell_ids() # Access the list of cells >>> tissue.nb_cells() # Access the number of cells >>> tissue.nb_labels() # Access the number of labels ( = `nb_cell` + 1 if background label is defined)
>>> tissue.cells.area() >>> tissue.cells.area(1001)
>>> tissue.walls.area() >>> tissue.walls.area((1001, 64)) >>> tissue.walls.area((64, 1001))
- __init__(image, background=None, **kwargs)[source]¶
3D dense multicellular tissue constructor.
- Parameters:
image (numpy.ndarray or timagetk.SpatialImage or timagetk.LabelledImage) – A 3D labelled array defining a dense multicellular tissue
background (int, optional) – If given, define the id of the background, that is the “space” surrounding the tissue.
- epidermal_cell_ids(min_area=None, real=True)[source]¶
List epidermal cell, i.e cells in contact with the background.
- Parameters:
- Returns:
list of int – List of epidermal cells, also known as L1-cells
Example
>>> from timagetk.io import imread >>> from timagetk.io.util import shared_dataset >>> from timagetk import TissueImage3D >>> tissue = TissueImage3D(imread(shared_dataset("p58", "intensity")[0]), background=1, not_a_label=0) >>> ep_cid = tissue.epidermal_cell_ids() >>> # Take a look at the cell wall areas to estimate realistic threshold area: >>> ep_wall_area = tissue.walls.area([(tissue.background, cid) for cid in ep_cid]) >>> from matplotlib import pyplot as plt >>> plt.hist(list(ep_wall_area.values()), bins=100, range=(0, 100)) >>> plt.show() >>> # Filter epidermal cell walls with a threshold area of 5µm²: >>> tissue.epidermal_cell_ids(5.)
- get_region(region)[source]¶
Extract a region using list of start & stop indexes.
There should be two values per dimension in region, e.g.
region=[5, 8, 5, 8]
for a 2D image. If the image is 3D and, in one dimension the start and stop indexes only differ by one (one layer of voxels), the returned image will be transformed to 2D!- Parameters:
region (list) – Indexes as list of integers, e.g. [y-start, y-stop, x-start, x-stop] for a 2D image.
- Returns:
TissueImage3D – Output image.
- Raises:
TypeError – If the given region is not a list.
ValueError – If the number of indexes in region is wrong, should be twice the image dimensionality. If the region coordinates are not within the array boundaries.
Example
>>> from timagetk import TissueImage3D >>> from timagetk.array_util import dummy_labelled_image_3D >>> # Initialize a dummy (uint8) TissueImage3D with a ZYX shape of 5x13x12: >>> img = TissueImage3D(dummy_labelled_image_3D([1.0, 0.5, 0.5]), background=1) >>> region = [0, 2, 1, 5, 1, 5] # z-start, z-stop, y-start, y-stop, x-start, x-stop >>> out_img = img.get_region(region) >>> isinstance(out_img, TissueImage3D) True >>> out_img TissueImage3D([[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[2, 4, 4, 4], [2, 2, 4, 4], [2, 2, 2, 4], [2, 2, 2, 3]]], dtype=uint8)
- get_slice(slice_id, axis='z')[source]¶
Return a slice of the tissue image.
- Parameters:
- Returns:
TissueImage2D – 2D tissue image with only the required slice.
- Raises:
ValueError – If the image is not 3D and
axis='z'
. Ifslice_id
does not exist, i.e. should satisfy:0 < slice_id < max(len(axis))
.
Examples
>>> from timagetk import TissueImage3D >>> from timagetk.array_util import dummy_labelled_image_3D >>> # Initialize a dummy (uint8) TissueImage3D with a ZYX shape of 5x13x12: >>> img = TissueImage3D(dummy_labelled_image_3D([1.0, 0.5, 0.5]), background=1) >>> print(img.background) 1 >>> zsl = img.get_slice(0) >>> print(type(zsl)) <class 'timagetk.components.tissue_image.TissueImage2D'> >>> print(zsl) TissueImage2D object with following attributes: - not_a_label: 0 - background: 1 - shape: (13, 12) - ndim: 2 - dtype: uint8 - origin: [0, 0] - voxelsize: [0.5, 0.5] - unit: 1e-06 - acquisition_date: None - extent: [6.0, 5.5] >>> # Taking an existing x-slice from a 3D image works fine: >>> img_x = img.get_slice(3, 'x') >>> print(img_x.axes_order_dict) {'Z': 0, 'Y': 1}
- invert_axis(axis)[source]¶
Revert given axis.
- Parameters:
axis ({'x', 'y', 'z'}) – Axis to invert, can be either ‘x’, ‘y’ or ‘z’ (if 3D).
- Returns:
LabelledImage – Image with reverted array for selected axis.
- Raises:
ValueError – If given
axis
is not in {‘x’, ‘y’, ‘z’} for 3D images or not in {‘x’, ‘y’} for 2D images.
Example
>>> from timagetk import TissueImage3D >>> from timagetk.array_util import dummy_labelled_image_3D >>> # Initialize a dummy (uint8) TissueImage3D with a ZYX shape of 5x13x12: >>> img = TissueImage3D(dummy_labelled_image_3D([1.0, 0.5, 0.5]), background=1) >>> print(img.get_slice(0, "z")) >>> inv_img = img.invert_axis(axis='z') >>> print(inv_img.get_slice(0, "z"))
- transpose(*axes)[source]¶
Permute image axes to given order, reverse by default.
- Parameters:
axes (list of int or list of str, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.
- Returns:
TissueImage3D – The image with permuted axes.
Examples
>>> from timagetk import TissueImage3D >>> from timagetk.array_util import dummy_labelled_image_3D >>> # -- Transpose works with 3D images: >>> # Initialize a dummy (uint8) TissueImage3D with a ZYX shape of 5x13x12: >>> img = TissueImage3D(dummy_labelled_image_3D([1.0, 0.5, 0.5]), background=1) >>> img_t = img.transpose() >>> # Transpose update the shape attribute of the image (here reversed): >>> print(img_t.shape) (12, 13, 5) >>> # Transpose update the voxelsize attribute of the image (here reversed): >>> print(img_t.voxelsize) [0.5, 0.5, 1.0] >>> # Transpose update the metadata dictionary of the image: >>> print(img_t.metadata)
>>> # -- Transpose accept axe names as input: >>> img_t = img.transpose('xyz') >>> print(img_t.shape) (12, 13, 5) >>> img_t = img.transpose('x', 'y', 'z') >>> print(img_t.shape) (12, 13, 5) >>> # -- Transpose works with 2D images: >>> from timagetk.array_util import dummy_labelled_image_2D >>> # Initialize a random (uint8) 2D SpatialImage with a YX shape of 13x12 (rows, columns): >>> img = TissueImage3D(dummy_labelled_image_2D([0.52, 0.53]), background=1) >>> img_t = img.transpose() >>> # Transpose update the shape attribute of the image (here reversed): >>> print(img.shape) (13, 12) >>> print(img_t.shape) (12, 13)
- voxel_first_layer(connectivity=18, keep_background=True, **kwargs)[source]¶
Extract the first layer of non-background voxels in contact with the background.
- Parameters:
- Returns:
TissueImage3D – Image made of the first layer of voxel in contact with the background
Example
>>> from timagetk import TissueImage3D >>> from timagetk.array_util import dummy_labelled_image_3D >>> # Initialize a dummy (uint8) TissueImage3D with a ZYX shape of 5x13x12: >>> img = TissueImage3D(dummy_labelled_image_3D([1.0, 0.5, 0.5]), background=1) >>> l1_img = img.voxel_n_first_layer(keep_background=False) >>> print(l1_img.get_array()) # only second XY-slice should be non-zero
- voxel_n_first_layer(n_voxel_layer, connectivity=18, keep_background=True, **kwargs)[source]¶
Extract the n-first layer of non-background voxels in contact with the background.
- Parameters:
- Returns:
TissueImage3D – Image made of the selected number of voxel layers
Example
>>> from timagetk import TissueImage3D >>> from timagetk.array_util import dummy_labelled_image_3D >>> # Initialize a dummy (uint8) TissueImage3D with a ZYX shape of 5x13x12: >>> img = TissueImage3D(dummy_labelled_image_3D([1.0, 0.5, 0.5]), background=1) >>> l1_img = img.voxel_n_first_layer(1, keep_background=False) >>> print(l1_img.get_array()) # only second XY-slice should be non-zero
- timagetk.components.tissue_image.cell_layers_from_image(seg_img, layers, labels=None, not_a_label=0, background=1)[source]¶
Return a layer indexed dictionary of with an array of label per time-point.
- Parameters:
seg_img (str or timagetk.LabelledImage or timagetk.TissueImage3D) – Segmented image.
labels (list or set, optional) – List of cell labels to keep.
not_a_label (int, optional) – If specified, it defines the “unknown label” (i.e. a value that is not a label). Defaults to
0
.background (int, optional) – If specified, it defines the “background label” (i.e. the space around labels). Defaults to
1
.
- Returns:
dict – Dictionary of labels per cell layer.
Examples
>>> from timagetk.components.tissue_image import cell_layers_from_image >>> from timagetk.synthetic_data.labelled_image import example_layered_sphere_labelled_image >>> from timagetk.io import imread >>> from timagetk import TissueImage3D >>> im = example_layered_sphere_labelled_image(n_points=5, n_layers=2, extent=50., voxelsize=(0.5, 0.5, 0.5)) >>> im = TissueImage3D(im, background=1, not_a_label=0) >>> cell_by_layers = cell_layers_from_image(im, [1, 2, 3]) >>> print(cell_by_layers[2]) # list cells in layer 2 [3, 4, 5, 6, 7] >>> print({layer: len(cids) for layer, cids in cell_by_layers.items()}) {1: 20, 2: 5, 3: 1}
- timagetk.components.tissue_image.tissue_image(image, **kwargs)[source]¶
Metaclass for 2D or 3D tissue image.
Examples
>>> from timagetk.io import imread >>> from timagetk.io.util import shared_dataset >>> from timagetk.components.tissue_image import tissue_image >>> tissue = imread(shared_dataset("p58", "intensity")[0], rtype=tissue_image, background=1, not_a_label=0) >>> print(tissue) >>> tissue.is3D()
- timagetk.components.tissue_image.voxel_n_layers(image, background, connectivity=None, n_layers=1, **kwargs)[source]¶
Extract the n-first layer of non-background voxels, i.e. those in contact with the background.
- Parameters:
image (numpy.ndarray) – A labelled array with a background.
background (int) – Id of the background label.
connectivity (int, optional) – Connectivity or neighborhood of the structuring element, default is
18
in 3D and4
in 2D. Should be in [4, 6, 8, 18, 26], where 4 and 8 are 2D structuring elements, the rest are 3D structuring elements.n_layers (int, optional) – Number of layer of voxels to extract, the first one being in contact with the background
- Returns:
numpy.ndarray – Labelled image made of the selected number of voxel layers
Trsf class¶
Image transformation class.
This is basically a linear matrix or a dense vectorfield. They can be generated: - manually with timagetk.algorithms.trsf.create_trsf - automatically with timagetk.algorithms.blockmathing or timagetk.algorithms.pointmatching algorithms
- timagetk.components.trsf.DEF_TRSF_TYPE = 'affine'¶
Default transformation type.
- timagetk.components.trsf.DEF_TRSF_UNIT = 'real'¶
Default transformation unit.
- timagetk.components.trsf.TRSF_TYPE = ['null', 'similitude', 'rigid', 'affine', 'vectorfield']¶
List of valid transformation types for
Trsf
class fromtimagetk.components.trsf
.
- timagetk.components.trsf.TRSF_UNIT = ['real', 'voxel']¶
List of valid transformation unit for
Trsf
class fromtimagetk.components.trsf
.
- class timagetk.components.trsf.Trsf(trsf=None, **kwargs)[source]¶
Transformation objects describe linear and non-linear matrix for image registration.
Examples
>>> from timagetk import Trsf >>> trsf = Trsf() >>> # Test if "type" of transformation is null: >>> trsf.is_null() True >>> # Get the "unit" of transformation object: >>> trsf.get_unit() 'real' >>> # Use `create_trsf` to create a random transformation: >>> from timagetk.algorithms.trsf import create_trsf >>> trsf = create_trsf('random', trsf_type="rigid") >>> print(trsf) >>> trsf.get_type() 'rigid' >>> # Change the unit from "real" (default) to "voxel": >>> trsf.set_unit("voxel") >>> trsf.get_unit() 'voxel' >>> # Manual creation of linear transformation >>> import numpy as np >>> arr = np.array([[1., 0., 0., 0.], [0., 2., 0., 0.], [0., 0., 3., 0.], [0., 0., 0., 4.]]) >>> man_trsf = Trsf(arr) >>> print(man_trsf) vtTransformation : { type : AFFINE_3D, unit : real, } >>> print(man_trsf.get_array()) [[1. 0. 0. 0.] [0. 2. 0. 0.] [0. 0. 3. 0.] [0. 0. 0. 4.]] >>> # Manual creation of linear transformation >>> import numpy as np >>> arr = np.array([[1., 0., 0., 0.], [0., 2., 0., 0.], [0., 0., 3., 0.], [0., 0., 0., 4.]]) >>> man_trsf = Trsf(arr, trsf_type='rigid', trsf_unit='voxel') >>> # Manual creation of non-linear transformation >>> import numpy as np >>> arr = np.array([np.random.random((4, 5, 5)), np.random.random((4, 5, 5)), np.random.random((4, 5, 5))]) >>> arr.shape (3, 4, 5, 5) >>> from vt import vtImage >>> vtim = vtImage(arr, [0.5, 0.1, 0.1])
- __init__(trsf=None, **kwargs)[source]¶
Transformation initialisation method.
- Parameters:
trsf (vtTransformation or str or ndarray, optional) – The name of the transformation to load, or the matrix to use.
trsf_unit ({'real', 'voxel'}) – Use ‘real’ to change the transformation unit to real world metrics. Use ‘voxel’ to change the transformation unit to be voxel based.
trsf_type (str in {"rigid", "similitude", "affine", "vectorfield"}, optional) – Use this to set the transformation type.
name (str) – Use this to give a name to the transformation, use the
name
attribute to access it.
- get_array()[source]¶
Return the linear part of transformation.
- Returns:
numpy.ndarray – The linear part of the transformation if any.
- get_type()[source]¶
Return the transformation type.
- Returns:
str – The type of transformation. Should be in {“null”, “rigid”, “similitude”, “affine”, “vectorfield”}.
Examples
>>> from timagetk import Trsf >>> trsf = Trsf() >>> trsf.get_type() 'null'
- get_unit()[source]¶
Get the transformation unit, either ‘real’ or ‘voxel’.
- Returns:
{‘real’, ‘voxel’} – The transformation unit.
Examples
>>> from timagetk import Trsf >>> trsf = Trsf() >>> trsf.get_unit() 'real'
- is_affine()[source]¶
Test if the transformation is affine.
- Returns:
bool –
True
if the transformation is affine, elseFalse
.
Examples
>>> # Use `create_trsf` to create a random transformation: >>> from timagetk.algorithms.trsf import create_trsf >>> trsf = create_trsf('random', trsf_type="affine") >>> trsf.is_affine() True
- is_identity()[source]¶
Test if the transformation is the identity.
- Returns:
bool –
True
if the transformation is the identity, elseFalse
.
Examples
>>> from timagetk import Trsf >>> from timagetk.algorithms.trsf import create_trsf >>> trsf = create_trsf('identity') >>> trsf.is_identity() True
- is_null()[source]¶
Test if the transformation is empty.
- Returns:
bool –
True
if the transformation is empty, elseFalse
.
Examples
>>> from timagetk import Trsf >>> trsf = Trsf() >>> trsf.is_null() True
- is_rigid()[source]¶
Test if the transformation is rigid.
- Returns:
bool –
True
if the transformation is rigid, elseFalse
.
Examples
>>> # Use `create_trsf` to create a random transformation: >>> from timagetk.algorithms.trsf import create_trsf >>> trsf = create_trsf('random', trsf_type="rigid") >>> trsf.is_rigid() True # FIXME: not working because of `create_trsf`...
- is_similitude()[source]¶
Test if the transformation is similitude.
- Returns:
bool –
True
if the transformation is similitude, elseFalse
.
Examples
>>> from timagetk import Trsf >>> trsf = Trsf() >>> trsf.is_similitude() True
- is_vectorfield()[source]¶
Test if the transformation is vectorfield.
- Returns:
bool –
True
if the transformation is vectorfield, elseFalse
.
Examples
>>> # Use `create_trsf` to create a random transformation: >>> from timagetk.algorithms.trsf import create_trsf >>> from timagetk.array_util import random_spatial_image >>> # A template image is required to initialize a "random" vectorfield transformation: >>> img = random_spatial_image([15, 40, 40], voxelsize=[0.5, 0.21, 0.21]) >>> trsf = create_trsf('sinus3D', template_img=img, trsf_type="vectorfield") >>> trsf.is_vectorfield() True # FIXME: not working because of `create_trsf`...
- set_unit(unit)[source]¶
Change the unit of the transformation, either ‘real’ or ‘voxel’.
- Parameters:
unit ({'real', 'voxel'}) – Use ‘real’ to change the transformation unit to real world metrics. Use ‘voxel’ to change the transformation unit to be voxel based.
Examples
>>> from timagetk import Trsf >>> trsf = Trsf() >>> trsf.set_unit("voxel") >>> trsf.get_unit() 'voxel'
- write(fname)[source]¶
Write the transformation to given file path.
- Parameters:
fname (str or pathlib.Path) – File path where to save the transformation.
Metadata class¶
Important
This is a work in progress!
Metadata functionnalities.
Use the function to add parameters to metadata when performing image modifications.
Metadata specifications:
Use ‘timagetk’ as the metadata main root key to store information
Use ‘class’ key for class information
Use a counter to sort operation orders
Under each number save a dictionary with details of the modification or about algorithm applied, such as its name and their parameters or the name of the transformation (or even the transformation if linear!).
Examples
>>> import numpy as np
>>> from timagetk.algorithms.resample import isometric_resampling
>>> from timagetk import SpatialImage
>>> test_array = np.ones((5,5,10), dtype=np.uint8)
>>> image_1 = SpatialImage(test_array, voxelsize=[1., 1., 2.])
>>> image_iso = isometric_resampling(image_1)
>>> image_iso.metadata['timagetk']
{(1, 'resample_isotropic'):
{'params': {},
'called':
{(1, 'resample'):
{'params':
{'image': ['', ''],
'option': 'gray',
'voxelsize': [1.0, 1.0, 1.0]},
'called':
{(1, 'apply_trsf'):
{'dtype': None,
'image': ['', ''],
'param_str_1': '-linear -template-dim 5 5 20 -template-voxel 1.0 1.0 1.0',
'param_str_2': ' -resize -interpolation linear',
'template_img': ['', ''],
'trsf': None}
}
}
}
}
}
- timagetk.components.metadata.IMAGE_MD_TAGS = ['shape', 'ndim', 'dtype', 'axes_order', 'origin', 'voxelsize', 'unit', 'acquisition_date']¶
List of tags associated to the metadata of an image.
- timagetk.components.metadata.IMAGE_MD_TYPES = {'acquisition_date': 'str', 'axes_order': 'dict', 'dtype': 'str', 'extent': 'list', 'ndim': 'int', 'origin': 'list', 'shape': 'list', 'unit': 'str', 'voxelsize': 'list'}¶
Dictionary mapping the type of each metadata tag.
- class timagetk.components.metadata.ImageMetadata(image, **kwargs)[source]¶
Metadata associated to
SpatialImage
attributes.With a
numpy.ndarray
get: ‘shape’, ‘ndim’, & ‘dtype’. Also, you must provide ‘origin’ and ‘voxelsize’ as keyword arguments, otherwise they will be set to their default values:DEFAULT_ORIG_2D
&DEFAULT_VXS_2D
orDEFAULT_ORIG_3D
&DEFAULT_VXS_3D
according to dimensionality.With a
SpatialImage
instance or any other which inherit it, also get: ‘voxelsize’ & ‘origin’.- dtype¶
Bit depth and size of the image
- Type:
- unit¶
The size unit, in International System of Units (meters), associated to the image.
- Type:
str, optional
Notes
Defined attributes for
ImageMetadata
are inIMAGE_MD_TAGS
. Attribute ‘extent’ is computed bytimagetk.util.compute_extent()
. It is possible to update a metadata dictionary with the known tags (and ‘extent’) usingself.update_metadata()
.- __init__(image, **kwargs)[source]¶
ImageMetadata constructor.
- Parameters:
image (numpy.ndarray or timagetk.SpatialImage) – Image to use to define metadata
image_md (dict) – Dictionary of metadata, may contain ‘voxelsize’ and/or ‘origin’ if using an array instead of a SpatialImage
axes_order (list, optional) – Physical axes ordering, defaults to
YX
in 2D orZYX
in 3D.origin (list, optional) – Coordinates of the origin in the image, defaults to
[0, 0]
in 2D or[0, 0, 0]
in 3D.voxelsize (list, optional) – Image voxelsize, defaults to
[1.0, 1.0]
in 2D or[1.0, 1.0, 1.0]
in 3D.unit (int or float, optional) – The size unit, in International System of Units (meters), associated to the image.
See also
timagetk.components.spatial_image.DEFAULT_AXES_2D
,timagetk.components.spatial_image.DEFAULT_AXES_3D
,timagetk.components.spatial_image.DEFAULT_VXS_2D
,timagetk.components.spatial_image.DEFAULT_VXS_3D
,timagetk.components.spatial_image.DEFAULT_ORIG_2D
,timagetk.components.spatial_image.DEFAULT_ORIG_3D
,timagetk.components.spatial_image.DEFAULT_SIZE_UNIT
Notes
If image is an array, you must provide ‘origin’ and ‘voxelsize’ as keyword arguments, otherwise they will be set to their default values.
Examples
>>> import numpy as np >>> from timagetk.components.metadata import ImageMetadata >>> # - Create a random array: >>> img = np.random.random_sample((15, 15)) >>> # - Do NOT specify 'voxelsize' & 'origin': >>> img_md = ImageMetadata(img) >>> # - Take a look at the obtained metadata: >>> img_md.get_dict() {'shape': (15, 15), 'ndim': 2, 'dtype': dtype('float64'), 'axes_order': 'YX', 'voxelsize': [1.0, 1.0], 'unit': 1e-06, 'origin': [0, 0], 'extent': [14.0, 14.0]} >>> # - Specify 'voxelsize' & 'unit': >>> md = {'voxelsize': [0.5, 0.5], 'unit': 1e-06} >>> img_md = ImageMetadata(img, **md) >>> img_md.get_dict() {'shape': (15, 15), 'ndim': 2, 'dtype': dtype('float64'), 'axes_order': 'YX', 'voxelsize': [0.5, 0.5], 'unit': 1e-06, 'origin': [0, 0], 'extent': [7.0, 7.0]} >>> # - Use a SpatialImage as input: >>> import numpy as np >>> from timagetk import SpatialImage >>> from timagetk.components.metadata import ImageMetadata >>> # - Create a random array: >>> img = np.random.random_sample((15, 15)) >>> img = SpatialImage(img) >>> # - Do NOT specify 'voxelsize' & 'origin': >>> img_md = ImageMetadata(img)
- get_from_array(array, voxelsize=None, origin=None, axes_order=None, unit=None)[source]¶
Get image metadata values from an array.
- Parameters:
array (numpy.ndarray) – Array to use to get metadata
voxelsize (list, optional) – Array voxelsize, if
None
(default) use the default values (either DEFAULT_VXS_2D or DEFAULT_VXS_3D)origin (list, optional) – Array origin, if
None
(default) use the default values (either DEFAULT_ORIG_2D or DEFAULT_ORIG_3D)
Notes
Only ‘shape’, ‘ndim’ & ‘type’ information are accessible from a NumPy array! Directly update the metadata dictionary and attributes.
Examples
>>> import numpy as np >>> from timagetk.components.metadata import ImageMetadata >>> # - Create a random array: >>> img = np.random.random_sample((15, 15)) >>> # - Do NOT specify 'voxelsize' & 'origin': >>> img_md = ImageMetadata(img) >>> # - Take a look at the obtained metadata: >>> img_md.get_dict() {'shape': (15, 15), 'ndim': 2, 'dtype': dtype('float64'), 'voxelsize': [1.0, 1.0], 'unit': 1e-06, 'origin': [0, 0], 'extent': [14.0, 14.0]}
- get_from_image(image)[source]¶
Get image metadata values from a SpatialImage instance.
- Parameters:
image (timagetk.SpatialImage) – Image that contains the attributes to update the metadata.
Notes
Directly update the metadata dictionary and attributes.
Examples
>>> from timagetk.components.metadata import ImageMetadata >>> from timagetk.array_util import random_spatial_image >>> # Initialize a random (uint8) 3D SpatialImage: >>> img = random_spatial_image((3, 5, 5), voxelsize=[1., 0.5, 0.5]) >>> img_md = ImageMetadata(img) >>> # - Take a look at the obtained metadata: >>> img_md.get_dict() {'shape': (15, 15), 'ndim': 2, 'dtype': dtype('uint8'), 'voxelsize': [1.0, 1.0], 'unit': 1e-06, 'origin': [0, 0], 'extent': [14.0, 14.0]}
- similar_metadata(md)[source]¶
Compare this ImageMetadata values to another one.
- Parameters:
md (dict or ImageMetadata) – Dictionary or image metadata to compare to self
- Returns:
bool –
True
if all metadata values are equal, elseFalse
.
Examples
>>> from timagetk.array_util import dummy_spatial_image_2D >>> im1 = dummy_spatial_image_2D([0.5, 0.5]) >>> im2 = dummy_spatial_image_2D([0.6, 0.6]) >>> im1.metadata_image.similar_metadata(im2.metadata_image)
- class timagetk.components.metadata.Metadata(md=None)[source]¶
Basic metadata class.
Notes
Take a dictionary as input and make object attributes out of it.
- __init__(md=None)[source]¶
Metadata constructor.
Notes
Uni-dimensional numpy arrays are changed to list. Other type are unchanged. See example.
- Parameters:
md (dict, optional) – Metadata dictionary
Examples
>>> import numpy as np >>> from timagetk.components.metadata import Metadata >>> md = {'origin': [0, 0], 'shape': (10, 10), 'voxelsize':np.array([0.2, 0.2])} >>> md = Metadata(md) >>> md.origin [0, 0] >>> md.shape (10, 10) >>> md.get_dict() {'origin': [0, 0], 'shape': (10, 10), 'voxelsize': [0.2, 0.2]}
- __weakref__¶
list of weak references to the object (if defined)
- class timagetk.components.metadata.ProcessMetadata(image)[source]¶
- __init__(image)[source]¶
ProcessMetadata constructor.
- Parameters:
image (timagetk.SpatialImage or timagetk.LabelledImage or timagetk.TissueImage2D or timagetk.TissueImage3D) – Image to attach processing metadata to.
- __weakref__¶
list of weak references to the object (if defined)
- timagetk.components.metadata.add2md(image, extra_params=None, from_level=2)[source]¶
Add parameters to ‘timagetk’ metadata attribute of given image.
- Parameters:
- Returns:
image (timagetk.SpatialImage or timagetk.LabelledImage or timagetk.TissueImage2D or timagetk.TissueImage3D) – Image with updated metadata dictionary
- timagetk.components.metadata.called_fn_md(lid, hfname, fname, fpars)[source]¶
Metadata format when using function calling others sub-processes.
- timagetk.components.metadata.get_func_name(level=1)[source]¶
Get the name of the function it is embedded in.
- Parameters:
level (int, optional) – Stack level, set to 1 to get the name of the function where
get_func_name
is embedded in, or more to go higher in the stack.- Returns:
str – Name of the function
- timagetk.components.metadata.get_func_param_value_from_frame(my_frame, v_name)[source]¶
Get the value of a variable in the given
frame
.Notes
If a
SpatialImage
instance is found, we return the metadata ‘filepath’/’filename’ instead of the whole object! If aTrsf
is found, and it is linear, we return the transformation matrix as a numpy array.- Parameters:
my_frame (frame) – Frame with a variable
v_name
v_name (str) – Name of a variable in the given frame
my_frame
- Returns:
any – Value of the variable
- timagetk.components.metadata.get_func_params(level=1)[source]¶
Get the parameters of the function it is embedded in.
- Parameters:
level (int, optional) – Stack level, set to 1 to get the name of the function where
get_func_name
is embedded in, or more to go higher in the stack.- Returns:
dict – Dictionary with the name of the parameters and their values at given
level
.
- timagetk.components.metadata.get_func_params_names_from_frame(frame)[source]¶
Get the parameters’ name of the function in the given
frame
.- Parameters:
frame
- Returns:
str – Name of the function
- timagetk.components.metadata.get_last_id(md_dict)[source]¶
Get the last id in the metadata dictionary.
- Parameters:
md_dict (dict) – Metadata dictionary
- Returns:
int – Last id if found else 1
- timagetk.components.metadata.get_params_called(md, op_id, op_name)[source]¶
Get ‘params’ and ‘called’ values in metadata dictionary.
- timagetk.components.metadata.md_str(op_id, op_max, op_name, params, called_md, indent_lvl, indent=' ')[source]¶
- Parameters:
op_id
op_max
op_name
params
called_md
indent_lvl
indent
- timagetk.components.metadata.print_md(metadata, indent_lvl=0)[source]¶
- Parameters:
indent_lvl
metadata
- timagetk.components.metadata.print_params(params, indent_lvl, p_indent='--', indent=' ')[source]¶
- Parameters:
p_indent
indent
params
indent_lvl
- Returns:
str – Formated parameters
Examples
>>> import numpy as np >>> from timagetk import SpatialImage >>> from timagetk.algorithms.resample import isometric_resampling >>> from timagetk.components.metadata import print_md >>> test_array = np.ones((5,5,10), dtype=np.uint8) >>> img = SpatialImage(test_array, voxelsize=[1., 1., 2.]) >>> output_image = isometric_resampling(img, voxelsize=0.4) >>> print(print_md(output_image.metadata))
>>> from timagetk.synthetic_data.labelled_image import example_layered_sphere_labelled_image >>> from timagetk.algorithms.linearfilter import gaussian_filter >>> from timagetk.algorithms.regionalext import regional_extrema >>> from timagetk.algorithms.connexe import connected_components >>> from timagetk.tasks.segmentation import watershed_segmentation >>> from timagetk.components.metadata import print_md >>> input_image = example_layered_sphere_labelled_image >>> smooth_image = gaussian_filter(input_image, sigma=2.0) >>> regext_image = regional_extrema(smooth_image, h=5, method='min') >>> seeds_image = connected_components(regext_image,low_threshold=1,high_threshold=3,method='connected_components') >>> segmented_image = watershed_segmentation(smooth_image, seeds_image, control='first', method='seeded_watershed') >>> segmented_image.metadata['timagetk'] >>> print(print_md(segmented_image.metadata))