impy package

Subpackages

Submodules

impy.array_api module

class impy.array_api.XP[source]

Bases: object

setCupy() None[source]
setNumpy() None[source]
impy.array_api.cupy_dispatcher(function)[source]

impy.binder module

class impy.binder.bind(func: Callable = None, funcname: str = None, *, indtype=None, outdtype=None, kind: str = 'image', ndim: int | None = None)[source]

Bases: object

Dynamically define ImgArray function that can iterate over axes. You can integrate your own function, or useful functions from skimage or opencv. This class is designed as a kind of decorator class so that it can be used as decorator of any function or directly takes a function as the first argument.

Parameters:
  • func (callable) – Function to wrapped and bound to ImgArray.

  • funcname (str, optional) – Method name after set to ImgArray. The name of func itself will be set by default.

  • indtype (dtype, optional) – If given, input data type will be converted by as_img_type method before passed to func.

  • outdtype (dtype, optional) – If given, output data array will be defined in this type if needed.

  • kind (str, {"image", "property", "label", "label_binary"}, default is "image") –

    What kind of function will be bound.

    • ”image” … Given an image, calculate a new image that has the exactily same shape. Bound method will return ImgArray that has the same shape and axes as the input image.

    • ”property” … Given an image, calculate a scalar value or any other object such as

    tuple, and store them in a PropArray. Axes of returned PropArray is (the axes of input image) - (axes of spatial dimensions specified by dims argument of bound method). - “label” … Given an image, calculate a label image with value 0 being background and set it to labels attribute. The label image must have the exactly same shape as input image. - “label_binary” … Given an image, calculate a binary image. Label image is generated from the binary image with label method in LabeledArray. The connectivity is None. The binary image must have the exactly same shape as input image.

  • ndim ({None, 2, 3}, default is None) – Dimension of image that the original function supports. If None, then it is assumed to support both 2 and 3 dimensional images and automatically determined by the universal dims_to_spatial_axes method.

Examples

  1. Bind “normalize” method that will normalize images separately.

    >>> def normalize(img):
    >>>    min_, max_ = img.min(), img.max()
    >>>    return (img - min_)/(max_ - min_)
    >>> ip.bind(normalize, indtype=np.float32, outdtype=np.float32)
    >>> img = ip.imread(...)
    >>> img.normalize()
    

2. Bind a method calc_mean that calculate mean value around spatial dimensions. For one yx- or zyx-image, a scalar value is returned, so that calc_mean should return PropArray.

>>> ip.bind(np.mean, "calc_mean", outdtype=np.float32, kind="property")
>>> img = ip.imread(...)
>>> img.calc_mean()
  1. Wrap the normalize function in (1) in a decorator method.

    >>> @ip.bind(indtype=np.float32, outdtype=np.float32)
    >>> def normalize(img):
    >>>    min_, max_ = img.min(), img.max()
    >>>    return (img - min_)/(max_ - min_)
    >>> img = ip.imread(...)
    >>> img.normalize()
    

or if you think indtype and outdtype are unnecessary:

>>> @ip.bind
>>> def normalize(img):
>>>     ...

4. Bind custom percentile labeling function (although label_threshold method can do the exactly same thing).

>>> @ip.bind(kind="label_binary")
>>> def mylabel(img, p=90):
>>>     per = np.percentile(img, p)
>>>     thr = img > per
>>>     return thr
>>> img = ip.imread(...)
>>> img.mylabel(95)   # img.labels is added here
bound = {}
last_added = None

impy.collections module

class impy.collections.DataDict(d: dict[_K, _T] | None = None, **kwargs: dict[_K, _T])[source]

Bases: CollectionBase, MutableMapping[_K, _T]

Dictionary-like class that can call same method for every object containded in the values. Accordingly, DataDict cannot have objects with different types as values. It is checked every time constructor or __setitem__ method is called.

Examples

  1. Run Gaussian filter for every ImgArray. >>> imgs = DataDict(first=img1, second=img2) >>> out = imgs.gaussian_filter() # getattr is called for every image here. >>> out.first # return the first one.

  2. Find single molecules for every ImgArray. >>> imgs = DataDict([img1, img2, …]) >>> out = imgs.find_sm()

apply(func: Callable | str, *args, **kwargs)[source]

Apply same function to each components. It can be any callable objects or any method of the components.

Parameters:
  • func (Callable or str) – Function to be applied to each components.

  • args – Other arguments of func.

  • kwargs – Other keyword arguments of func.

Returns:

This list is composed of {“name0”: func(data[0]), “name1”: func(data[1]), …}

Return type:

DataDict

class impy.collections.DataList(iterable: Iterable[_T] = ())[source]

Bases: CollectionBase, MutableSequence[_T]

List-like class that can call same method for every object containded in it. Accordingly, DataList cannot have objects with different types. It is checked every time constructor or append method is called.

Examples

  1. Run Gaussian filter for every ImgArray. >>> imgs = DataList([img1, img2, …]) >>> out = imgs.gaussian_filter() # getattr is called for every image here.

  2. Find single molecules for every ImgArray. >>> imgs = DataList([img1, img2, …]) >>> out = imgs.find_sm()

agg(functions: Callable[[_T], Any] | Iterable[Callable[[_T], Any]])[source]
apply(func: Callable | str, *args, **kwargs) DataList[source]

Apply same function to each components. It can be any callable objects or any method of the components.

Parameters:
  • func (Callable or str) – Function to be applied to each components.

  • args – Other arguments of func.

  • kwargs – Other keyword arguments of func.

Returns:

This list is composed of [func(data[0]), func(data[1]), …]

Return type:

DataList

insert(key: int, component: _T) None[source]

S.insert(index, value) – insert value before index

impy.core module

impy.core.arange(stop: int, dtype: DTypeLike = None) ImgArray[source]

impy version of numpy.arange. This function has additional parameters axes and name. Original docstring follows.

axesstr, optional

Image axes. Must be same length as image dimension.

name: str, optional

Image name.

like: MetaArray, optional

Reference array from which name and axes will be copied.

arange([start,] stop[, step,], dtype=None, *, like=None)

Return evenly spaced values within a given interval.

arange can be called with a varying number of positional arguments:

  • arange(stop): Values are generated within the half-open interval [0, stop) (in other words, the interval including start but excluding stop).

  • arange(start, stop): Values are generated within the half-open interval [start, stop).

  • arange(start, stop, step) Values are generated within the half-open interval [start, stop), with spacing between values given by step.

For integer arguments the function is roughly equivalent to the Python built-in range, but returns an ndarray rather than a range instance.

When using a non-integer step, such as 0.1, it is often better to use numpy.linspace.

See the Warning sections below for more information.

Parameters:
  • start (integer or real, optional) – Start of interval. The interval includes this value. The default start value is 0.

  • stop (integer or real) – End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

  • step (integer or real, optional) – Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given.

  • dtype (dtype, optional) – The type of the output array. If dtype is not given, infer the data type from the other input arguments.

  • like (array_like, optional) –

    Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

    New in version 1.20.0.

Returns:

arange – Array of evenly spaced values.

For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.

Return type:

ndarray

Warning

The length of the output might not be numerically stable.

Another stability issue is due to the internal implementation of numpy.arange. The actual step value used to populate the array is dtype(start + step) - dtype(start) and not step. Precision loss can occur here, due to casting or due to using floating points when start is much larger than step. This can lead to unexpected behaviour. For example:

>>> np.arange(0, 5, 0.5, dtype=int)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> np.arange(-3, 3, 0.5, dtype=int)
array([-3, -2, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8])

In such cases, the use of numpy.linspace should be preferred.

The built-in range generates Python built-in integers that have arbitrary size, while numpy.arange produces numpy.int32 or numpy.int64 numbers. This may result in incorrect results for large integer values:

>>> power = 40
>>> modulo = 10000
>>> x1 = [(n ** power) % modulo for n in range(8)]
>>> x2 = [(n ** power) % modulo for n in np.arange(8)]
>>> print(x1)
[0, 1, 7776, 8801, 6176, 625, 6576, 4001]  # correct
>>> print(x2)
[0, 1, 7776, 7185, 0, 5969, 4816, 3361]  # incorrect

See also

numpy.linspace

Evenly spaced numbers with careful handling of endpoints.

numpy.ogrid

Arrays of evenly spaced numbers in N-dimensions.

numpy.mgrid

Grid-shaped arrays of evenly spaced numbers in N-dimensions.

how-to-partition

Examples

>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0.,  1.,  2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
impy.core.array(arr: ArrayLike, /, dtype: DTypeLike = None, *, copy: bool = True, name: str = None, axes: str = None, like: MetaArray | None = None) ImgArray[source]

make an ImgArray object, like np.array(x)

Parameters:
  • arr (array-like) – Base array.

  • copy (bool, default is True) – If True, a copy of the original array is made.

  • dtype (data type, optional) – Image data type.

  • name (str, optional) – Name of image.

  • axes (str, optional) – Image axes.

Return type:

ImgArray

impy.core.asarray(arr: ArrayLike, dtype: DTypeLike | None = None, *, name: str | None = None, axes: str | None = None, like: MetaArray | None = None) ImgArray[source]

make an ImgArray object, like np.asarray(x)

Parameters:
  • arr (array-like) – Base array.

  • dtype (data type, optional) – Image data type.

  • name (str, optional) – Name of image.

  • axes (str, optional) – Image axes.

  • copy (bool, default is True) – If True, a copy of the original array is made.

Return type:

ImgArray

impy.core.asbigarray(arr: ArrayLike, dtype: DTypeLike = None, *, name: str | None = None, axes: str | None = None, like: MetaArray | None = None) BigImgArray[source]

Make an BigImgArray object from other types of array.

Parameters:
  • arr (array-like) – Base array.

  • {}

Return type:

BigImgArray

impy.core.aslabel(arr: ArrayLike, dtype: DTypeLike = None, *, name: str | None = None, axes: str | None = None, like: MetaArray | None = None) ImgArray[source]

Make an Label object.

This function helps to create a Label object from an array. Dtype check is performed on array creation.

Parameters:
  • arr (array-like) – Base array.

  • dtype (data type, optional) – Image data type.

  • name (str, optional) – Name of image.

  • axes (str, optional) – Image axes.

Return type:

Label

impy.core.aslazy(*args, **kwargs) LazyImgArray[source]
impy.core.big_imread(path: str, chunks='auto', *, name: str | None = None, squeeze: bool = False) BigImgArray[source]

Read an image lazily. Image file is first opened as an memory map, and subsequently converted to numpy.ndarray or cupy.ndarray chunkwise by dask.array.map_blocks.

Parameters:
  • path (str) – Path to the file.

  • chunks (optional) – Specify chunk sizes. By default, yx-axes are assigned to the same chunk for every slice of image, whild chunk sizes of the rest of axes are automatically set with “auto” option.

  • name (str, optional) – Name of array.

  • squeeze (bool, default is False) – If True and there is one-sized axis, then call np.squeeze.

Return type:

BigImgArray

impy.core.broadcast_arrays(*arrays: MetaArray) list[impy.arrays.bases.metaarray.MetaArray][source]

Broadcast input arrays to the same shape and axes

impy.core.circular_mask(radius: nDFloat, shape: ShapeLike, center: Literal['center'] | tuple[float, ...] = 'center', soft: bool = False, out_value: bool = True) ImgArray[source]

Make a circular or ellipsoid shaped mask. Region close to center will be filled with False.

Parameters:
  • radius (float or array-like) – Radius of non-mask region

  • shape (tuple) – Shape of mask.

  • center (tuple or "center") – Center of circle. By default circle locates at the center.

Returns:

Boolean image with zyx or yx axes

Return type:

ImgArray

impy.core.empty(shape: ShapeLike, dtype: DTypeLike = <class 'numpy.uint16'>, *, name: str | None = None, axes: AxesLike | None = None, like: MetaArray | None = None) ImgArray[source]

impy version of numpy.empty. This function has additional parameters axes and name. Original docstring follows.

axesstr, optional

Image axes. Must be same length as image dimension.

name: str, optional

Image name.

like: MetaArray, optional

Reference array from which name and axes will be copied.

empty(shape, dtype=float, order=’C’, *, like=None)

Return a new array of given shape and type, without initializing entries.

Parameters:
  • shape (int or tuple of int) – Shape of the empty array, e.g., (2, 3) or 2.

  • dtype (data-type, optional) – Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64.

  • order ({'C', 'F'}, optional, default: 'C') – Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.

  • like (array_like, optional) –

    Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

    New in version 1.20.0.

Returns:

out – Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

Return type:

ndarray

See also

empty_like

Return an empty array with shape and type of input.

ones

Return a new array setting values to one.

zeros

Return a new array setting values to zero.

full

Return a new array of given shape filled with value.

Notes

empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.

Examples

>>> np.empty([2, 2])
array([[ -9.74499359e+001,   6.69583040e-309],
       [  2.13182611e-314,   3.06959433e-309]])         #uninitialized
>>> np.empty([2, 2], dtype=int)
array([[-1073741821, -1067949133],
       [  496041986,    19249760]])                     #uninitialized
impy.core.full(shape: ShapeLike, fill_value: Any, dtype: DTypeLike = <class 'numpy.uint16'>, *, name: str | None = None, axes: AxesLike | None = None, like: MetaArray | None = None) ImgArray[source]

impy version of numpy.full. This function has additional parameters axes and name. Original docstring follows.

axesstr, optional

Image axes. Must be same length as image dimension.

name: str, optional

Image name.

like: MetaArray, optional

Reference array from which name and axes will be copied.

Return a new array of given shape and type, filled with fill_value.

Parameters:
  • shape (int or sequence of ints) – Shape of the new array, e.g., (2, 3) or 2.

  • fill_value (scalar or array_like) – Fill value.

  • dtype (data-type, optional) –

    The desired data-type for the array The default, None, means

    np.array(fill_value).dtype.

  • order ({'C', 'F'}, optional) – Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.

  • like (array_like, optional) –

    Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

    New in version 1.20.0.

Returns:

out – Array of fill_value with the given shape, dtype, and order.

Return type:

ndarray

See also

full_like

Return a new array with shape of input filled with value.

empty

Return a new uninitialized array.

ones

Return a new array setting values to one.

zeros

Return a new array setting values to zero.

Examples

>>> np.full((2, 2), np.inf)
array([[inf, inf],
       [inf, inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
       [10, 10]])
>>> np.full((2, 2), [1, 2])
array([[1, 2],
       [1, 2]])
impy.core.gaussian_kernel(shape: ShapeLike, sigma: nDFloat = 1.0, peak: float = 1.0, *, name: str | None = None, axes: AxesLike | None = None) ImgArray[source]

Make an Gaussian kernel or Gaussian image.

Parameters:
  • shape (tuple of int) – Shape of image.

  • sigma (float or array-like, default is 1.0) – Standard deviation of Gaussian.

  • peak (float, default is 1.0) – Peak intensity.

Returns:

Gaussian image

Return type:

ImgArray

impy.core.imread(path: str, dtype: DTypeLike = None, key: AxesTargetedSlicer | None = None, *, name: str | None = None, squeeze: bool = False) ImgArray[source]

Load image(s) from a path. You can read list of images from directories with wildcards or "$" in path.

Parameters:
  • path (str) – Path to the image or directory.

  • dtype (Any type that np.dtype accepts) – Data type of images.

  • key (AxesTargetedSlicer, optional) – If not None, image is read in a memory-mapped array first, and only img[key] is returned. Only axis-targeted slicing is supported. This argument is important when reading a large file.

  • name (str, optional) – Name of array.

  • squeeze (bool, default is False) – If True, redundant dimensions will be squeezed.

Returns:

Image data read from the file.

Return type:

ImgArray

Examples

Read a part of an image

>>> path = "path/to/image.mrc"
>>> %time ip.imread(path)["x=:10;y=:10"]
Wall time: 136 ms
>>> %time ip.imread(path, key="x=:10;y=:10")
Wall time: 3.01 ms
impy.core.imread_collection(path: str | list[str], filt: Callable[[ndarray], bool] | None = None) DataList[source]

Open images as ImgArray and store them in DataList.

Parameters:
  • path (str or list of str) – Path than can be passed to glob.glob. If a list of path is given, all the matched images will be read and concatenated into a DataList.

  • filt (callable, optional) – If specified, only images that satisfies filt(img)==True will be stored in the returned DataList.

Return type:

DataList

impy.core.indices(dimensions: ShapeLike, dtype: DTypeLike = <class 'numpy.uint16'>, *, name: str | None = None, axes: AxesLike | None = None, like: MetaArray | None = None) AxesTuple[ImgArray][source]

Copy of numpy.indices.

Parameters:
  • dimensions (shape-like) – The shape of the grid.

  • dtype (dtype, optional) – Data type of the result.

  • name (str, optional) – Name of the result arrays.

  • axes (AxesLike, optional) – Axes of the result arrays.

  • like (MetaArray, optional) – Reference array from which name and axes will be copied.

Return type:

tuple of ImgArray

impy.core.lazy_imread(*args, **kwargs) LazyImgArray[source]
impy.core.ones(shape: ShapeLike, dtype: DTypeLike = <class 'numpy.uint16'>, *, name: str | None = None, axes: AxesLike | None = None, like: MetaArray | None = None) ImgArray[source]

impy version of numpy.ones. This function has additional parameters axes and name. Original docstring follows.

axesstr, optional

Image axes. Must be same length as image dimension.

name: str, optional

Image name.

like: MetaArray, optional

Reference array from which name and axes will be copied.

Return a new array of given shape and type, filled with ones.

Parameters:
  • shape (int or sequence of ints) – Shape of the new array, e.g., (2, 3) or 2.

  • dtype (data-type, optional) – The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.

  • order ({'C', 'F'}, optional, default: C) – Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.

  • like (array_like, optional) –

    Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

    New in version 1.20.0.

Returns:

out – Array of ones with the given shape, dtype, and order.

Return type:

ndarray

See also

ones_like

Return an array of ones with shape and type of input.

empty

Return a new uninitialized array.

zeros

Return a new array setting values to zero.

full

Return a new array of given shape filled with value.

Examples

>>> np.ones(5)
array([1., 1., 1., 1., 1.])
>>> np.ones((5,), dtype=int)
array([1, 1, 1, 1, 1])
>>> np.ones((2, 1))
array([[1.],
       [1.]])
>>> s = (2,2)
>>> np.ones(s)
array([[1.,  1.],
       [1.,  1.]])
impy.core.read_meta(path: str) dict[str, Any][source]

Read the metadata of an image file.

Parameters:

path (str) – Path to the image file.

Returns:

Dictionary of keys {“axes”, “scale”, “metadata”}

Return type:

dict

impy.core.roiread(path: str) RoiList[source]

Read a Roi.zip file as a RoiList object.

impy.core.sample_image(name: str) ImgArray[source]

Get sample images from skimage and convert it into ImgArray.

Parameters:

name (str) – Name of sample image, such as “camera”.

Returns:

Sample image.

Return type:

ImgArray

impy.core.zeros(shape: ShapeLike, dtype: DTypeLike = <class 'numpy.uint16'>, *, name: str | None = None, axes: AxesLike | None = None, like: MetaArray | None = None) ImgArray[source]

impy version of numpy.zeros. This function has additional parameters axes and name. Original docstring follows.

axesstr, optional

Image axes. Must be same length as image dimension.

name: str, optional

Image name.

like: MetaArray, optional

Reference array from which name and axes will be copied.

zeros(shape, dtype=float, order=’C’, *, like=None)

Return a new array of given shape and type, filled with zeros.

Parameters:
  • shape (int or tuple of ints) – Shape of the new array, e.g., (2, 3) or 2.

  • dtype (data-type, optional) – The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.

  • order ({'C', 'F'}, optional, default: 'C') – Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.

  • like (array_like, optional) –

    Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

    New in version 1.20.0.

Returns:

out – Array of zeros with the given shape, dtype, and order.

Return type:

ndarray

See also

zeros_like

Return an array of zeros with shape and type of input.

empty

Return a new uninitialized array.

ones

Return a new array setting values to one.

full

Return a new array of given shape filled with value.

Examples

>>> np.zeros(5)
array([ 0.,  0.,  0.,  0.,  0.])
>>> np.zeros((5,), dtype=int)
array([0, 0, 0, 0, 0])
>>> np.zeros((2, 1))
array([[ 0.],
       [ 0.]])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)],
      dtype=[('x', '<i4'), ('y', '<i4')])

impy.correlation module

impy.correlation.fourier_ncc(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, squeeze: bool = True, *, dims: Sequence[str | Axis] | int | None = None) PropArray | float[source]

Normalized Cross Correlation in Fourier space.

Parameters:
maskboolean ImgArray, optional

If provided, True regions will be masked and will not be taken into account when calculate correlation.

squeezebool, default is True

If True, the redundant axis will be deleted. Array with sinl0gle value will be converted to a scalar.

dimsstr or int, optional

Spatial dimensions. If string is given, each symbol is interpeted as an axis name of spatial dimensions. If an integer is given, it is interpreted as the number of spatial dimensions. For instance, dims="yx" means axes "y" and "x" are spatial dimensions and function is applied to other axes, say, "t" and/or "c". dims=3 is equivalent to dims="zyx".

Returns:

Correlation value(s).

Return type:

PropArray or float

impy.correlation.fourier_shell_correlation(img0: ImgArray, img1: ImgArray, dfreq: float = 0.02) tuple[numpy.ndarray, numpy.ndarray]

Calculate Fourier Shell Correlation (FSC; or Fourier Ring Correlation, FRC, for 2-D images) between two images. FSC is defined as:

\[FSC(r) = \frac{Re(\sum_{r<r'<r+dr}[F_0(r') \cdot \bar{F_1}(r)])} {\sqrt{\sum_{r<r'<r+dr}|F_0(r')|^2 \cdot \sum_{r<r'<r+dr}|F_1(r')|^2}}\]

In this function, frequency domain will be binned like this:

|---|---|---|---|---|
0  0.1 0.2 0.3 0.4 0.5

and frequencies calculated in each bin will be 0.05, 0.15, …, 0.45.

Parameters:
dfreqfloat, default is 0.02

Difference of frequencies. This value will be the width of bins.

Returns:

The first array is frequency, and the second array is FSC.

Return type:

Two np.ndarray

impy.correlation.fourier_zncc(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, squeeze: bool = True, *, dims: Sequence[str | Axis] | int | None = None) PropArray | float[source]

Zero-mean Normalized Cross Correlation in Fourier space.

Parameters:
maskboolean ImgArray, optional

If provided, True regions will be masked and will not be taken into account when calculate correlation.

squeezebool, default is True

If True, the redundant axis will be deleted. Array with sinl0gle value will be converted to a scalar.

dimsstr or int, optional

Spatial dimensions. If string is given, each symbol is interpeted as an axis name of spatial dimensions. If an integer is given, it is interpreted as the number of spatial dimensions. For instance, dims="yx" means axes "y" and "x" are spatial dimensions and function is applied to other axes, say, "t" and/or "c". dims=3 is equivalent to dims="zyx".

Returns:

Correlation value(s).

Return type:

PropArray or float

impy.correlation.fsc(img0: ImgArray, img1: ImgArray, dfreq: float = 0.02) tuple[numpy.ndarray, numpy.ndarray][source]

Calculate Fourier Shell Correlation (FSC; or Fourier Ring Correlation, FRC, for 2-D images) between two images. FSC is defined as:

\[FSC(r) = \frac{Re(\sum_{r<r'<r+dr}[F_0(r') \cdot \bar{F_1}(r)])} {\sqrt{\sum_{r<r'<r+dr}|F_0(r')|^2 \cdot \sum_{r<r'<r+dr}|F_1(r')|^2}}\]

In this function, frequency domain will be binned like this:

|---|---|---|---|---|
0  0.1 0.2 0.3 0.4 0.5

and frequencies calculated in each bin will be 0.05, 0.15, …, 0.45.

Parameters:
dfreqfloat, default is 0.02

Difference of frequencies. This value will be the width of bins.

Returns:

The first array is frequency, and the second array is FSC.

Return type:

Two np.ndarray

impy.correlation.ft_pcc_landscape(img0: ImgArray, img1: ImgArray, max_shifts: int | tuple[int, ...] | None = None)[source]

Create landscape of phase cross correlation.

This function takes Fourier transformed images as input. If you have to repetitively use a same template image, this function is faster.

Parameters:
max_shiftsfloat, tuple of float, optional

Maximum shifts in each dimension. If a single scalar is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Landscape image.

Return type:

ImgArray

impy.correlation.ft_pcc_maximum(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, upsample_factor: int = 10, max_shifts: float | tuple[float, ...] | None = None) ndarray[source]

Calculate lateral shift between two images using phase cross correlation.

This function takes Fourier transformed images as input. If you have to repetitively use a same template image, this function is faster.

Parameters:
upsample_factorint, default is 10

Up-sampling factor when calculating phase cross correlation.

max_shiftsfloat, tuple of float, optional

Maximum shifts in each dimension. If a single scalar is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Shift in pixel.

Return type:

np.ndarray

impy.correlation.ft_pcc_maximum_with_corr(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, upsample_factor: int = 10, max_shifts: float | tuple[float, ...] | None = None) ndarray[source]

Calculate lateral shift between two images using phase cross correlation.

This function takes Fourier transformed images as input. If you have to repetitively use a same template image, this function is faster.

Parameters:
upsample_factorint, default is 10

Up-sampling factor when calculating phase cross correlation.

max_shiftsfloat, tuple of float, optional

Maximum shifts in each dimension. If a single scalar is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Shift in pixel and phase cross correlation.

Return type:

np.ndarray and float

impy.correlation.manders_coloc(img0: ImgArray, img1: ndarray, *, squeeze: bool = True, dims: Sequence[str | Axis] | int | None = None) PropArray | float[source]

Manders’ correlation coefficient. This is defined as following:

\(r = \frac{\sum_{i \in I_{ref}} I_i}{\sum_{i} I_i}\)

This value is NOT independent of background intensity. You need to correctly subtract background from self. This value is NOT interchangable between channels.

Parameters:
  • img0 (ImgArray) – First image.

  • img1 (ImgArray) – Second image.

  • squeeze (bool, default is True) – If True, the redundant axis will be deleted. Array with sinl0gle value will be converted to a scalar.

  • dims (str or int, optional) – Spatial dimensions. If string is given, each symbol is interpeted as an axis name of spatial dimensions. If an integer is given, it is interpreted as the number of spatial dimensions. For instance, dims="yx" means axes "y" and "x" are spatial dimensions and function is applied to other axes, say, "t" and/or "c". dims=3 is equivalent to dims="zyx".

Returns:

Correlation coefficient(s).

Return type:

PropArray or float

impy.correlation.ncc(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, squeeze: bool = True, *, dims: Sequence[str | Axis] | int | None = None) PropArray | float[source]

Normalized Cross Correlation.

Parameters:
maskboolean ImgArray, optional

If provided, True regions will be masked and will not be taken into account when calculate correlation.

squeezebool, default is True

If True, the redundant axis will be deleted. Array with sinl0gle value will be converted to a scalar.

dimsstr or int, optional

Spatial dimensions. If string is given, each symbol is interpeted as an axis name of spatial dimensions. If an integer is given, it is interpreted as the number of spatial dimensions. For instance, dims="yx" means axes "y" and "x" are spatial dimensions and function is applied to other axes, say, "t" and/or "c". dims=3 is equivalent to dims="zyx".

Returns:

Correlation value(s).

Return type:

PropArray or float

impy.correlation.nmi(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, bins: int = 100, squeeze: bool = True, *, dims: Sequence[str | Axis] | int | None = None) PropArray | float[source]

Normalized Mutual Information.

\(Y(A, B) = \frac{H(A) + H(B)}{H(A, B)}\)

See “Elegant SciPy”

Parameters:
maskboolean ImgArray, optional

If provided, True regions will be masked and will not be taken into account when calculate correlation.

binsint, default is 100

Number of bins to construct histograms.

squeezebool, default is True

If True, the redundant axis will be deleted. Array with sinl0gle value will be converted to a scalar.

dimsstr or int, optional

Spatial dimensions. If string is given, each symbol is interpeted as an axis name of spatial dimensions. If an integer is given, it is interpreted as the number of spatial dimensions. For instance, dims="yx" means axes "y" and "x" are spatial dimensions and function is applied to other axes, say, "t" and/or "c". dims=3 is equivalent to dims="zyx".

Returns:

Correlation value(s).

Return type:

PropArray or float

impy.correlation.pcc_landscape(img0: ImgArray, img1: ImgArray, max_shifts: int | tuple[int, ...] | None = None)[source]

Create landscape of phase cross correlation.

Parameters:
max_shiftsfloat, tuple of float, optional

Maximum shifts in each dimension. If a single scalar is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Landscape image.

Return type:

ImgArray

impy.correlation.pcc_maximum(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, upsample_factor: int = 10, max_shifts: int | tuple[int, ...] | None = None) ndarray[source]

Calculate lateral shift between two images using phase cross correlation.

Same as skimage.registration.phase_cross_correlation but some additional parameters are supported.

Parameters:
upsample_factorint, default is 10

Up-sampling factor when calculating phase cross correlation.

max_shiftsint, tuple of int, optional

Maximum shifts in each dimension. If a single integer is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Shift in pixel.

Return type:

np.ndarray

impy.correlation.pcc_maximum_with_corr(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, upsample_factor: int = 10, max_shifts: int | tuple[int, ...] | None = None) ndarray[source]

Calculate lateral shift between two images using phase cross correlation.

Same as skimage.registration.phase_cross_correlation but some additional parameters are supported.

Parameters:
upsample_factorint, default is 10

Up-sampling factor when calculating phase cross correlation.

max_shiftsint, tuple of int, optional

Maximum shifts in each dimension. If a single integer is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Shift in pixel and phase cross correlation

Return type:

np.ndarray and float

impy.correlation.pearson_coloc(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, squeeze: bool = True, *, dims: Sequence[str | Axis] | int | None = None) PropArray | float

Zero-mean Normalized Cross Correlation.

Parameters:
maskboolean ImgArray, optional

If provided, True regions will be masked and will not be taken into account when calculate correlation.

squeezebool, default is True

If True, the redundant axis will be deleted. Array with sinl0gle value will be converted to a scalar.

dimsstr or int, optional

Spatial dimensions. If string is given, each symbol is interpeted as an axis name of spatial dimensions. If an integer is given, it is interpreted as the number of spatial dimensions. For instance, dims="yx" means axes "y" and "x" are spatial dimensions and function is applied to other axes, say, "t" and/or "c". dims=3 is equivalent to dims="zyx".

Returns:

Correlation value(s).

Return type:

PropArray or float

impy.correlation.polar_pcc_maximum(img0: ImgArray, img1: ImgArray, upsample_factor: int = 10, max_degree: int = None) float[source]

Calculate rotational shift between two images using polar Fourier transformation.

Parameters:
upsample_factorint, default is 10

Up-sampling factor when calculating phase cross correlation.

max_degreeint, tuple of int, optional

Maximum rotation in degree.

Returns:

Rotation in degree

Return type:

float

impy.correlation.polar_pcc_maximum_with_corr(img0: ImgArray, img1: ImgArray, upsample_factor: int = 10, max_degree: int = None) float[source]

Calculate rotational shift between two images using polar Fourier transformation.

Parameters:
upsample_factorint, default is 10

Up-sampling factor when calculating phase cross correlation.

max_degreeint, tuple of int, optional

Maximum rotation in degree.

Returns:

Rotation in degree and phase cross correlation

Return type:

float and float

impy.correlation.zncc(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, squeeze: bool = True, *, dims: Sequence[str | Axis] | int | None = None) PropArray | float[source]

Zero-mean Normalized Cross Correlation.

Parameters:
maskboolean ImgArray, optional

If provided, True regions will be masked and will not be taken into account when calculate correlation.

squeezebool, default is True

If True, the redundant axis will be deleted. Array with sinl0gle value will be converted to a scalar.

dimsstr or int, optional

Spatial dimensions. If string is given, each symbol is interpeted as an axis name of spatial dimensions. If an integer is given, it is interpreted as the number of spatial dimensions. For instance, dims="yx" means axes "y" and "x" are spatial dimensions and function is applied to other axes, say, "t" and/or "c". dims=3 is equivalent to dims="zyx".

Returns:

Correlation value(s).

Return type:

PropArray or float

impy.correlation.zncc_landscape(img0: ImgArray, img1: ImgArray, max_shifts: int | tuple[int, ...] | None = None)[source]

Create landscape of zero-mean normalized cross correlation.

Parameters:
max_shiftsfloat, tuple of float, optional

Maximum shifts in each dimension. If a single scalar is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Landscape image.

Return type:

ImgArray

impy.correlation.zncc_maximum(img0: ImgArray, img1: ImgArray, upsample_factor: int = 10, max_shifts: int | tuple[int, ...] | None = None) ndarray[source]

Calculate lateral shift between two images using zero-mean normalized cross correlation.

Similar to pcc_maximum(), this function can determine shift at sub-pixel precision. Since ZNCC uses real space, this function performs better than PCC when the input images have frequency loss. Unlike zncc_maximum_with_corr(), this function only returns the optimal shift. :param img0: First image. :type img0: ImgArray :param img1: Second image. :type img1: ImgArray

upsample_factorint, default is 10

Up-sampling factor when calculating cross correlation. Convolution image will be up-sampled by third-order interpolation.

max_shiftsfloat, tuple of float, optional

Maximum shifts in each dimension. If a single scalar is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Shift in pixel .

Return type:

np.ndarray

impy.correlation.zncc_maximum_with_corr(img0: ImgArray, img1: ImgArray, upsample_factor: int = 10, max_shifts: int | tuple[int, ...] | None = None) tuple[numpy.ndarray, float][source]

Calculate lateral shift between two images using zero-mean normalized cross correlation.

Similar to pcc_maximum(), this function can determine shift at sub-pixel precision. Since ZNCC uses real space, this function performs better than PCC when the input images have frequency loss. :param img0: First image. :type img0: ImgArray :param img1: Second image. :type img1: ImgArray

upsample_factorint, default is 10

Up-sampling factor when calculating cross correlation. Convolution image will be up-sampled by third-order interpolation.

max_shiftsfloat, tuple of float, optional

Maximum shifts in each dimension. If a single scalar is given, it is interpreted as maximum shifts in all dimensions. No upper bound of shifts if not given.

Returns:

Shift in pixel and ZNCC value.

Return type:

np.ndarray and float

impy.io module

impy.io.imread(path: str, memmap: bool = False) ImageData

Read an image file.

The reader is chosen according to the file extension.

Parameters:
  • path (str) – File path of an image.

  • memmap (bool, default is False) – Read image as a memory-mapped-like state.

Returns:

Image data tuple.

Return type:

ImageData

impy.io.imread_dask(path: str, chunks: Any) ImageData

Read an image file as a dask array.

The reader is chosen according to the file extension.

Parameters:
  • path (str) – File path of an image.

  • chunks (Any) – Parameter that will be passed to dask.array.from_array or dask.array.from_zarr function.

Returns:

Image data tuple.

Return type:

ImageData

impy.io.imsave(path: str, img: ImpyArray, lazy: bool = False) None
impy.io.mark_reader(*ext: str) Callable[[_R], _R]

Mark a function as a reader function.

Examples

>>> @IO.mark_reader(".tif")
>>> def read_tif(path, memmap=False):
>>>     ...
impy.io.mark_writer(*ext: str) Callable[[_R], _R]

Mark a function as a writer function.

Examples

>>> @IO.mark_writer(".tif")
>>> def save_tif(path, img, lazy=False):
>>>     ...

impy.random module

class impy.random.ImageGenerator(rng: Generator)[source]

Bases: object

normal(loc: float | ndarray = 0.0, scale: float | ndarray = 1.0, size: int | tuple[int, ...] | None = None, *, axes: Iterable[str | Axis] | None = None, name: str | None = None, like: MetaArray | LazyImgArray = None) ImgArray[source]
poisson(lam: float, size: int | tuple[int, ...] | None = None, *, axes: Iterable[str | Axis] | None = None, name: str | None = None, like: MetaArray | LazyImgArray = None) ImgArray[source]
random(size: int | tuple[int, ...] | None = None, dtype=None, *, axes: Iterable[str | Axis] | None = None, name: str | None = None, like: MetaArray | LazyImgArray = None) ImgArray[source]
random_uint16(size, *, name: str = None, axes: str = None, like: MetaArray | LazyImgArray = None) ImgArray[source]
random_uint8(size: int | tuple[int], *, name: str = None, axes: str = None, like: MetaArray | LazyImgArray = None) ImgArray[source]
standard_exponential(size: int | tuple[int, ...] | None = None, dtype=None, method: Literal['zig', 'inv'] = None, *, axes: Iterable[str | Axis] | None = None, name: str | None = None, like: MetaArray | LazyImgArray = None) ImgArray[source]
standard_normal(size: int | tuple[int, ...] | None = None, dtype=None, *, axes: Iterable[str | Axis] | None = None, name: str | None = None, like: MetaArray | LazyImgArray = None) ImgArray[source]
impy.random.default_rng(seed) ImageGenerator[source]

Get the default random number generator.

impy.random.normal(loc=0.0, scale=1.0, size=None)[source]

Draw random samples from a normal (Gaussian) distribution.

The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2], is often called the bell curve because of its characteristic shape (see the example below).

The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2].

Note

New code should use the ~numpy.random.Generator.normal method of a ~numpy.random.Generator instance instead; please see the random-quick-start.

Parameters:
  • loc (float or array_like of floats) – Mean (“centre”) of the distribution.

  • scale (float or array_like of floats) – Standard deviation (spread or “width”) of the distribution. Must be non-negative.

  • size (int or tuple of ints, optional) – Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

Returns:

out – Drawn samples from the parameterized normal distribution.

Return type:

ndarray or scalar

See also

scipy.stats.norm

probability density function, distribution or cumulative density function, etc.

random.Generator.normal

which should be used for new code.

Notes

The probability density for the Gaussian distribution is

\[p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },\]

where \(\mu\) is the mean and \(\sigma\) the standard deviation. The square of the standard deviation, \(\sigma^2\), is called the variance.

The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at \(x + \sigma\) and \(x - \sigma\) [2]). This implies that normal is more likely to return samples lying close to the mean, rather than those far away.

References

Examples

Draw samples from the distribution:

>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)

Verify the mean and the variance:

>>> abs(mu - np.mean(s))
0.0  # may vary
>>> abs(sigma - np.std(s, ddof=1))
0.1  # may vary

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
...          linewidth=2, color='r')
>>> plt.show()

Two-by-four array of samples from the normal distribution with mean 3 and standard deviation 2.5:

>>> np.random.normal(3, 2.5, size=(2, 4))
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],   # random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]])  # random
impy.random.random(size=None)[source]

Return random floats in the half-open interval [0.0, 1.0). Alias for random_sample to ease forward-porting to the new random API.

impy.random.random_uint16(size, *, name: str = None, axes: str = None, like: MetaArray | LazyImgArray = None) ImgArray[source]

Return a random uint16 image, ranging 0-65535.

Parameters:
  • size (int or tuple of int) – Image shape.

  • name (str, optional) – Image name.

  • axes (str, optional) – Image axes.

Returns:

Random Image in dtype np.uint16.

Return type:

ImgArray

impy.random.random_uint8(size: int | tuple[int], *, name: str = None, axes: str = None, like: MetaArray | LazyImgArray = None) ImgArray[source]

Return a random uint8 image, ranging 0-255.

Parameters:
  • size (int or tuple of int) – Image shape.

  • name (str, optional) – Image name.

  • axes (str, optional) – Image axes.

Returns:

Random Image in dtype np.uint8.

Return type:

ImgArray

impy.roi module

class impy.roi.LineRoi(data: ArrayLike, axes: AxesLike, multi_dims: ArrayLike | None = None)[source]

Bases: PolyLineRoi

class impy.roi.PointRoi(data: ArrayLike, axes: AxesLike, multi_dims: ArrayLike | None = None)[source]

Bases: Roi

class impy.roi.PolyLineRoi(data: ArrayLike, axes: AxesLike, multi_dims: ArrayLike | None = None)[source]

Bases: Roi

class impy.roi.PolygonRoi(data: ArrayLike, axes: AxesLike, multi_dims: ArrayLike | None = None)[source]

Bases: Roi

static get_coordinates(coords: ndarray)[source]

Convert coordinates.

class impy.roi.RectangleRoi(data: ArrayLike, axes: AxesLike, multi_dims: ArrayLike | None = None)[source]

Bases: PolygonRoi

class impy.roi.Roi(data: ArrayLike, axes: AxesLike, multi_dims: ArrayLike | None = None)[source]

Bases: object

Base class for ImageJ ROI types.

This class adds slice covariancy and axes to the ROI objects. Basically, a Roi object is conposed of a spatial dimensions (stored in _data) and extra-dimensions (stored in _multi_dims).

property axes: Axes

Roi axes.

copy() Self[source]

Make a copy of the ROI.

drop(axis: int | str | Axis)[source]

Drop an axis from the ROI.

classmethod from_imagejroi(roi: ImagejRoi) Self[source]

Construct a Roi from an roifile.ImagejRoi object.

static get_coordinates(coords: ndarray)[source]

Convert coordinates.

property n_spatial_dims: int
property ndim: int
plot(ax=None, **kwargs)[source]
class impy.roi.RoiList(axes: Iterable[str | Axis], rois: Iterable[Roi] = ())[source]

Bases: MutableSequence[Roi]

A list of ROIs.

property axes: Axes

RoiList axes.

drop(axis: int | str | Axis)[source]

Drop an axis from all the ROIs.

classmethod fromfile(path: str) Self[source]

Construct a RoiList from a file.

Parameters:

path (str) – Path to the ROI file.

Returns:

A RoiList object with the ROIs read from the file.

Return type:

RoiList

insert(index: int, roi: Roi)[source]

Insert a ROI at the given index.

The axes of the ROI must match the axes of the ROI list.

Parameters:
  • index (int) – Index at which to insert the ROI.

  • roi (Roi) – ROI to insert.

plot(ax=None, **kwargs)[source]

Plot all the ROIs.

tofile(path: str) None[source]

Save the RoiList to a file.

Parameters:

path (str) – Path to the file.

Module contents