Input/Output¶
Image I/O¶
Image IO (input/output) module.
- timagetk.io.image.apply_mask(img, mask_filename, masking_value=0, crop_mask=False)[source]¶
Load and apply a z-projection mask (2D) to a SpatialImage (2D/3D).
In case of an intensity image, allows removing unwanted signal intensities. If the SpatialImage is 3D, it is applied in z-direction. The mask should contain a distinct “masking value”.
- Parameters:
img (timagetk.components.spatial_image.SpatialImage) – Image to modify with the mask.
mask_filename (str) – String giving the location of the mask file
masking_value (int, optional) – Value (default 0) defining the masked region
crop_mask (bool, optional) – If
True
(defaultFalse
), the returned SpatialImage is cropped around the non-masked region
- Returns:
timagetk.components.spatial_image.SpatialImage – The masked SpatialImage.
- timagetk.io.image.default_image_attributes(array, log_undef=<bound method Logger.debug of <Logger timagetk.io.image (INFO)>>, **kwargs)[source]¶
Set the default image attribute values given the array dimensionality.
- Parameters:
array (numpy.ndarray) – The array to use as image.
log_undef (fun) – The logging level to use for undefined image attributes.
dtype (str or numpy.dtype) – A valid
dtype
to use with this array, checked againstAVAIL_TYPES
. Defaults toarray.dtype
.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
{}
.
- Returns:
dict – The image attributes dictionary.
See also
timagetk.components.spatial_image.AVAIL_TYPES
,timagetk.components.spatial_image.DEFAULT_SIZE_UNIT
,timagetk.components.spatial_image.default_axes_order
,timagetk.components.spatial_image.default_origin
,timagetk.components.spatial_image.default_voxelsize
Notes
Any extra keyword argument not listed above will be kept and returned.
Examples
>>> from timagetk.io.image import default_image_attributes >>> from timagetk.array_util import random_array >>> # Example 1: set the default image attributes for a 2D array: >>> img_2D = random_array([7, 5]) >>> attr_2D = default_image_attributes(img_2D) >>> print(attr_2D) {'dtype': 'uint8', 'axes_order': 'YX', 'origin': [0, 0], 'unit': 1e-06, 'voxelsize': [1.0, 1.0], 'metadata': {}}
>>> # Example 2: set the default image attributes for a 3D array: >>> img_3D = random_array([7, 5, 4]) >>> attr_3D = default_image_attributes(img_3D) >>> print(attr_3D) {'dtype': 'uint8', 'axes_order': 'ZYX', 'origin': [0, 0, 0], 'unit': 1e-06, 'voxelsize': [1.0, 1.0, 1.0], 'metadata': {}} >>> # Example 3: set the default image attributes for a 3D array, except voxelsize: >>> attr_3D = default_image_attributes(img_3D, voxelsize=[0.5, 0.25, 0.25]) >>> print(attr_3D) {'voxelsize': [0.5, 0.25, 0.25], 'dtype': 'uint8', 'axes_order': 'ZYX', 'origin': [0, 0, 0], 'unit': 1e-06, 'metadata': {}}
- timagetk.io.image.imread(fname, rtype=None, **kwargs)[source]¶
Read an image (2D/3D +C).
- Parameters:
fname (str or pathlib.Path) – File path to the image, can be a URL.
rtype (type, optional) – If defined, force retured type of image to given class.
channel_names (list of str) – List of channel names, to use with
MultiChannelImage
instances to overide those defined in the CZI file.channel (str) – Channel to return, i.e only this one will be returned, to use with
MultiChannelImage
instances.hash (str) – The hash value to use for comparison.
hash_method ({'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'MD5'}) – The hash method to use, default is ‘md5’, case insentitive.
- Returns:
timagetk.components.spatial_image.SpatialImage or timagetk.LabelledImage or timagetk.MultiChannelImage – Image and metadata (such as voxel-size, extent, type, etc.)
See also
timagetk.io.util.POSS_EXT
Example
>>> from timagetk.io.image import imread >>> # EXAMPLE #1 - Load a file from URL: >>> img = imread('https://zenodo.org/record/3737630/files/sphere_membrane_t0.inr.gz') >>> type(img) timagetk.components.spatial_image.SpatialImage >>> print((img.filepath, img.filename)) ('/tmp', 'sphere_membrane_t0.inr.gz')
>>> # EXAMPLE #2 - Load a file from URL and validate with secure hash: >>> md5_h = '24cc1edfaca092c26486a58fd6979827' >>> img = imread('https://zenodo.org/record/3737630/files/sphere_membrane_t0.inr.gz', hash=md5_h, hash_method='md5') >>> type(img) timagetk.components.spatial_image.SpatialImage >>> print((img.filepath, img.filename)) ('/tmp', 'sphere_membrane_t0.inr.gz)
>>> # EXAMPLE #3 - Load a file from URL and force returned instance type: >>> from timagetk import TissueImage3D >>> url = 'https://zenodo.org/record/3737630/files/sphere_membrane_t0_seg.inr.gz' >>> img = imread(url, TissueImage3D, background=1, not_a_label=0) >>> type(img) timagetk.components.tissue_image.TissueImage3D >>> # EXAMPLE #4 - Load a file from the shared data: >>> from timagetk.io.util import shared_dataset >>> image_path = shared_dataset('sphere')[0] >>> img = imread(image_path) >>> type(img) timagetk.components.spatial_image.SpatialImage
- timagetk.io.image.imsave(fname, sp_img, **kwargs)[source]¶
Save an image (2D/3D).
- Parameters:
fname (str or pathlib.Path) – File path where to save the image.
sp_img (timagetk.components.spatial_image.SpatialImage or timagetk.LabelledImage or timagetk.TissueImage3D or timagetk.MultiChannelImage) – Image instance to save on drive.
pattern (str) – Physical dimension order to use to save the image, “ZCYX” by default.
force (bool) – Overwrite any existing file of same fname.
See also
timagetk.io.util.POSS_EXT
Example
>>> from timagetk.array_util import random_spatial_image >>> import tempfile >>> import numpy as np >>> from timagetk.io.image import imsave, imread >>> from timagetk import SpatialImage >>> sp_image = random_spatial_image((3, 4, 5), voxelsize=[0.3, 0.4 ,0.5]) >>> # Save the image in a temporary file: >>> tmp_path = tempfile.NamedTemporaryFile() >>> imsave(tmp_path.name+'.tif', sp_image) >>> # Load this file: >>> sp_image_cp = imread(tmp_path.name+'.tif') >>> # Compare arrays and voxelizes: >>> np.testing.assert_array_equal(sp_image, sp_image_cp) >>> np.testing.assert_array_equal(sp_image.voxelsize, sp_image_cp.voxelsize)
>>> sp_image = random_spatial_image((3, 4), voxelsize=[0.3, 0.4]) >>> # Save the image in a temporary file: >>> tmp_path = tempfile.NamedTemporaryFile() >>> imsave(tmp_path.name+'.tif', sp_image) >>> # Load this file: >>> sp_image_cp = imread(tmp_path.name+'.tif') >>> # Compare arrays and voxelizes: >>> np.testing.assert_array_equal(sp_image, sp_image_cp) >>> np.testing.assert_array_equal(sp_image.voxelsize, sp_image_cp.voxelsize)
>>> from timagetk import MultiChannelImage >>> from timagetk.io import imsave >>> from timagetk.synthetic_data.nuclei_image import example_nuclei_signal_images >>> n_img, s_img, _, _= example_nuclei_signal_images(n_points=10, extent=20, voxelsize=(1,1,1)) >>> img = MultiChannelImage({'nuclei':n_img, 'signal':s_img}) >>> imsave('~/test.tif', img)
>>> tmp_path = tempfile.NamedTemporaryFile() >>> imsave(tmp_path.name+'.tif', img)
- timagetk.io.image.read_czi_image(czi_file, channel_names=None, **kwargs)[source]¶
Read Carl Zeiss Image (CZI) file.
- Parameters:
czi_file (str) – File path to the image to load.
channel_names (list of str, optional) – Defines channel names to use. By default, try to load channel names from the image metadata.
pattern (str, optional) – Physical dimension order to use to load the image, “.C.ZXY.” by default. By default, try to load the pattern from the image metadata.
return_order (str) – Physical dimension order to use for the returned array. Defaults to “ZYXC”.
- Returns:
timagetk.SpatialImage or timagetk.MultiChannelImage – If a single channel and time-point is found, returns a
SpatialImage
instance. If multiple channels are found but with a single time-point, returns aMultiChannelImage
instance.
Notes
If more than one channel is found, return a
MultiChannelImage
.For the pattern variable, use:
C
as channel;T
as time;X
as x-axis (rows);Y
as y-axis (planes);Z
as z-axis (columns);
Examples
>>> from timagetk.io.image import read_czi_image >>> from timagetk.io.image import _image_from_url >>> im_url = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> im_fname = _image_from_url(im_url) # download the CZI image >>> ch_names = ["DII-VENUS-N7", "pPIN1:PIN1-GFP", "Propidium Iodide", "pRPS5a:TagBFP-SV40", "pCLV3:mCherry-N7"] >>> image = read_czi_image(im_fname, ch_names) >>> print(image.get_channel_names()) ['DII-VENUS-N7', 'pPIN1:PIN1-GFP', 'Propidium Iodide', 'pRPS5a:TagBFP-SV40', 'pCLV3:mCherry-N7'] >>> print(image)
>>> im_url = "https://zenodo.org/record/3737795/files/qDII-CLV3-PIN1-PI-E35-LD-SAM4.czi" >>> im_fname = _image_from_url(im_url) # download the CZI image >>> from czifile import CziFile >>> czi_img = CziFile(im_fname) >>> import xmltodict >>> md = xmltodict.parse(czi_img.metadata())['ImageDocument']['Metadata']
- timagetk.io.image.read_lsm_image(lsm_file, channel_names=None, **kwargs)[source]¶
Read LSM file.
- Parameters:
lsm_file (str) – File path to the image to load.
channel_names (list of str, optional) – Defines channel names to use. By default, try to load channel names from the image metadata.
pattern (str, optional) – Physical dimension order to use to load the image, “TZCYX” by default. By default, try to load the pattern from the image metadata.
return_order (str) – Physical dimension order to use for the returned array. Defaults to “ZYXC”.
- Returns:
timagetk.SpatialImage or timagetk.MultiChannelImage – If a single channel and time-point is found, returns a
SpatialImage
instance. If multiple channels are found but with a single time-point, returns aMultiChannelImage
instance.
Notes
If more than one channel is found, return a
MultiChannelImage
.For the pattern variable, use:
C
as channel;T
as time;X
as x-axis (rows);Y
as y-axis (planes);Z
as z-axis (columns);
Examples
>>> from timagetk.io.image import read_lsm_image >>> from timagetk.io.util import shared_data >>> im = read_lsm_image(shared_data("090223-p58-flo-top.lsm", "p58/raw")) >>> im.get_voxelsize() [1.0, 0.20031953747828882, 0.20031953747828882] >>> im.get_shape() [50, 460, 460] >>> im.unit 1e-06 >>> im.axes_order 'ZYX'
- timagetk.io.image.read_tiff_image(tiff_file, channel_names=None, **kwargs)[source]¶
Read (ImageJ) TIFF image file.
- Parameters:
tiff_file (str) – File path to the image to load.
channel_names (list of str, optional) – Defines channel names to use. By default, try to load channel names from the image metadata.
pattern (str, optional) – Physical dimension order to use to load the image, “ZCYX” by default. By default, try to load the pattern from the image metadata.
return_order (str) – Physical dimension order to use for the returned array. Defaults to “ZYXC”.
- Returns:
timagetk.SpatialImage or timagetk.MultiChannelImage – If a single channel and time-point is found, returns a
SpatialImage
instance. If multiple channels are found but with a single time-point, returns aMultiChannelImage
instance.
Notes
If more than one channel is found, return a
MultiChannelImage
.For the pattern variable, use:
C
as channel;X
as x-axis (rows);Y
as y-axis (planes);Z
as z-axis (columns);
Examples
>>> from timagetk.io.image import read_tiff_image >>> from timagetk.io.util import shared_data >>> im = read_tiff_image(shared_data("p58_t0_fused.tif", "p58/fusion")) >>> im.get_voxelsize() [0.2003195434808731, 0.20031954352751363, 0.20031954352751363] >>> im.get_shape() [59, 460, 460] >>> im.axes_order 'ZYX'
- timagetk.io.image.save_tiff_image(tiff_file, img, **kwargs)[source]¶
Save an image as a TIFF file.
- Parameters:
tiff_file (str or pathlib.Path) – File path where to save the image.
img (timagetk.SpatialImage or timagetk.LabelledImage or timagetk.TissueImage3D or timagetk.MultiChannelImage) – Image instance to save on drive.
pattern (str, optional) – Physical dimension order to use to load the image, “ZCYX” by default. By default, try to load the pattern from the image metadata.
Notes
For the pattern variable, use:
C
as channel;X
as x-axis (rows);Y
as y-axis (planes);Z
as z-axis (columns);
Example
>>> import tempfile >>> from timagetk import MultiChannelImage >>> from timagetk.io.image import save_tiff_image >>> # EXAMPLE#1 - Save a SpatialImage as a TIFF file: >>> from timagetk.array_util import random_spatial_image >>> sp_image = random_spatial_image((3, 4, 5), voxelsize=[0.3, 0.4 ,0.5]) >>> # Save the image in a temporary file: >>> tmp_path = tempfile.NamedTemporaryFile() >>> save_tiff_image(tmp_path.name+'.tif', sp_image)
>>> # EXAMPLE#2 - Save a MultiChannel as a TIFF file: >>> from timagetk.synthetic_data.nuclei_image import example_nuclei_signal_images >>> n_img, s_img, _, _= example_nuclei_signal_images(n_points=10, extent=20, voxelsize=(1,1,1)) >>> img = MultiChannelImage({'nuclei':n_img, 'signal':s_img}) >>> tmp_path = tempfile.NamedTemporaryFile() >>> save_tiff_image(tmp_path.name+'.tif', img)
Accepted image formats are: |POSS_EXT|.
Transformation I/O¶
Input/Output for Trsf objects.