darsia.Image#

class Image(img, transformations=None, **kwargs)[source]#

Bases: object

An image with physical meaning.

Wraps a NumPy array together with its physical extent, acquisition time and coordinate system, so that regions, patches and measurements can be addressed in metres and seconds. ScalarImage and OpticalImage are convenience specialisations.

Initialise a physical space-time image.

Supports scalar and vector-valued 2d/3d/4d images, including single time slices and time series. The scalar flag records whether the range is stored in an extra axis; series records whether a time axis is present.

Parameters:
imgnumpy.ndarray

Data array with space_dim + time_dim + range_dim axes.

transformationslist of callable(), optional

Reduction and correction routines, applied in order.

**kwargs

Options controlling the attributes below; the defaults target conventional optical images.

Attributes:
dimint

Dimensionality of the physical space.

scalarbool

Whether the data is scalar-valued (no extra range axis).

seriesbool

Whether the array carries a time axis.

indexingstr

Axis indexing of the first dim entries.

imgnumpy.ndarray

The (space-time) image array.

datelist

Absolute time of each slice.

timelist

Relative time of each slice.

Examples

data = np.zeros((Nx, Ny, Nz, Nt, Nd), dtype=float)
image = darsia.Image(data, scalar=False, series=True, dim=3)

Methods

append(image[, offset])

Append other image to current image.

astype(data_type)

For scalar data types, change the data type of the data array.

copy()

Copy constructor.

eval(point[, interpolation])

Evaluate the image array at a given point location.

geometry()

Generate (flat) geometry object corresponding to the image.

img_as(data_type)

Change data type via skimage.

integral()

Integrate the image over its spatial dimensions.

metadata()

Return all metadata required to initiate an image via keyword arguments.

reset_origin([return_image])

Reset origin and coordinatesystem.

reset_reference_time()

Pick date of first image in a series as reference date.

resize(cx[, cy])

roi(roi)

Extraction of spatial subregion using a darsia.ROI object.

save(path[, verbose])

Save image to file.

set_time([time])

Setter for time array.

shape_metadata()

Return all metadata connected to dimensions of image and voxels.

show([title, duration, mode])

Show image using matplotlib.pyplots or plotly built-in methods.

show_matplotlib([title, duration])

Show the image using matplotlib.pyplot.

show_plain([title])

Show image using matplotlib.pyplots in plain mode.

show_plotly([title, duration])

Show the image using plotly (often faster than matplotlib).

slice(cut, axis)

Extract of spatial slice.

subregion(roi)

Extraction of spatial subregion.

time_interval(indices)

Extraction of temporal subregion, only for space-time images.

time_slice(time_index)

Extraction of single time slice.

to_vtk(path[, name])

Save image to file in vtk format.

update_metadata([meta])

Update metadata of image.

update_reference_time(reference)

Update reference time.

Attributes

coordinatesystem

Physical coordinate system with equipped transformation from voxel to Cartesian space.

domain

Physical domain.

dtype

Data type of the (current) image array.

num_voxels

Number of voxels in each dimension.

opposite_corner

Cartesian coordinate of the corner opposite to origin.

shape

Shape of the image array, incl.

space_num

Spatial resolution, i.e., number of voxels.

voxel_size

Size of each voxel in each direction, ordered as indexing.

img

Data array.

original_dtype

Original dtype at construction of the object.

space_dim

Dimension of the spatial domain.

indexing

Indexing of each axis in context of matrix indexing (ijk) or Cartesian coordinates (xyz).

dimensions

Dimension in the directions corresponding to the indexings.

name

Name of image, e.g., used to describe the origin.

origin

Cartesian coordinates associated to the [0,0,0] voxel (after applying transformations), using Cartesian indexing.

series

Flag controlling whether the data array corresponds to a time series.

time_dim

Dimensionality of the image in temporal sense.

time_num

Number of time points.

date

Time in datetime format.

reference_date

Reference date (for defining relative time).

time

Relative time in scalar format (in seconds).

scalar

Flag controlling whether the data array is scalar, i.e., it does not use an extra axis to encode the range.

range_dim

Dimensionality of the image in data sense.

range_num

Number of entries for each data entry.

append(image, offset=None)[source]#

Append other image to current image. Makes in particular a non-space-time image to a space-time image.

Parameters:
imageImage

Image to be appended.

offsetfloat or int, optional

Time increment between last and next slice.

astype(data_type)[source]#

For scalar data types, change the data type of the data array. For Image data types, cast the entire image.

Parameters:
data_typetype or np.dtype

Target data type.

Returns:
Image

Image with transformed data type.

copy()[source]#

Copy constructor.

Returns:
Image

Copy of the image object.

eval(point, interpolation='nearest')[source]#

Evaluate the image array at a given point location.

Parameters:
pointVoxel, Coordinate, VoxelArray, or CoordinateArray

Point(s) at which to evaluate the image. Coordinates are converted to voxels if necessary.

interpolationstr

Interpolation mode. Either "nearest" (default, rounds to nearest voxel) or "linear" (bilinear/trilinear interpolation via scipy.interpolate.RegularGridInterpolator). Voxel inputs (Voxel/VoxelArray) always use nearest-neighbor regardless of this parameter.

Returns:
np.ndarray

Image value(s) at the given point(s). For a single point, returns a scalar or 1D array depending on whether the image is scalar or non-scalar. For multiple points, returns an array of corresponding values.

Example::

import darsia

import numpy as np

arr = np.arange(12, dtype=float).reshape(3, 4)

image = darsia.ScalarImage(arr, dimensions=[1, 1], space_dim=2)

# Default nearest-voxel evaluation (existing behaviour)

image.eval(darsia.Coordinate([0.6, 0.5]))

# Bilinear interpolation at a sub-voxel coordinate

image.eval(darsia.Coordinate([0.625, 0.5]), interpolation=”linear”) # 8.0

geometry()[source]#

Generate (flat) geometry object corresponding to the image.

Returns:
darsia.Geometry

Geometry object.

img_as(data_type)[source]#

Change data type via skimage.

Parameters:
data_typetype or np.dtype

Target data type.

Returns:
Image

Image with transformed data type.

integral()[source]#

Integrate the image over its spatial dimensions.

Returns:
float

Integral of the image over space.

metadata()[source]#

Return all metadata required to initiate an image via keyword arguments.

Returns:
dict

Metadata with keys equal to all keywords arguments.

reset_origin(return_image=False)[source]#

Reset origin and coordinatesystem.

Parameters:
return_imagebool, optional

Flag controlling whether a copy of the image is returned. Defaults to False.

Returns:
Image

Copy of image with reset coordinatesystem.

reset_reference_time()[source]#

Pick date of first image in a series as reference date.

roi(roi)[source]#

Extraction of spatial subregion using a darsia.ROI object.

Parameters:
roidarsia.ROI

Region of interest, defining a box in space.

Returns:
Image

Image with restricted spatial domain.

save(path, verbose=True)[source]#

Save image to file.

Store array and metadata in single file.

NOTE: Keywords are compatible with imread_from_npz.

Parameters:
pathPath

Full path to image. Use ending “npz”.

set_time(time=None)[source]#

Setter for time array.

Parameters:
timescalar or list, optional

Time to be set; if None, time is retrieved from date.

shape_metadata()[source]#

Return all metadata connected to dimensions of image and voxels.

Useful to define darsia.Geometry from darsia.Image.

Returns:
dict

Metadata with keys to instantiate a Geometry.

show(title='', duration=None, mode='matplotlib', **kwargs)[source]#

Show image using matplotlib.pyplots or plotly built-in methods. The latter often is faster.

Parameters:
titlestr

Title in the displayed window.

durationint, optional

Display duration in seconds.

modestr

Display mode; either “matplotlib” or “plotly”.

**kwargs

Additional arguments passed to show_matplotlib or show_plotly.

show_matplotlib(title='', duration=None, **kwargs)[source]#

Show the image using matplotlib.pyplot.

Parameters:
titlestr

Title in the displayed window.

durationint, optional

Display duration in seconds.

**kwargs

Additional display options:

threshold (float)     threshold for displaying 3d images
relative (bool)       whether the threshold is relative
view (str)            "scatter" or "voxel" (3d only; "voxel"
                      is slower)
side_view (str)       "scatter" or "voxel" (3d only)
surpress_2d (bool)    whether 2d images are displayed
surpress_3d (bool)    whether 3d images are displayed
                      (default True, since slow)
delay (bool)          delay the display, to show several
                      images at once
show_plain(title='', **kwargs)[source]#

Show image using matplotlib.pyplots in plain mode.

NOTE: Only applicable for 2d images, which are not scalar. The image array is plotted without any additional information and modifications.

Parameters:
titlestr

Title in the displayed window.

**kwargs

Additional arguments passed to show_matplotlib or show_plotly.

show_plotly(title='', duration=None, **kwargs)[source]#

Show the image using plotly (often faster than matplotlib).

Parameters:
titlestr

Title in the displayed window.

durationint, optional

Display duration in seconds.

**kwargs

Additional display options:

threshold (float)     threshold for displaying 3d images
relative (bool)       whether the threshold is relative
view (str)            "scatter" or "voxel" (3d only; "voxel"
                      is slower)
side_view (str)       "scatter" or "voxel" (3d only)
surpress_2d (bool)    whether 2d images are displayed
surpress_3d (bool)    whether 3d images are displayed
slice(cut, axis)[source]#

Extract of spatial slice.

Parameters:
cutfloat or int

Coordinate or voxel at which the slice is extracted.

axisstr or int

Axis, normal to the slice, addressing matrix indexing or Cartesian indexing if int or str, respectively.

subregion(roi)[source]#

Extraction of spatial subregion.

Parameters:
roituple of slices, VoxelArray, or CoordinateArray

Voxel intervals in all dimensions, or points in space, in Cartesian coordinates, uniquely defining a box, i.e., at least space_dim points. Type decides interpretation.

Returns:
Image

Image with restricted spatial domain.

time_interval(indices)[source]#

Extraction of temporal subregion, only for space-time images.

Parameters:
indicesslice

Time interval in terms of indices.

Returns:
Image

Image with restricted temporal domain.

Raises:
ValueError

If image is not a time series.

ValueError

If indices is not a slice.

time_slice(time_index)[source]#

Extraction of single time slice.

Parameters:
time_indexint

Time index in interval [0, …, time_num-1].

Returns:
Image

Single-timed image.

to_vtk(path, name=None)[source]#

Save image to file in vtk format.

Parameters:
pathPath

Full path to image, without ending.

namestr, optional

Name of the data. Defaults to None.

update_metadata(meta=None, **kwargs)[source]#

Update metadata of image.

Parameters:
metadict

Metadata to be updated, with keys corresponding to self.metadata().

**kwargs

Additional keyword arguments to be updated.

update_reference_time(reference)[source]#

Update reference time. Modifies the relative time.

reference (datetime or float): reference date or relative reference time (in seconds)

property coordinatesystem#

Physical coordinate system with equipped transformation from voxel to Cartesian space.

NOTE: The definition of CoordinateSystem implicitly requires several attributes to be defined. Therefore, we need to define the CoordinateSystem after defining the spatial attributes, also implicitly defined as properties.

Returns:
CoordinateSystem

Physical coordinate system.

date#

Time in datetime format.

dimensions#

Dimension in the directions corresponding to the indexings.

property domain#

Physical domain.

Returns:
tuple

Collection of coordinates in matrix indexing defining domain.

property dtype#

Data type of the (current) image array.

Returns:
np.dtype

Data type of the image array.

img#

Data array.

indexing#

Indexing of each axis in context of matrix indexing (ijk) or Cartesian coordinates (xyz).

name#

Name of image, e.g., used to describe the origin.

property num_voxels#

Number of voxels in each dimension.

Returns:
list

Number of voxels in each dimension.

property opposite_corner#

Cartesian coordinate of the corner opposite to origin.

Returns:
Coordinate

Cartesian coordinate of the corner opposite to origin.

origin#

Cartesian coordinates associated to the [0,0,0] voxel (after applying transformations), using Cartesian indexing.

original_dtype#

Original dtype at construction of the object.

range_dim#

Dimensionality of the image in data sense.

range_num#

Number of entries for each data entry.

reference_date#

Reference date (for defining relative time).

scalar#

Flag controlling whether the data array is scalar, i.e., it does not use an extra axis to encode the range.

series#

Flag controlling whether the data array corresponds to a time series.

property shape#

Shape of the image array, incl. time and data dimension.

Returns:
tuple

Shape of the image array.

space_dim#

Dimension of the spatial domain.

property space_num#

Spatial resolution, i.e., number of voxels.

Returns:
int

Spatial resolution.

time#

Relative time in scalar format (in seconds).

time_dim#

Dimensionality of the image in temporal sense.

time_num#

Number of time points.

property voxel_size#

Size of each voxel in each direction, ordered as indexing.

Returns:
list

Size of each voxel in each direction.