Image data

Nanomesh has two classes for representing image data, Plane for working with 2D pixel data and Volume for working with 3D voxel data. These can be used to load, crop, transform, filter, and segment image data.

Both classes derive from Image. Instantiating Image will create the appropriate subclass.

Classes

nanomesh.Image(image)

Generic image class.

nanomesh.Plane(image)

Data class for working with 2D image data.

nanomesh.Volume(image)

Data class for working with 3D (volumetric) image data..

Reference

class nanomesh.Image(image: ndarray)[source]

Bases: object

Generic image class.

Depending on the dimensions of the image data, the appropriate subclass will be chosen if possible.

Parameters

image (numpy.array) – N-dimensional numpy array containing image data.

image

The raw image data

Type

numpy.ndarray

Methods:

apply(function,Β **kwargs)

Apply function to {classname}.image array.

astype(dtype)

Shortcut for np.ndarray.astype().

binary_digitize([threshold])

Convert into a binary image.

digitize(bins,Β **kwargs)

Digitize image.

fft()

Apply fourier transform to image.

from_sitk_image(sitk_image)

Return instance from SimpleITK.Image.

gaussian([sigma])

Apply Gaussian blur to image.

invert_contrast()

Invert the contrast of the image.

load(filename,Β **kwargs)

Load the data.

normalize_values()

Rescale values to 0.0 to 1.0.

save(filename)

Save the data.

threshold([method])

Compute threshold value using given method.

to_sitk_image()

Return instance of SimpleITK.Image from {classname}.image().

apply(function: Callable, **kwargs)[source]

Apply function to {classname}.image array. Return an instance of {classname} if the result is of the same dimensions, otherwise return the result of the operation.

Parameters
  • function (callable) – Function to apply to {classname}.image.

  • **kwargs – Keyword arguments to pass to function.

Returns

New instance of {classname}.

Return type

{classname}

astype(dtype: str | np.dtype) np.ndarray[source]

Shortcut for np.ndarray.astype().

binary_digitize(threshold: Optional[Union[float, str]] = None)[source]

Convert into a binary image.

Parameters

threshold (float, optional) – Threshold used for segmentation. If given as a string, apply corresponding theshold via {classname}.threshold(). Defaults to median.

Returns

New instance of {classname}.

Return type

{classname}

digitize(bins: Union[list, tuple], **kwargs)[source]

Digitize image.

For more info see numpy.digitize().

Parameters
  • bins (list, tuple) – List of bin values. Must be monotonic and one-dimensional.

  • **kwargs – These parameters are passed to numpy.digitize().

Returns

New instance of {classname}.

Return type

{classname}

fft() Image[source]

Apply fourier transform to image.

Returns

Real component of fourier transform with the zero-frequency component shifted to the center of the spectrum.

Return type

{classname}

classmethod from_sitk_image(sitk_image) Image[source]

Return instance from SimpleITK.Image.

gaussian(sigma: int = 1, **kwargs)[source]

Apply Gaussian blur to image.

Parameters
Returns

New instance of {classname}.

Return type

{classname}

invert_contrast()[source]

Invert the contrast of the image.

Returns

out – Inverted image

Return type

{classname}

classmethod load(filename: PathLike, **kwargs) Image[source]

Load the data. Supported filetypes: .npy, .vol.

For memory mapping, use mmap_mode=’r’. Memory-mapped

files are used for accessing small segments of large files on disk, without reading the entire file into memory. Note that this can still result in some slow / unexpected behaviour with some operations.

More info: numpy.memmap()

Parameters
  • filename (PathLike) – Name of the file to load.

  • **kwargs – These parameters are passed on to data readers.

Returns

Instance of {classname}.

Return type

{classname}

Raises

IOError – Raised if the file extension is unknown.

normalize_values()[source]

Rescale values to 0.0 to 1.0.

Returns

out – Normalized image

Return type

{classname}

save(filename: PathLike)[source]

Save the data. Supported filetypes: .npy.

Parameters

filename (Pathlike) – Name of the file to save to.

threshold(method: str = 'otsu', **kwargs) float[source]

Compute threshold value using given method.

For more info, see skimage.filters

Parameters
  • method (str) – Thresholding method to use. Defaults to otsu.

  • **kwargs – These parameters are passed to threshold method.

Returns

threshold – Threshold value.

Return type

float

to_sitk_image()[source]

Return instance of SimpleITK.Image from {classname}.image().

class nanomesh.Plane(image: ndarray)[source]

Bases: Image

Data class for working with 2D image data.

Depending on the dimensions of the image data, the appropriate subclass will be chosen if possible.

Parameters

image ((i,j) numpy.array) – N-dimensional numpy array containing image data.

image

The raw image data

Type

(i,j) numpy.ndarray

Methods:

apply(function,Β **kwargs)

Apply function to Plane.image array.

astype(dtype)

Shortcut for np.ndarray.astype().

binary_digitize([threshold])

Convert into a binary image.

clear_border(*,Β object_label,Β fill_val,Β **kwargs)

Remove objects at the border of the image.

compare_with_digitized(digitized[,Β cmap])

Compare image with digitized (segmented) image.

compare_with_mesh(mesh)

Make a plot comparing the image with the given mesh.

compare_with_other(other[,Β cmap])

Compare image with other image.

crop(left,Β top,Β right,Β bottom)

Crop image to pixel indices.

crop_to_roi(bbox)

Crop plane to rectangle defined by bounding box.

digitize(bins,Β **kwargs)

Digitize image.

fft()

Apply fourier transform to image.

from_sitk_image(sitk_image)

Return instance from SimpleITK.Image.

gaussian([sigma])

Apply Gaussian blur to image.

generate_mesh(**kwargs)

Generate mesh from binary (segmented) image.

invert_contrast()

Invert the contrast of the image.

load(**kwargs)

Load the data.

normalize_values()

Rescale values to 0.0 to 1.0.

plot(*args,Β **kwargs)

Plot the image using matplotlib.

save(filename)

Save the data.

select_roi([from_points])

Select region of interest in interactive matplotlib figure.

show(*[,Β ax,Β title])

Plot the image using matplotlib.

threshold([method])

Compute threshold value using given method.

to_sitk_image()

Return instance of SimpleITK.Image from Plane.image().

try_all_threshold(**kwargs)

Produce a plot trying all available thresholds using skimage.filters.try_all_threshold().

apply(function: Callable, **kwargs)

Apply function to Plane.image array. Return an instance of Plane if the result is of the same dimensions, otherwise return the result of the operation.

Parameters
  • function (callable) – Function to apply to Plane.image.

  • **kwargs – Keyword arguments to pass to function.

Returns

New instance of Plane.

Return type

Plane

astype(dtype: str | np.dtype) np.ndarray

Shortcut for np.ndarray.astype().

binary_digitize(threshold: Optional[Union[float, str]] = None)

Convert into a binary image.

Parameters

threshold (float, optional) – Threshold used for segmentation. If given as a string, apply corresponding theshold via Plane.threshold(). Defaults to median.

Returns

New instance of Plane.

Return type

Plane

clear_border(*, object_label: int, fill_val: int, **kwargs) Plane[source]

Remove objects at the border of the image.

Parameters
Returns

New instance of Plane.

Return type

Plane

compare_with_digitized(digitized: Union[ndarray, Plane], cmap: Optional[str] = None, **kwargs) plt.Axes[source]

Compare image with digitized (segmented) image. Returns a plot with the overlay of the digitized image.

Parameters
Returns

ax

Return type

matplotlib.axes.Axes

compare_with_mesh(mesh: TriangleMesh) plt.Axes[source]

Make a plot comparing the image with the given mesh.

Parameters

mesh (TriangleMesh) – Mesh to compare the image with.

Return type

plt.Axes

compare_with_other(other: Union[ndarray, Plane], cmap: Optional[str] = None, **kwargs) plt.Axes[source]

Compare image with other image.

Parameters
Returns

ax

Return type

matplotlib.axes.Axes

crop(left: int, top: int, right: int, bottom: int) Plane[source]

Crop image to pixel indices.

Parameters
  • left (int) – Index of pixel delimiting cropping box.

  • top (int) – Index of pixel delimiting cropping box.

  • right (int) – Index of pixel delimiting cropping box.

  • bottom (int) – Index of pixel delimiting cropping box.

Returns

New instance of Plane.

Return type

Plane

crop_to_roi(bbox: ndarray) Plane[source]

Crop plane to rectangle defined by bounding box.

Parameters

bbox ((4,2) numpy.ndarray) – List of points describing region of interest. The bounding box may be rotated.

Returns

Cropped region as Plane object.

Return type

Plane

digitize(bins: Union[list, tuple], **kwargs)

Digitize image.

For more info see numpy.digitize().

Parameters
  • bins (list, tuple) – List of bin values. Must be monotonic and one-dimensional.

  • **kwargs – These parameters are passed to numpy.digitize().

Returns

New instance of Plane.

Return type

Plane

fft() Image

Apply fourier transform to image.

Returns

Real component of fourier transform with the zero-frequency component shifted to the center of the spectrum.

Return type

Plane

classmethod from_sitk_image(sitk_image) Image

Return instance from SimpleITK.Image.

gaussian(sigma: int = 1, **kwargs)

Apply Gaussian blur to image.

Parameters
Returns

New instance of Plane.

Return type

Plane

generate_mesh(**kwargs) TriangleMesh[source]

Generate mesh from binary (segmented) image.

Parameters

**kwargs – Keyword arguments are passed to nanomesh.plane2mesh()

Returns

mesh – Description of the mesh.

Return type

TriangleMesh

invert_contrast()

Invert the contrast of the image.

Returns

out – Inverted image

Return type

Plane

classmethod load(**kwargs) Image

Load the data. Supported filetypes: .npy, .vol.

For memory mapping, use mmap_mode=’r’. Memory-mapped

files are used for accessing small segments of large files on disk, without reading the entire file into memory. Note that this can still result in some slow / unexpected behaviour with some operations.

More info: numpy.memmap()

Parameters
  • filename (PathLike) – Name of the file to load.

  • **kwargs – These parameters are passed on to data readers.

Returns

Instance of Plane.

Return type

Plane

Raises

IOError – Raised if the file extension is unknown.

normalize_values()

Rescale values to 0.0 to 1.0.

Returns

out – Normalized image

Return type

Plane

plot(*args, **kwargs)[source]

Plot the image using matplotlib.

Parameters
Returns

ax – Instance of matplotlib.axes.Axes

Return type

matplotlib.axes.Axes

save(filename: PathLike)

Save the data. Supported filetypes: .npy.

Parameters

filename (Pathlike) – Name of the file to save to.

select_roi(from_points: Optional[ndarray] = None)[source]

Select region of interest in interactive matplotlib figure.

Parameters

from_points ((n, 2) numpy.ndarray, optional) – List of points that are used as anchors for the roi selection.

Returns

roi – Region of interest object. Bounding box is stored in roi.bbox.

Return type

nanomesh.image._roi2d.ROISelector

show(*, ax: Optional[Axes] = None, title: Optional[str] = None, **kwargs) plt.Axes[source]

Plot the image using matplotlib.

Parameters
Returns

ax – Instance of matplotlib.axes.Axes

Return type

matplotlib.axes.Axes

threshold(method: str = 'otsu', **kwargs) float

Compute threshold value using given method.

For more info, see skimage.filters

Parameters
  • method (str) – Thresholding method to use. Defaults to otsu.

  • **kwargs – These parameters are passed to threshold method.

Returns

threshold – Threshold value.

Return type

float

to_sitk_image()

Return instance of SimpleITK.Image from Plane.image().

try_all_threshold(**kwargs)[source]

Produce a plot trying all available thresholds using skimage.filters.try_all_threshold().

Parameters

**kwargs – These parameters are passed to skimage.filters.try_all_threshold().

class nanomesh.Volume(image: ndarray)[source]

Bases: Image

Data class for working with 3D (volumetric) image data..

Depending on the dimensions of the image data, the appropriate subclass will be chosen if possible.

Parameters

image ((i,j,k) numpy.array) – N-dimensional numpy array containing image data.

image

The raw image data

Type

(i,j,k) numpy.ndarray

Methods:

apply(function,Β **kwargs)

Apply function to Volume.image array.

astype(dtype)

Shortcut for np.ndarray.astype().

binary_digitize([threshold])

Convert into a binary image.

digitize(bins,Β **kwargs)

Digitize image.

fft()

Apply fourier transform to image.

from_sitk_image(sitk_image)

Return instance from SimpleITK.Image.

gaussian([sigma])

Apply Gaussian blur to image.

generate_mesh(**kwargs)

Generate mesh from binary (segmented) image.

invert_contrast()

Invert the contrast of the image.

load(**kwargs)

Load the data.

normalize_values()

Rescale values to 0.0 to 1.0.

plot(*args,Β **kwargs)

Shortcut for Volume.show().

save(filename)

Save the data.

select_plane([x,Β y,Β z])

Select a slice in the volume.

select_subvolume(*[,Β xs,Β ys,Β zs])

Select a subvolume from the current volume.

show([renderer])

Show volume using itkwidgets or ipyvolume.

show_slice(**kwargs)

Show slice using nanomesh.image.SliceViewer.

threshold([method])

Compute threshold value using given method.

to_sitk_image()

Return instance of SimpleITK.Image from Volume.image().

apply(function: Callable, **kwargs)

Apply function to Volume.image array. Return an instance of Volume if the result is of the same dimensions, otherwise return the result of the operation.

Parameters
  • function (callable) – Function to apply to Volume.image.

  • **kwargs – Keyword arguments to pass to function.

Returns

New instance of Volume.

Return type

Volume

astype(dtype: str | np.dtype) np.ndarray

Shortcut for np.ndarray.astype().

binary_digitize(threshold: Optional[Union[float, str]] = None)

Convert into a binary image.

Parameters

threshold (float, optional) – Threshold used for segmentation. If given as a string, apply corresponding theshold via Volume.threshold(). Defaults to median.

Returns

New instance of Volume.

Return type

Volume

digitize(bins: Union[list, tuple], **kwargs)

Digitize image.

For more info see numpy.digitize().

Parameters
  • bins (list, tuple) – List of bin values. Must be monotonic and one-dimensional.

  • **kwargs – These parameters are passed to numpy.digitize().

Returns

New instance of Volume.

Return type

Volume

fft() Image

Apply fourier transform to image.

Returns

Real component of fourier transform with the zero-frequency component shifted to the center of the spectrum.

Return type

Volume

classmethod from_sitk_image(sitk_image) Image

Return instance from SimpleITK.Image.

gaussian(sigma: int = 1, **kwargs)

Apply Gaussian blur to image.

Parameters
Returns

New instance of Volume.

Return type

Volume

generate_mesh(**kwargs) MeshContainer[source]

Generate mesh from binary (segmented) image.

Parameters

**kwargs – These parameters are passed to mesh3d.volume2mesh

Returns

Instance of MeshContainer

Return type

MeshContainer

invert_contrast()

Invert the contrast of the image.

Returns

out – Inverted image

Return type

Volume

classmethod load(**kwargs) Image

Load the data. Supported filetypes: .npy, .vol.

For memory mapping, use mmap_mode=’r’. Memory-mapped

files are used for accessing small segments of large files on disk, without reading the entire file into memory. Note that this can still result in some slow / unexpected behaviour with some operations.

More info: numpy.memmap()

Parameters
  • filename (PathLike) – Name of the file to load.

  • **kwargs – These parameters are passed on to data readers.

Returns

Instance of Volume.

Return type

Volume

Raises

IOError – Raised if the file extension is unknown.

normalize_values()

Rescale values to 0.0 to 1.0.

Returns

out – Normalized image

Return type

Volume

plot(*args, **kwargs)[source]

Shortcut for Volume.show().

save(filename: PathLike)

Save the data. Supported filetypes: .npy.

Parameters

filename (Pathlike) – Name of the file to save to.

select_plane(x: Optional[int] = None, y: Optional[int] = None, z: Optional[int] = None) Plane[source]

Select a slice in the volume. Either x, y or z must be specified.

Parameters
  • x (int, optional) – Index along the x-axis

  • y (int, optional) – Index along the y-axis

  • z (int, optional) – Index along the z-axis

Returns

Return plane as Plane.

Return type

Plane

Raises

ValueError – If none of the x, y, or z arguments have been specified

select_subvolume(*, xs: Optional[tuple] = None, ys: Optional[tuple] = None, zs: Optional[tuple] = None) Volume[source]

Select a subvolume from the current volume.

Each range must include a start and stop value, for example:

vol.select_subvolume(xs=(10, 20)) is equivalent to: vol.image[[:,:,10:20]

or

vol.select_subvolume(ys=(20, 25), zs=(40, 50)) is equivalent to: vol.image[[40:50,20:25,:]

Parameters
  • xs (tuple, optional) – Range to select along y-axis

  • ys (tuple, optional) – Range to select along y-axis

  • zs (tuple, optional) – Range to select along z-axis

Returns

Subvolume as Volume

Return type

Volume

show(renderer: str = 'itkwidgets', **kwargs) None[source]

Show volume using itkwidgets or ipyvolume.

Parameters
  • renderer (str, optional) – Select renderer (ipvolume, itkwidgets)

  • **kwargs – These parameters are passed to itkwidgets.view() or ipyvolume.quickvolshow().

Raises

ValueError – Raised if the renderer is unknown.

show_slice(**kwargs)[source]

Show slice using nanomesh.image.SliceViewer.

Extra arguments are passed on.

Parameters

**kwargs – These parameters are passed to nanomesh.image.SliceViewer

Return type

SliceViewer

threshold(method: str = 'otsu', **kwargs) float

Compute threshold value using given method.

For more info, see skimage.filters

Parameters
  • method (str) – Thresholding method to use. Defaults to otsu.

  • **kwargs – These parameters are passed to threshold method.

Returns

threshold – Threshold value.

Return type

float

to_sitk_image()

Return instance of SimpleITK.Image from Volume.image().