impy package¶
Subpackages¶
- impy.arrays package
- impy.frame package
- impy.utils package
- impy.viewer package
- Subpackages
- impy.viewer.widgets package
- Submodules
- impy.viewer.widgets.dialog module
- impy.viewer.widgets.explorer module
- impy.viewer.widgets.gui module
- impy.viewer.widgets.log module
- impy.viewer.widgets.plane_clip module
- impy.viewer.widgets.results module
- impy.viewer.widgets.table module
- impy.viewer.widgets.textedit module
- Module contents
- impy.viewer.widgets package
- Submodules
- impy.viewer.keybinds module
- impy.viewer.menus module
- impy.viewer.mouse module
- impy.viewer.utils module
- impy.viewer.viewer module
- Module contents
- Subpackages
Submodules¶
impy.axes module¶
- class impy.axes.Axes(value=None)[source]¶
Bases:
object
- replace(old: str, new: str)[source]¶
Replace axis symbol. To avoid unexpected effect between images, new scale attribute will be copied.
- Parameters
old (str) – Old symbol.
new (str) – New symbol.
- property scale¶
- exception impy.axes.ImageAxesError[source]¶
Bases:
Exception
This error is raised when axes is defined in a wrong way.
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. History of function call will be similarly recorded in self.history. 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
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()
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=None, **kwargs)[source]¶
Bases:
impy.collections.CollectionBase
,collections.UserDict
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
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.
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
- class impy.collections.DataList(iterable=())[source]¶
Bases:
impy.collections.CollectionBase
,collections.UserList
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
Run Gaussian filter for every ImgArray. >>> imgs = DataList([img1, img2, …]) >>> out = imgs.gaussian_filter() # getattr is called for every image here.
Find single molecules for every ImgArray. >>> imgs = DataList([img1, img2, …]) >>> out = imgs.find_sm()
- append(component: impy.collections._T) None [source]¶
S.append(value) – append value to the end of the sequence
- 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
- extend(other: impy.collections.DataList) None [source]¶
S.extend(iterable) – extend sequence by appending elements from the iterable
impy.core module¶
- impy.core.array(arr: ArrayLike, dtype: DTypeLike = None, *, name: str = None, axes: str = None, copy: bool = True) ImgArray [source]¶
make an ImgArray object, like
np.array(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.
- Returns
- Return type
- impy.core.asarray(arr: ArrayLike, dtype: DTypeLike = None, *, name: str = None, axes: str = 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.
- Returns
- Return type
- impy.core.aslazy(arr: ArrayLike, dtype: DTypeLike = None, *, name: str = None, axes: str = None, chunks='auto') LazyImgArray [source]¶
Make an LazyImgArray object from other types of array.
- Parameters
arr (array-like) – Base array.
dtype (data type, optional) – Image data type.
name (str, optional) – Name of image.
axes (str, optional) – Image axes.
chunks (int, tuple) – How to chunk the array. For details see
dask.array.from_array
.
- Returns
- Return type
- impy.core.circular_mask(radius: nDFloat, shape: _ShapeLike, center: str | tuple[float, ...] = 'center') 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
- impy.core.empty(shape: _ShapeLike, dtype: DTypeLike = <class 'numpy.uint16'>, *, name: str = None, axes: str = None) impy.arrays.imgarray.ImgArray [source]¶
impy version of numpy.empty. This function has additional parameters
axes
andname
. Original docstring follows.- axesstr, optional
Image axes. Must be same length as image dimension.
- name: str, optional
Image name.
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)
or2
.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) –
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.Note
The
like
keyword is an experimental feature pending on acceptance of NEP 35.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
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, axes: str = None) impy.arrays.imgarray.ImgArray [source]¶
impy version of numpy.full. This function has additional parameters
axes
andname
. Original docstring follows.- axesstr, optional
Image axes. Must be same length as image dimension.
- name: str, optional
Image name.
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)
or2
.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) –
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.Note
The
like
keyword is an experimental feature pending on acceptance of NEP 35.New in version 1.20.0.
- Returns
out – Array of fill_value with the given shape, dtype, and order.
- Return type
ndarray
See also
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) 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
- impy.core.imread(path: str, dtype: DTypeLike = None, key: str = None, *, squeeze: bool = False) ImgArray [source]¶
Load image(s) from a path. You can read list of images from directories with wildcards or
"$"
inpath
.- Parameters
path (str) – Path to the image or directory.
dtype (Any type that np.dtype accepts) – Data type of images.
key (str, 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.squeeze (bool, default is False) – If True, redundant dimensions will be squeezed.
- Returns
Image data read from the file.
- Return type
Examples
Read a part of an image
>>> path = r"C:\...\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[[np.ndarray], bool] = 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.
- Returns
- Return type
- impy.core.lazy_imread(path: str, chunks='default', *, squeeze: bool = False) impy.arrays.lazy.LazyImgArray [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.
squeeze (bool, default is False) – If True and there is one-sized axis, then call np.squeeze.
- Returns
- Return type
- impy.core.ones(shape: _ShapeLike, dtype: DTypeLike = <class 'numpy.uint16'>, *, name: str = None, axes: str = None) impy.arrays.imgarray.ImgArray [source]¶
impy version of numpy.ones. This function has additional parameters
axes
andname
. Original docstring follows.- axesstr, optional
Image axes. Must be same length as image dimension.
- name: str, optional
Image name.
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)
or2
.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) –
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.Note
The
like
keyword is an experimental feature pending on acceptance of NEP 35.New in version 1.20.0.
- Returns
out – Array of ones with the given shape, dtype, and order.
- Return type
ndarray
See also
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] [source]¶
Read the metadata of an image file.
- Parameters
path (str) – Path to the image file.
- Returns
Dictionary of metadata with following keys. - “axes”: axes information - “ijmeta”: ImageJ metadata - “history”: impy history - “tags”: tiff tags
- Return type
dict
- impy.core.sample_image(name: str) impy.arrays.imgarray.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
- impy.core.zeros(shape: _ShapeLike, dtype: DTypeLike = <class 'numpy.uint16'>, *, name: str = None, axes: str = None) impy.arrays.imgarray.ImgArray [source]¶
impy version of numpy.zeros. This function has additional parameters
axes
andname
. Original docstring follows.- axesstr, optional
Image axes. Must be same length as image dimension.
- name: str, optional
Image name.
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)
or2
.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) –
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.Note
The
like
keyword is an experimental feature pending on acceptance of NEP 35.New in version 1.20.0.
- Returns
out – Array of zeros with the given shape, dtype, and order.
- Return type
ndarray
See also
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: Dims = None) PropArray | float [source]¶
Normalized Cross Correlation in Fourier space.
- 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 todims="zyx"
.
- Returns
Correlation value(s).
- Return type
PropArray or float
- impy.correlation.fourier_shell_correlation(img0: impy.arrays.imgarray.ImgArray, img1: impy.arrays.imgarray.ImgArray, nbin: int = 32, r_max: float = None, *, squeeze: bool = True, dims: Optional[Union[str, int]] = None) impy.arrays.specials.PropArray ¶
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}}\]- nbinint, default is 32
Number of bins.
- r_maxfloat, optional
Maximum radius to make profile. Region 0 <= r < r_max will be split into nbin rings (or shells). Scale must be considered because scales of each axis may vary.
- 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 todims="zyx"
.
- Returns
FSC stored in x-axis by default. If input images have tzcyx-axes, then an array with tcx-axes will be returned. Make sure x-axis no longer means length in x because images are Fourier transformed.
- Return type
- impy.correlation.fourier_zncc(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, squeeze: bool = True, *, dims: Dims = None) PropArray | float [source]¶
Zero-Normalized Cross Correlation in Fourier space.
- 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 todims="zyx"
.
- Returns
Correlation value(s).
- Return type
PropArray or float
- impy.correlation.fsc(img0: impy.arrays.imgarray.ImgArray, img1: impy.arrays.imgarray.ImgArray, nbin: int = 32, r_max: float = None, *, squeeze: bool = True, dims: Optional[Union[str, int]] = None) impy.arrays.specials.PropArray [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}}\]- nbinint, default is 32
Number of bins.
- r_maxfloat, optional
Maximum radius to make profile. Region 0 <= r < r_max will be split into nbin rings (or shells). Scale must be considered because scales of each axis may vary.
- 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 todims="zyx"
.
- Returns
FSC stored in x-axis by default. If input images have tzcyx-axes, then an array with tcx-axes will be returned. Make sure x-axis no longer means length in x because images are Fourier transformed.
- Return type
- impy.correlation.ft_pcc_maximum(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, upsample_factor: int = 10) np.ndarray [source]¶
Calculate lateral shift between two images. This function takes Fourier transformed images as input. If you have to repetitively use a same template image, this function is faster.
- upsample_factorint, default is 10
Up-sampling factor when calculating phase cross correlation.
- Returns
Shift in pixel.
- Return type
np.ndarray
- impy.correlation.manders_coloc(img0: ImgArray, img1: np.ndarray, *, squeeze: bool = True, dims: Dims = 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 todims="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: Dims = None) PropArray | float [source]¶
Normalized Cross Correlation.
- 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 todims="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: Dims = None) PropArray | float [source]¶
Normalized Mutual Information.
\(Y(A, B) = \frac{H(A) + H(B)}{H(A, B)}\)
See “Elegant SciPy”
- 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 todims="zyx"
.
- Returns
Correlation value(s).
- Return type
PropArray or float
- impy.correlation.pcc_maximum(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, upsample_factor: int = 10) np.ndarray [source]¶
Calculate lateral shift between two images. Same as
skimage.registration.phase_cross_correlation
.- upsample_factorint, default is 10
Up-sampling factor when calculating phase cross correlation.
- Returns
Shift in pixel.
- Return type
np.ndarray
- impy.correlation.pearson_coloc(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, squeeze: bool = True, *, dims: Dims = None) PropArray | float ¶
Zero-Normalized Cross Correlation.
- 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 todims="zyx"
.
- Returns
Correlation value(s).
- Return type
PropArray or float
- impy.correlation.zncc(img0: ImgArray, img1: ImgArray, mask: ImgArray | None = None, squeeze: bool = True, *, dims: Dims = None) PropArray | float [source]¶
Zero-Normalized Cross Correlation.
- 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 todims="zyx"
.
- Returns
Correlation value(s).
- Return type
PropArray or float
impy.random module¶
- impy.random.normal(loc=0.0, scale=1.0, size=None)¶
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
normal
method of adefault_rng()
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)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned ifloc
andscale
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.
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
- 1
Wikipedia, “Normal distribution”, https://en.wikipedia.org/wiki/Normal_distribution
- 2(1,2,3)
P. R. Peebles Jr., “Central Limit Theorem” in “Probability, Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125.
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 N(3, 6.25):
>>> 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)¶
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: Optional[str] = None, axes: Optional[str] = None) impy.arrays.imgarray.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
- impy.random.random_uint8(size: int | tuple[int], *, name: str = None, axes: str = 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