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¶
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, dtype=None, *, name: Optional[str] = None, axes: Optional[str] = None, copy: bool = True) impy.arrays.imgarray.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, dtype=None, *, name: Optional[str] = None, axes: Optional[str] = None) impy.arrays.imgarray.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, dtype=None, *, name: Optional[str] = None, axes: Optional[str] = None, chunks='auto') impy.arrays.lazy.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: tuple[int, ...], 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, dtype=<class 'numpy.uint16'>, *, name: Optional[str] = None, axes: Optional[str] = None) impy.arrays.imgarray.ImgArray [source]¶
Make an ImgArray object, like
np.empty
.- Parameters
shape (int or tuple of int) – Shape of image.
dtype (data type, optional) – Image data type.
name (str, optional) – Name of image.
axes (str, optional) – Image axes.
- impy.core.full(shape, dtype=<class 'numpy.uint16'>, *, name: Optional[str] = None, axes: Optional[str] = None) impy.arrays.imgarray.ImgArray [source]¶
Make an ImgArray object, like
np.full
.- Parameters
shape (int or tuple of int) – Shape of image.
dtype (data type, optional) – Image data type.
name (str, optional) – Name of image.
axes (str, optional) – Image axes.
- impy.core.gaussian_kernel(shape: tuple[int, ...], sigma=1.0, peak: float = 1.0) impy.arrays.imgarray.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: Optional[str] = None, key: Optional[str] = None, *, squeeze: bool = False) impy.arrays.imgarray.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=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, 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, dtype=<class 'numpy.uint16'>, *, name: Optional[str] = None, axes: Optional[str] = None) impy.arrays.imgarray.ImgArray [source]¶
Make an ImgArray object, like
np.ones
.- Parameters
shape (int or tuple of int) – Shape of image.
dtype (data type, optional) – Image data type.
name (str, optional) – Name of image.
axes (str, optional) – Image axes.
- 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, dtype=<class 'numpy.uint16'>, *, name: Optional[str] = None, axes: Optional[str] = None) impy.arrays.imgarray.ImgArray [source]¶
Make an ImgArray object, like
np.zeros
.- Parameters
shape (int or tuple of int) – Shape of image.
dtype (data type, optional) – Image data type.
name (str, optional) – Name of image.
axes (str, optional) – Image axes.
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