impy.arrays package¶
Subpackages¶
Submodules¶
impy.arrays.axesmixin module¶
- class impy.arrays.axesmixin.AxesMixin[source]¶
Bases:
object
Abstract class with shape, ndim and axes are defined.
- property axes: impy.axes.Axes¶
- iter(axes: str, israw: bool = False, exclude: str = '') tuple[Slices, np.ndarray | AxesMixin] [source]¶
Iteration along axes. If axes=”tzc”, then equivalent to following pseudo code:
for t in all_t: for z in all_z: for c in all_c: yield self[t, z, c, ...]
- Parameters
axes (str or int) – On which axes iteration is performed. Or the number of spatial dimension.
israw (bool, default is False) – If True, MetaArray will be returned. If False, np.ndarray will be returned.
exclude (str, optional) – Which axes will be excluded in output. For example, self.axes=”tcyx” and exclude=”c” then the axes of output will be “tyx” and slice is also correctly arranged.
- Yields
slice and (np.ndarray or AxesMixin) – slice and a subimage=self[sl]
- ndim: int¶
- property scale: impy.axes.ScaleDict¶
- property scale_unit: str¶
- set_scale(other=None, **kwargs) None [source]¶
Set scales of each axis.
- Parameters
other (dict or object with axes) – New scales. If dict, it should be like {“x”: 0.1, “y”: 0.1}. If MetaArray, only scales of common axes are copied.
kwargs – This enables function call like set_scale(x=0.1, y=0.1).
- shape: tuple[int, ...]¶
- property shape_info: str¶
- property spatial_shape: tuple[int, ...]¶
impy.arrays.imgarray module¶
- class impy.arrays.imgarray.ImgArray(obj, name=None, axes=None, dirpath=None, history=None, metadata=None, dtype=None)[source]¶
Bases:
impy.arrays.labeledarray.LabeledArray
- affine(matrix=None, scale=None, rotation=None, shear=None, translation=None, mode: str = 'constant', cval: float = 0, output_shape=None, order: int = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Convert image by Affine transformation. 2D Affine transformation is written as:
\[\begin{split}\begin{bmatrix} y'\\ x' \\1 \end{bmatrix} = \begin{bmatrix} A_{00} & A_{01} & A_{02} \\ A_{10} & A_{11} & A_{12} \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} y \\x\\ 1 \end{bmatrix}\end{split}\]and similarly, n-D Affine transformation can be described as (n+1)-D matrix.
- Parameters
matrix – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.scale – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.rotation – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.shear – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.translation – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.mode – Padding mode, constant value and the shape of output. See
scipy.ndimage.affine_transform
for details.cval – Padding mode, constant value and the shape of output. See
scipy.ndimage.affine_transform
for details.output_shape – Padding mode, constant value and the shape of output. See
scipy.ndimage.affine_transform
for details.order (int, default is 1) – Spline interpolation order. For more details see here.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Transformed image.
- Return type
- affine_correction(matrices=None, *, bins: int = 256, order: int = 1, prefilter: bool = True, along: str = 'c') impy.arrays.imgarray.ImgArray [source]¶
Correct chromatic aberration using Affine transformation. Input matrix is determined by maximizing normalized mutual information.
- Parameters
matrices (array or iterable of arrays, optional) – Affine matrices.
bins (int, default is 256) – Number of bins that is generated on calculating mutual information.
order (int, default is 1) –
Spline interpolation order. For more details see here.
prefilter (bool, default is True.) – If median filter is applied to all images before fitting. This does not change original images.
along (str, default is "c") – Along which axis correction will be performed. Chromatic aberration -> “c” Some drift during time lapse movie -> “t”
- Returns
Corrected image.
- Return type
- area_closing(area: int = 64, *, connectivity: int = 1, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
- area_opening(area: int = 64, *, connectivity: int = 1, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
- binning(binsize: int = 2, method='mean', *, check_edges: bool = True, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Binning of images. This function is similar to
rescale
but is strictly binned by \(N \times N\) blocks. Also, any numpy functions that accept “axis” argument are supported for reduce functions.- Parameters
binsize (int, default is 2) – Bin size, such as 2x2.
method (str or callable, default is numpy.mean) – Reduce function applied to each bin.
check_edges (bool, default is True) – If True, only divisible
binsize
is accepted. If False, image is cropped at the end to match binsize.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
Binned image
- Return type
- centroid_sm(coords: Coords = None, radius: nDInt = 4, sigma: nDFloat = 1.5, filt: Callable[[ImgArray], bool] = None, percentile: float = 95, *, dims: Dims = None) MarkerFrame [source]¶
Calculate positions of particles in subpixel precision using centroid.
- Parameters
coords (MarkerFrame or (N, 2) array, optional) – Coordinates of peaks. If None, this will be determined by find_sm.
radius (int, default is 4.) – Range to calculate centroids. Rectangular image with size 2r+1 x 2r+1 will be send to calculate moments.
sigma (float, default is 1.5) – Expected standard deviation of particles.
filt (callable, optional) – For every slice
sl
, label is added only when filt(input) == True is satisfied.percentile – Passed to
peak_local_max()
dims – Passed to
peak_local_max()
- Returns
Coordinates of peaks.
- Return type
- clip(in_range: tuple[int | str, int | str] = ('0%', '100%')) ImgArray [source]¶
Saturate low/high intensity using np.clip().
- Parameters
in_range (two scalar values, optional) – range of lower/upper limits, by default (0, 100)
- Returns
Clipped image with temporal attribute
- Return type
- closing(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Morphological closing. If input is binary image, the running function will automatically switched to
binary_closing
to speed up calculation.- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- coef_filter(radius: float = 1, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Coefficient of variance filter. For kernel area X, \(\frac{\sqrt{V[X]}}{E[X]}\) is calculated. This filter is useful for feature extraction from images with uneven background intensity.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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
Filtered image
- Return type
- convex_hull(*, dims: Optional[Union[str, int]] = None, update=False) impy.arrays.imgarray.ImgArray [source]¶
Compute convex hull image.
- Parameters
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Convex hull image.
- Return type
- convolve(kernel, *, mode: str = 'reflect', cval: float = 0, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
General linear convolution by running kernel filtering.
- Parameters
kernel (array-like) – Convolution kernel.
mode (str, default is "reflect".) – Padding mode. See scipy.ndimage.convolve.
cval (int, default is 0) – Constant value to fill outside the image if mode == “constant”.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Convolved image.
- Return type
- corner_harris(sigma: Union[Sequence[float], float] = 1, k: float = 0.05, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Calculate Harris response image.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
k (float, optional) – Sensitivity factor to separate corners from edges, typically in range [0, 0.2]. Small values of k result in detection of sharp corners.
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
Harris response
- Return type
- corner_peaks(*, min_distance: int = 1, percentile: float = None, topn: int = inf, topn_per_label: int = inf, exclude_border: bool = True, use_labels: bool = True, dims: Dims = None) MarkerFrame [source]¶
Find local corner maxima. Slightly different from peak_local_max.
- Parameters
min_distance (int, default is 1) – Minimum distance allowed for each two peaks. This parameter is slightly different from that in
skimage.feature.peak_local_max
because here float input is allowed and every time footprint is calculated.percentile (float, optional) – Percentile to compute absolute threshold.
topn (int, optional) – Maximum number of peaks for each iteration.
topn_per_label (int, default is np.inf) – Maximum number of peaks per label.
use_labels (bool, default is True) – If use self.labels when it exists.
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
DataFrame with columns same as axes of self. For example, if self.axes is “tcyx” then return value has “t”, “c”, “y” and “x” columns, and sub-frame at t=0, c=0 contains all the coordinates of corners in the slice at t=0, c=0.
- Return type
- count_neighbors(*, connectivity: int = None, mask: bool = True, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Count the number or neighbors of binary images. This function can be used for cross section or branch detection. Only works for binary images.
- Parameters
connectivity (int, optional) – Connectivity of pixels. See
skimage.measure.label
.mask (bool, default is True) – If True, only neighbors of pixels that satisfy self==True is returned.
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
uint8 array of the number of neighbors.
- Return type
Examples
>>> skl = img.threshold().skeletonize() >>> edge = skl.count_neighbors() >>> np.argwhere(edge == 1) # get coordinates of filament edges. >>> np.argwhere(edge >= 3) # get coordinates of filament cross sections.
- diameter_closing(diameter: int = 8, *, connectivity: int = 1, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
- diameter_opening(diameter: int = 8, *, connectivity: int = 1, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
- dilation(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Morphological dilation. If input is binary image, the running function will automatically switched to
binary_dilation
to speed up calculation.- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- dirpath: str¶
- distance_map(*, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Calculate distance map from binary images. For instance,
[1, 1, 1, 0, 0, 0, 1, 1, 1]
will be converted to[3, 2, 1, 0, 0, 0, 1, 2, 3]
. Note that returned array will be float in n-D images.- Parameters
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
Distance map, the further the brighter
- Return type
- dog_filter(low_sigma: Union[Sequence[float], float] = 1, high_sigma: Union[Sequence[float], float] = None, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Run Difference of Gaussian filter. This function does not support update argument because intensity can be negative.
- Parameters
low_sigma (scalar or array of scalars, default is 1.) – lower standard deviation(s) of Gaussian.
high_sigma (scalar or array of scalars, default is x1.6 of low_sigma.) – higher standard deviation(s) of Gaussian.
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
Filtered image.
- Return type
- doh_filter(sigma: Union[Sequence[float], float] = 1, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Determinant of Hessian filter. This function does not support update argument because output has total different scale of intensity.
Warning
Because in most cases we want to find only bright dots, eigenvalues larger than 0 is ignored before computing determinant.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
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
Filtered image.
- Return type
- drift_correction(shift: Coords = None, ref: ImgArray = None, *, zero_ave: bool = True, along: str = None, dims: Dims = 2, update: bool = False, **affine_kwargs) ImgArray [source]¶
Drift correction using iterative Affine translation. If translation vectors
shift
is not given, then it will be determined usingtrack_drift
method of ImgArray.- Parameters
shift (DataFrame or (N, D) array, optional) – Translation vectors. If DataFrame, it must have columns named with all the symbols contained in
dims
.ref (ImgArray, optional) – The reference n-D image to determine drift, if
shift
was not given.zero_ave (bool, default is True) – If True, average shift will be zero.
along (str, optional) – Along which axis drift will be corrected.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
affine_kwargs – Keyword arguments that will be passed to
warp
.
- Returns
Corrected image.
- Return type
Examples
- Drift correction of multichannel image using the first channel as the reference.
>>> img.drift_correction(ref=img["c=0"])
- edge_filter(method: str = 'sobel', *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Sobel filter. This filter is useful for edge detection.
- Parameters
method (str, {"sobel", "farid", "scharr", "prewitt"}, default is "sobel") – Edge operator name.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- edge_grad(sigma: Union[Sequence[float], float] = 1.0, method: str = 'sobel', *, deg: bool = False, dims: Optional[Union[str, int]] = 2) impy.arrays.phasearray.PhaseArray [source]¶
Calculate gradient direction using horizontal and vertical edge operation. Gradient direction is the direction with maximum gradient, i.e., intensity increase is largest.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
method (str, {"sobel", "farid", "scharr", "prewitt"}, default is "sobel") – Edge operator name.
deg (bool, default is True) – If True, degree rather than radian is returned.
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
Phase image with range [-180, 180) if deg==True, otherwise [-pi, pi).
- Return type
Examples
- Profile filament orientation distribution using histogram of edge gradient.
>>> grad = img.edge_grad(deg=True) >>> plt.hist(grad.ravel(), bins=100)
- enhance_contrast(radius: Union[Sequence[float], float] = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Enhance contrast filter.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Contrast enhanced image.
- Return type
- entropy_filter(radius: Union[Sequence[float], float] = 5, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Running entropy filter. This filter is useful for detecting change in background distribution.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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
Filtered image.
- Return type
- erosion(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Morphological erosion. If input is binary image, the running function will automatically switched to
binary_erosion
to speed up calculation.- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
{cval} –
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- estimate_sigma(*, squeeze: bool = True, dims: Dims = None) PropArray | float [source]¶
Wavelet-based estimation of Gaussian noise.
- Parameters
squeeze (bool, default is True) – If True and output can be converted to a scalar, then convert it.
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
Estimated standard deviation. sigma[“t=0;c=1”] means the estimated value of image slice at t=0 and c=1.
- Return type
PropArray or float
- fft(*, shape: int | Iterable[int] | str = 'same', shift: bool = True, double_precision=False, dims: Dims = None) ImgArray [source]¶
Fast Fourier transformation. This function returns complex array, which is inconpatible with some ImgArray functions.
- Parameters
shape (int, iterable of int, "square" or "same") – Output shape. Input image is padded or cropped according to this value: - integers: padded or cropped to the specified shape. - “square”: padded to smallest 2^N-long square. - “same” (default): no padding or cropping.
shift (bool, default is True) – If True, call
np.fft.fftshift
in the end.double_precision (bool, default is False) – If True, FFT will be calculated using 64-bit float and 128-bit complex.
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
FFT image.
- Return type
See also
- fill_hole(thr: float | str = 'otsu', *, dims: Dims = None, update: bool = False) ImgArray [source]¶
Filling holes. See skimage’s documents here.
- Parameters
thr (scalar or str, optional) – Threshold (value or method) to apply if image is not binary.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Hole-filled image.
- Return type
- find_corners(sigma: Union[Sequence[float], float] = 1, k: float = 0.05, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Corner detection using Harris response.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
k (float, optional) – Sensitivity factor to separate corners from edges, typically in range [0, 0.2]. Small values of k result in detection of sharp corners.
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
Coordinates of corners. For details see
corner_peaks
method.- Return type
- find_sm(sigma: nDFloat = 1.5, *, method: str = 'dog', cutoff: float = None, percentile: float = 95, topn: int = inf, exclude_border: bool = True, dims: Dims = None) MarkerFrame [source]¶
Single molecule detection using difference of Gaussian, determinant of Hessian, Laplacian of Gaussian or normalized cross correlation method.
- Parameters
sigma (float, optional) – Standard deviation of puncta.
method (str {"dog", "doh", "log", "gaussian", "ncc"}, default is "dog") – Which filter is used prior to finding local maxima. If “ncc”, a Gaussian particle is used as the template image.
cutoff (float, optional) – Cutoff value of filtered image generated by method.
percentile – Passed to
peak_local_max()
topn – Passed to
peak_local_max()
exclude_border – Passed to
peak_local_max()
dims – Passed to
peak_local_max()
- Returns
Peaks in uint16 type.
- Return type
Examples
Track single molecules and view the tracks with napari.
>>> coords = img.find_sm() >>> lnk = coords.link(3, min_dwell=10) >>> ip.gui.add(img) >>> ip.gui.add(lnk)
See also
- flood(seeds: Coords, *, connectivity: int = 1, tolerance: float = None, dims: Dims = None)[source]¶
Flood filling with a list of seed points. By repeating skimage’s
flood
function, this method can perform segmentation of an image.- Parameters
seeds (MarkerFrame or (N, D) array-like) – Seed points to start flood filling.
connectivity (int, optional) – Connectivity of pixels. See
skimage.measure.label
.tolerance (float, optional) – Intensity deviation within this value will be filled.
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
Labeled image.
- Return type
- focus_map(radius: int = 1, *, dims: Optional[Union[str, int]] = 2) impy.arrays.specials.PropArray [source]¶
Compute focus map using variance of Laplacian method. yx-plane with higher variance is likely a focal plane because sharper image causes higher value of Laplacian on the edges.
- Parameters
radius (int, default is 1) – Radius of Laplacian filter’s kernel.
{dims} –
- Returns
Array of variance of Laplacian
- Return type
Examples
- Get the focus plane from a 3D image.
>>> score = img.focus_map() >>> score.plot() # plot the variation of laplacian focus >>> z_focus = np.argmax(score) # determine the focus plane >>> img[z_focus] # get the focus plane
- gabor_angle(n_sample: int = 180, lmd: float = 5, sigma: float = 2.5, gamma: float = 1, phi: float = 0, *, deg: bool = False, dims: Optional[Union[str, int]] = 2) impy.arrays.phasearray.PhaseArray [source]¶
Calculate filament angles using Gabor filter. For all the candidates of angles, Gabor response is calculated, and the strongest response is returned as output array.
- Parameters
n_sample (int, default is 180) – Number of `theta`s to calculate. By default, -90, -89, …, 89 degree are calculated.
lmd (float, default is 5) – Wave length of Gabor kernel. Make sure that the diameter of the objects you want to detect is around lmd/2.
sigma (float, default is 2.5) – Standard deviation of Gaussian factor of Gabor kernel.
gamma (float, default is 1) – Anisotropy of Gabor kernel, i.e. the standard deviation orthogonal to theta will be sigma/gamma.
phi (float, default is 0) – Phase offset of harmonic factor of Gabor kernel.
deg (bool, default is False) – If True, degree rather than radian is returned.
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
Phase image with range [-90, 90) if deg==True, otherwise [-pi/2, pi/2).
- Return type
See also
- gabor_filter(lmd: float = 5, theta: float = 0, sigma: float = 2.5, gamma: float = 1, phi: float = 0, *, return_imag: bool = False, dims: Optional[Union[str, int]] = 2) impy.arrays.imgarray.ImgArray [source]¶
Make a Gabor kernel and convolve it.
- Parameters
lmd (float, default is 5) – Wave length of Gabor kernel. Make sure that the diameter of the objects you want to detect is around lmd/2.
theta (float, default is 0) – Orientation of harmonic factor of Gabor kernel in radian (x-directional if theta==0).
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
gamma (float, default is 1) – Anisotropy of Gabor kernel, i.e. the standard deviation orthogonal to theta will be sigma/gamma.
phi (float, default is 0) – Phase offset of harmonic factor of Gabor kernel.
return_imag (bool, default is False) – If True, a complex image that contains both real and imaginary part of Gabor response is returned.
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
Filtered image.
- Return type
ImgArray (dtype is float32 or complex64)
Examples
- Edge Detection using multi-angle Gabor filtering.
>>> thetas = np.deg2rad([0, 45, 90, 135]) >>> out = np.zeros((4,)+img.shape, dtype=np.float32) >>> for i, theta in enumerate(thetas): >>> out[i] = img.gabor_filter(theta=theta) >>> out = np.max(out, axis=0)
- gauss_correction(ref: impy.arrays.imgarray.ImgArray = None, scale: float = 0.0625, median_radius: float = 15)[source]¶
Correct unevenly distributed excitation light using Gaussian fitting. This method subtracts background intensity at the same time. If input image is uint, then output value under 0 will replaced with 0. If you want to quantify background, it is necessary to first convert input image to float image.
- Parameters
ref (ImgArray, default is self.) – Reference image to estimate background.
scale (float, default is 1/16.) – Scale of rough image (to speed up fitting).
median_radius (float, default is 15.) – Radius of median prefilter’s kernel. If smaller than 1, prefiltering will be skipped.
- Returns
Corrected and background subtracted image.
- Return type
Examples
1. When input image has “ptcyx”-axes, and you want to estimate the background intensity for each channel by averaging all the positions and times.
>>> img_cor = img.gauss_correction(ref=img.proj("pt"))
2. When input image has “ptcyx”-axes, and you want to estimate the background intensity for each channel and time point by averaging all the positions.
>>> img_cor = img.gauss_correction(ref=img.proj("p"))
- gauss_sm(coords: Coords = None, radius: nDInt = 4, sigma: nDFloat = 1.5, filt: Callable = None, percentile: float = 95, *, return_all: bool = False, dims: Dims = None) MarkerFrame | DataDict [source]¶
Calculate positions of particles in subpixel precision using Gaussian fitting.
- Parameters
coords (MarkerFrame or (N, 2) array, optional) – Coordinates of peaks. If None, this will be determined by find_sm.
radius (int, default is 4.) – Fitting range. Rectangular image with size 2r+1 x 2r+1 will be send to Gaussian fitting function.
sigma (float, default is 1.5) – Expected standard deviation of particles.
filt (callable, optional) – For every slice sl, label is added only when filt(input) == True is satisfied. This discrimination is conducted before Gaussian fitting so that stringent filter will save time.
percentile – Passed to peak_local_max()
dims (str or int, optional) – Passed to peak_local_max()
return_all (bool, default is False) – If True, fitting results are all returned as Frame Dict.
dims – 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
MarkerFrame, if return_all == False – Gaussian centers.
DataDict with keys {means, sigmas, errors}, if return_all == True – Dictionary that contains means, standard deviations and fitting errors.
- gaussfit(scale: float = 0.0625, p0: list = None, show_result: bool = True, method: str = 'Powell') impy.arrays.imgarray.ImgArray [source]¶
Fit the image to 2-D Gaussian background.
- Parameters
scale (float, default is 1/16.) – Scale of rough image (to speed up fitting).
p0 (list or None, optional) – Initial parameters.
show_result (bool, default is True) – If True, plot the fitting result on the cross sections.
method (str, optional) – Fitting method. See scipy.optimize.minimize.
- Returns
Fit image.
- Return type
- gaussian_filter(sigma: Union[Sequence[float], float] = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Run Gaussian filter (Gaussian blur).
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- glcm_props(distances, angles, radius: int, properties: tuple = None, *, bins: int = None, rescale_max: bool = False, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Compute properties of “Gray Level Coocurrence Matrix”. This will take long time because of pure Python for-loop.
- Parameters
distances (array_like) – List of pixel pair distance offsets.
angles (array_like) – List of pixel pair angles in radians.
radius (int) – Window radius.
properties (tuple of str) – contrast, dissimilarity, homogeneity, energy, mean, std, asm, max, entropy
bins (int, optional) – Number of bins.
rescale_max (bool, default is False) – If True, the contrast of the input image is maximized by multiplying an integer.
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
GLCM with additional axes “da”, where “d” means distance and “a” means angle. If input image has “tzyx” axes then output will have “tzd<yx” axes.
- Return type
DataDict of ImgArray
Examples
- Plot GLCM’s IDM and ASM images
>>> out = img.glcm_props([1], [0], 3, properties=("idm","asm")) >>> out.idm["d=0;<=0"].imshow() >>> out.asm["d=0;<=0"].imshow()
- hessian_angle(sigma: Union[Sequence[float], float] = 1.0, *, deg: bool = False, dims: Optional[Union[str, int]] = 2) impy.arrays.phasearray.PhaseArray [source]¶
Calculate filament angles using Hessian’s eigenvectors.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
deg (bool, default is False) – If True, degree rather than radian is returned.
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
Phase image with range [-90, 90] if
deg==True
, otherwise [-pi/2, pi/2].- Return type
See also
- hessian_eig(sigma: Union[Sequence[float], float] = 1, *, dims: Optional[Union[str, int]] = None) tuple[impy.arrays.imgarray.ImgArray, impy.arrays.imgarray.ImgArray] [source]¶
Calculate Hessian’s eigenvalues and eigenvectors.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
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
Arrays of eigenvalues and eigenvectors. The axis
"l"
denotes the index of eigenvalues. l=0 means the smallest eigenvalue."r"
denotes the index of spatial dimensions. For 3D image, r=0 means z-element of an eigenvector.- Return type
ImgArray and ImgArray
- hessian_eigval(sigma: Union[Sequence[float], float] = 1, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Calculate Hessian’s eigenvalues for each image.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
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
Array of eigenvalues. The axis
"l"
denotes the index of eigenvalues. l=0 means the smallest eigenvalue.- Return type
Examples
- Extract filament
>>> eig = -img.hessian_eigval()["l=0"] >>> eig[eig<0] = 0
- highpass_filter(cutoff: Union[Sequence[float], float] = 0.2, order: float = 2, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Butterworth high-pass filter.
- Parameters
cutoff (float or array-like, default is 0.2) – Cutoff frequency.
order (float, default is 2) – Steepness of cutoff.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image
- Return type
- ifft(real: bool = True, *, shift: bool = True, double_precision=False, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Fast Inverse Fourier transformation. Complementary function with fft().
- Parameters
real (bool, default is True) – If True, only the real part is returned.
shift (bool, default is True) – If True, call
np.fft.ifftshift
at the first.double_precision (bool, default is False) – If True, FFT will be calculated using 64-bit float and 128-bit complex.
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
IFFT image.
- Return type
- kalman_filter(gain: float = 0.8, noise_var: float = 0.05, *, along: str = 't', dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Kalman filter for image smoothing. This function is same as “Kalman Stack Filter” in ImageJ but support batch processing. This filter is useful for preprocessing of particle tracking.
- Parameters
gain (float, default is 0.8) – Filter gain.
noise_var (float, default is 0.05) – Initial estimate of noise variance.
along (str, default is "t") – Which axis will be the time axis.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image
- Return type
- label_threshold(thr: float | str = 'otsu', *, dims: Dims = None, **kwargs) Label [source]¶
Make labels with threshold(). Be sure that keyword argument
dims
can be different (in most cases for >4D images) between threshold() and label(). In this function, both function will have the samedims
for simplicity.- Parameters
thr (float or str or None, optional) – Threshold value, or thresholding algorithm.
{dims} –
**kwargs – Keyword arguments that will passed to function indicated in ‘method’.
- Returns
Same array but labels are updated.
- Return type
- laplacian_filter(radius: int = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Edge detection using Laplacian filter. Kernel is made by skimage’s function.
- Parameters
radius (int, default is 1) – Radius of kernel. Shape of kernel will be (2*radius+1, 2*radius+1).
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- lbp(p: int = 12, radius: int = 1, *, method: str = 'default', dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Local binary pattern feature extraction.
- Parameters
p (int, default is 12) – Number of circular neighbors
radius (int, default is 1) – Radius of neighbours.
method (str, optional) – Method to determined the pattern.
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
Local binary pattern image.
- Return type
- lineprops(src: Coords, dst: Coords, func: str | Callable = 'mean', *, order: int = 1, squeeze: bool = True) PropArray [source]¶
Measure line property using func(line_scan).
- Parameters
src (MarkerFrame or array-like) – Source coordinates.
dst (MarkerFrame of array-like) – Destination coordinates.
func (str or callable, default is "mean".) – Measurement function.
order (int, default is 1) –
Spline interpolation order. For more details see here.
squeeze (bool, default is True.) – If True and only one line is measured, the redundant dimension ID_AXIS will be deleted.
- Returns
Line properties.
- Return type
Examples
- Time-course measurement of intensities on lines.
>>> pr = img.lineprops([[2,3], [8,9]], [[32,85], [66,73]]) >>> pr.plot()
- local_dft(key: str = '', upsample_factor: Union[Sequence[int], int] = 1, *, double_precision=False, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Local discrete Fourier transformation (DFT). This function will be useful for Fourier transformation of small region of an image with a certain factor of up-sampling. In general FFT takes \(O(N\log{N})\) time, much faster compared to normal DFT (\(O(N^2)\)). However, If you are interested in certain region of Fourier space, you don’t have to calculate all the spectra. In this case DFT is faster and less memory comsuming.
Warning
The result of
local_dft
will NOT be shifted withnp.fft.fftshift
because in general the center of arrays are unknown. Also, it is easier to understand x=0 corresponds to the center.Even whole spectrum is returned,
local_dft
may be faster than FFT with small and/or non-FFT-friendly shaped image.- Parameters
key (str) – Key string that specify region to DFT, such as “y=-50:10;x=:80”. With Upsampled spectra, keys corresponds to the coordinate before up-sampling. If you want certain region, say “x=10:20”, this value will not change with different
upsample_factor
.upsample_factor (int or array of int, default is 1) – Up-sampling factor. For instance, when
upsample_factor=10
a single pixel will be expanded to 10 pixels.double_precision (bool, default is False) – If True, FFT will be calculated using 64-bit float and 128-bit complex.
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
DFT output.
- Return type
See also
- local_power_spectra(key: str = '', upsample_factor: Union[Sequence[int], int] = 1, norm: bool = False, *, double_precision=False, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Return local n-D power spectra of images. See
local_dft
.- Parameters
key (str) – Key string that specify region to DFT, such as “y=-50:10;x=:80”. With Upsampled spectra, keys corresponds to the coordinate before up-sampling. If you want certain region, say “x=10:20”, this value will not change with different
upsample_factor
.upsample_factor (int or array of int, default is 1) – Up-sampling factor. For instance, when
upsample_factor=10
a single pixel will be expanded to 10 pixels.norm (bool, default is False) – If True, maximum value of power spectra is adjusted to 1.
double_precision (bool, default is False) – If True, FFT will be calculated using 64-bit float and 128-bit complex.
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
Power spectra
- Return type
See also
- log_filter(sigma: Union[Sequence[float], float] = 1, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Laplacian of Gaussian filter.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
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
Filtered image.
- Return type
- lowpass_conv_filter(cutoff: Union[Sequence[float], float] = 0.2, order: float = 2, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Butterworth low-pass filter in real space. Butterworth kernel is created first using inverse Fourier transform of weight function.
- Parameters
cutoff (float or array-like, default is 0.2) – Cutoff frequency.
order (float, default is 2) – Steepness of cutoff.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image
- Return type
- lowpass_filter(cutoff: Union[Sequence[float], float] = 0.2, order: float = 2, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Butterworth low-pass filter.
- Parameters
cutoff (float or array-like, default is 0.2) – Cutoff frequency.
order (float, default is 2) – Steepness of cutoff.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image
- Return type
- lucy(psf: numpy.ndarray, niter: int = 50, eps: float = 1e-05, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Deconvolution of N-dimensional image, using Richardson-Lucy’s algorithm.
- Parameters
psf (np.ndarray) – Point spread function.
niter (int, default is 50.) – Number of iterations.
eps (float, default is 1e-5) – During deconvolution, division by small values in the convolve image of estimation and PSF may cause divergence. Therefore, division by values under eps is substituted to zero.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Deconvolved image.
- Return type
- lucy_tv(psf: numpy.ndarray, max_iter: int = 50, lmd: float = 0.001, tol: float = 0.001, eps: float = 1e-05, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Deconvolution of N-dimensional image, using Richardson-Lucy’s algorithm with total variance regularization (so called RL-TV algorithm). The TV regularization factor at pixel position \(x\), \(F_{reg}(x)\), is calculated as:
\[F_{reg}(x) = \frac{1}{1-\lambda \cdot div(\frac{grad(I(x)}{|grad(I(x))|})}\](\(I(x)\): image, \(\lambda\): constant)
and this factor is multiplied for every estimation made in each iteration.
- Parameters
psf (np.ndarray) – Point spread function.
max_iter (int, default is 50.) – Maximum number of iterations.
lmd (float, default is 1e-3) – The constant lambda of TV regularization factor.
tol (float, default is 1e-3) –
Iteration stops if regularized absolute summation is lower than this value.
\(\frac{\sum_{x}|I'(x) - I(x)|}{\sum_{x}|I(x)|}\)
(\(I'(x)\): estimation of \(k+1\)-th iteration, \(I(x)\): estimation of \(k\)-th iteration)
eps (float, default is 1e-5) – During deconvolution, division by small values in the convolve image of estimation and PSF may cause divergence. Therefore, division by values under
eps
is substituted to zero.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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Deconvolved image.
- Return type
References
Dey, N., Blanc-Féraud, L., Zimmer, C., Roux, P., Kam, Z., Olivo-Marin, J. C., & Zerubia, J. (2004). 3D microscopy deconvolution using Richardson-Lucy algorithm with total variation regularization (Doctoral dissertation, INRIA).
- mean_filter(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Mean filter. Kernel is filled with same values.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image
- Return type
- median_filter(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Running median filter. This filter is useful for deleting outliers generated by noise.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- name: str¶
- ncc_filter(template: numpy.ndarray, mode: str = 'constant', cval: float = None, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Template matching using normalized cross correlation (NCC) method. This function is basically identical to that in skimage.feature, but is optimized for batch processing and improved readability.
- Parameters
template (np.ndarray) – Template image. Must be 2 or 3 dimensional.
{mode} –
cval (float, optional) – Background intensity. If not given, it will calculated as the minimum value of the original image.
{dims} –
- Returns
Response image with values between -1 and 1.
- Return type
- opening(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Morphological opening. If input is binary image, the running function will automatically switched to
binary_opening
to speed up calculation.- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- pad(pad_width, mode: str = 'constant', *, dims: Optional[Union[str, int]] = None, **kwargs) impy.arrays.imgarray.ImgArray [source]¶
Pad image only for spatial dimensions.
- Parameters
pad_width – See documentation of np.pad().
mode – See documentation of np.pad().
**kwargs – See documentation of np.pad().
dims (int or str, optional) – Which dimension to pad.
- Returns
Padded image.
- Return type
Examples
Suppose
img
has zyx-axes.- Padding 5 pixels in zyx-direction:
>>> img.pad(5)
- Padding 5 pixels in yx-direction:
>>> img.pad(5, dims="yx")
- Padding 5 pixels in yx-direction and 2 pixels in z-direction:
>>> img.pad([(5,5), (4,4), (4,4)])
- Padding 10 pixels in z-(-)-direction and 5 pixels in z-(+)-direction.
>>> img.pad([(10, 5)], dims="z")
- pad_defocus(kernel, *, depth: int = 3, width: int = 6, bg: float = None) impy.arrays.imgarray.ImgArray [source]¶
Make a z-directional padded image by defocusing the original image. This padding is useful when applying FFT to a 3D image.
- Parameters
kernel (0-, 1- or 3-dimensional array.) – If 0- (scalar) or 1-dimensional array was given, this is interpreted as standard deviation of Gaussian kernel. If 3-dimensional array was given, this is directly used as convolution kernel. Other dimension will raise ValueError.
depth (int, default is 3) – Depth of defocusing. For an image with z-axis size L, then output image will have size L + 2*depth.
width (int, default is 6) – Width of defocusing. For an image with yx-shape (M, N), then output image will have shape (M * 2*width, N + 2*width).
bg (float, optional) – Background intensity. If not given, it will calculated as the minimum value of the original image.
- Returns
Padded image.
- Return type
Examples
depth = 2
----| |----| o |-- o ... center of kernel ----| o |----| |-- ++++| |++++|___|++ <- the upper edge of original image ++++|___|+++++++++++
- pathprops(paths: PathFrame, properties: str | Callable | Iterable[str | Callable] = 'mean', *, order: int = 1) DataDict [source]¶
Measure line property using func(line_scan) for each func in properties.
- Parameters
- Returns
Line properties. Keys are property names and values are the corresponding PropArrays.
- Return type
DataDict of PropArray
Examples
- Time-course measurement of intensities on a path.
>>> img.pathprops([[2,3], [102, 301], [200,400]])
- peak_local_max(*, min_distance: float = 1.0, percentile: float = None, topn: int = inf, topn_per_label: int = inf, exclude_border: bool = True, use_labels: bool = True, dims: Dims = None) MarkerFrame [source]¶
Find local maxima. This algorithm corresponds to ImageJ’s ‘Find Maxima’ but is more flexible.
- Parameters
min_distance (float, default is 1.0) – Minimum distance allowed for each two peaks. This parameter is slightly different from that in
skimage.feature.peak_local_max
because here float input is allowed and every time footprint is calculated.percentile (float, optional) – Percentile to compute absolute threshold.
topn (int, optional) – Maximum number of peaks for each iteration.
topn_per_label (int, default is np.inf) – Maximum number of peaks per label.
use_labels (bool, default is True) – If use self.labels when it exists.
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
DataFrame with columns same as axes of self. For example, if self.axes is “tcyx” then return value has “t”, “c”, “y” and “x” columns, and sub-frame at t=0, c=0 contains all the coordinates of peaks in the slice at t=0, c=0.
- Return type
- pointprops(coords: Coords, *, order: int = 1, squeeze: bool = True) PropArray [source]¶
Measure interpolated intensity at points with float coordinates.
- Parameters
coords (MarkerFrame or array-like) – Coordinates of point to be measured.
order (int, default is 1) –
Spline interpolation order. For more details see here.
squeeze (bool, default is True) – If True and only one point is measured, the redundant dimension ID_AXIS will be deleted.
- Returns
Point properties.
- Return type
Examples
- Calculate centroids and measure intensities.
>>> coords = img.proj("t").centroid_sm() >>> prop = img.pointprops(coords)
- power_spectra(shape='same', norm: bool = False, zero_norm: bool = False, *, double_precision=False, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Return n-D power spectra of images, which is defined as:
\[P = Re(F[I_{img}])^2 + Im(F[I_{img}])^2\]- Parameters
shape (int, iterable of int, "square" or "same") – Output shape. Input image is padded or cropped according to this value: - integers: padded or cropped to the specified shape. - “square”: padded to smallest 2^N-long square. - “same” (default): no padding or cropping.
norm (bool, default is False) – If True, maximum value of power spectra is adjusted to 1.
double_precision (bool, default is False) – If True, FFT will be calculated using 64-bit float and 128-bit complex.
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
Power spectra
- Return type
See also
- proj(axis: str = None, method: str | Callable = 'mean', mask=None, **kwargs) ImgArray [source]¶
Z-projection along any axis.
- Parameters
axis (str, optional) – Along which axis projection will be calculated. If None, most plausible one will be chosen.
method (str or callable, default is mean-projection.) – Projection method. If str is given, it will converted to numpy function.
mask (array-like, optional) – If provided, input image will be converted to np.ma.array and
method
will also be interpreted as an masked functio if possible.**kwargs – Other keyword arguments that will passed to projection function.
- Returns
Projected image.
- Return type
- radial_profile(nbin: int = 32, center: Iterable[float] = None, r_max: float = None, *, method: str = 'mean', dims: Optional[Union[str, int]] = None) impy.arrays.specials.PropArray [source]¶
Calculate radial profile of images. Scale along each axis will be considered, i.e., rather ellipsoidal profile will be calculated instead if scales are different between axes.
- Parameters
nbin (int, default is 32) – Number of bins.
center (iterable of float, optional) – The coordinate of center of radial profile. By default, the center of image is used.
r_max (float, 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.method (str, default is "mean") – Reduce function. Basic statistics functions are supported in
scipy.ndimage
but their names are not consistent with those in numpy. Use numpy’s names here.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
Radial profile stored in x-axis by default. If input image has tzcyx-axes, then an array with tcx-axes will be returned.
- Return type
- random_walker(beta: float = 130, mode: str = 'cg_j', tol: float = 0.001, *, dims: Optional[Union[str, int]] = None) impy.arrays.label.Label [source]¶
Random walker segmentation. Only wrapped skimage segmentation.
self.labels
will be segmented.- Parameters
beta – see skimage.segmentation.random_walker
mode – see skimage.segmentation.random_walker
tol – see skimage.segmentation.random_walker
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
Relabeled image.
- Return type
- refine_sm(coords: Coords = None, radius: float = 4, *, percentile: float = 95, n_iter: int = 10, sigma: float = 1.5, dims: Dims = None)[source]¶
Refine coordinates of peaks and calculate positional errors using trackpy’s functions. Mean and noise level are determined using original method.
- Parameters
coords (MarkerFrame or (N, D) array, optional) – Coordinates of peaks. If None, this will be determined by find_sm.
radius (float, default is 4.) – Range to mask single molecules.
percentile (int, default is 95) – Passed to
peak_local_max()
n_iter (int, default is 10) – Number of iteration of refinement.
sigma (float, default is 1.5) – Expected standard deviation of particles.
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
Coordinates in MarkerFrame and refinement results in pd.DataFrame.
- Return type
MarkerFrame and pd.DataFrame
See also
- regionprops(properties: Iterable[str] | str = ('mean_intensity',), *, extra_properties: Iterable[Callable] | None = None) DataDict[str, PropArray] [source]¶
Run skimage’s regionprops() function and return the results as PropArray, so that you can access using flexible slicing. For example, if a tcyx-image is analyzed with
properties=("X", "Y")
, then you can get X’s time-course profile of channel 1 at label 3 byprop["X"]["p=5;c=1"]
orprop.X["p=5;c=1"]
.- Parameters
properties (iterable, optional) – properties to analyze, see
skimage.measure.regionprops
.extra_properties (iterable of callable, optional) – extra properties to analyze, see
skimage.measure.regionprops
.
- Returns
Dictionary has keys of properties that are specified by properties. Each value has the array of properties.
- Return type
DataDict of PropArray
Examples
Measure region properties around single molecules.
>>> coords = img.centroid_sm() >>> img.specify(coords, 3, labeltype="circle") >>> props = img.regionprops()
- remove_fine_objects(length: float = 10, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Remove fine objects using diameter_opening.
- Parameters
length (float, default is 10) – Objects longer than this will be removed.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Image with large objects removed.
- Return type
See also
- remove_large_objects(radius: float = 5, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Remove large objects using opening. Those objects that were not removed by opening will be removed in output.
- Parameters
radius (float, optional) – Objects with radius larger than this value will be removed.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Image with large objects removed.
- Return type
See also
- remove_skeleton_structure(structure: str = 'tip', *, connectivity: int = None, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Remove certain structure from skeletonized images.
- Parameters
structure (str, default is "tip") – What type of structure to remove.
connectivity (int, optional) – Connectivity of pixels. See
skimage.measure.label
.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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Processed image.
- Return type
- rescale(scale: float = 0.0625, *, dims: Optional[Union[str, int]] = None, order: int = None) impy.arrays.imgarray.ImgArray [source]¶
Rescale image.
- Parameters
scale (float, optional) – scale of the new image.
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"
.order (int, default is 1) –
Spline interpolation order. For more details see here.
- Returns
Rescaled image.
- Return type
- rescale_intensity(in_range: tuple[int | str, int | str] = ('0%', '100%'), dtype=<class 'numpy.uint16'>) ImgArray [source]¶
Rescale the intensity of the image using skimage.exposure.rescale_intensity().
- Parameters
in_range (two scalar values, default is (0%, 100%)) – Range of lower/upper limit.
dtype (numpy dtype, default is np.uint16) – Output dtype.
- Returns
Rescaled image with temporal attribute
- Return type
- rof_filter(lmd: float = 0.05, tol: float = 0.0001, max_iter: int = 50, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Rudin-Osher-Fatemi’s total variation denoising.
- Parameters
lmd (float, default is 0.05) – Constant value in total variation.
tol (float, default is 1e-4) – Iteration stops when gain is under this value.
max_iter (int, default is 50) – Maximum number of iterations.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image
- Return type
- rolling_ball(radius: float = 30, prefilter: str = 'mean', *, return_bg: bool = False, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Subtract Background using rolling-ball algorithm.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
prefilter (str, {"mean", "median", "none"}) – If apply 3x3 averaging before creating background.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Background subtracted image.
- Return type
- rotate(degree: float, center='center', *, mode='constant', cval: float = 0, dims: Optional[Union[str, int]] = 2, order: int = 1, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
2D rotation of an image around a point. Outside will be padded with zero. For n-D images, this implementation is faster than
scipy.ndimage.rotate
.- Parameters
degree (float) – Clockwise degree of rotation. Not radian.
center (str or array-like, optional) – Rotation center coordinate. By default the center of image will be the rotation center.
mode (str) – Padding mode. See
scipy.ndimage.affine_transform
for details.cval (float, default is 0) – Constant value to fill outside the image for mode == “constant”.
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"
.order (int, default is 1) –
Spline interpolation order. For more details see here.
update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Rotated image.
- Return type
- skeletonize(radius: float = 0, *, dims: Optional[Union[str, int]] = None, update=False) impy.arrays.imgarray.ImgArray [source]¶
Skeletonize images. Only works for binary images.
- Parameters
radius (float, optional) – Radius of skeleton. This is achieved simply by dilation of skeletonized results.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Skeletonized image.
- Return type
- smooth_mask(sigma: float = 2.0, dilate_radius: float = 2.0, mask_light: bool = False, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Smoothen binary mask image at its edges. This is useful to make a “soft mask”.
- Parameters
sigma (float, default is 2.0) – Standard deviation of Gaussian blur.
dilate_radius (float, default is 2.0) – Radius in pixel that will be used to dilate mask before blurred.
mask_light (bool, default is False) – If true, mask array is considered to mask other image at its True values. Otherwise mask array plays more like a weight array, that is, False region will be zero.
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
Smoothened mask image.
- Return type
- split_pixel_unit(center: tuple[float, float] = (0.5, 0.5), *, order: int = 1, angle_order: list[int] = None, newaxis: str = 'a') impy.arrays.imgarray.ImgArray [source]¶
Split a \((2N, 2M)\)-image into four \((N, M)\)-images for each other pixels. Generally, image acquisition with a polarization camera will output \((2N, 2M)\)-image with \(N \times M\) pixel units:
0
1
0
1
0
1
3
2
3
2
3
2
0
1
0
1
0
1
3
2
3
2
3
2
This function generates images only consist of positions of [0], [1], [2] or [3]. Strictly, each image is acquired from different position (the pixel (i,j) in [0]-image and the pixel (i,j) in [1]-image are acquired from different positions). This function also complement for this difference by Affine transformation and spline interpolation.
- Parameters
center (tuple (a, b), where \(0 \le a \le 1\) and \(0 \le b \le 1\), default is (0, 0)) –
Coordinate that will be considered as the center. For example, center=(0, 0) means the most upper left pixel, and center=(0.5, 0.5) means the middle point of a pixel unit.
0, 1 3, 2
becomes
(0, 0), (0, 1) (1, 0), (1, 1)
- orderint, default is 1
Spline interpolation order. For more details see here.
- angle_orderlist of int, default is [2, 1, 0, 3]
Specify which pixels correspond to which polarization angles. 0, 1, 2 and 3 corresponds to polarization of 0, 45, 90 and 135 degree respectively. This list will be directly passed to np.ndarray like
arr[angle_order]
to sort it. For example, if a pixel unit receives polarized light like below:[0] [1] [ 90] [ 45] [|] [/] [2] [3] -> [135] [ 0] or [\] [-]
then
angle_order
should be [2, 1, 0, 3].
- Returns
Axis “a” is added in the first dimension. For example, If input is “tyx”-axes, then output will be “atyx”-axes.
- Return type
Examples
Extract polarization in 0-, 45-, 90- and 135-degree directions from an image that is acquired from a polarization camera, and calculate total intensity of light by averaging.
>>> img_pol = img.split_pixel_unit() >>> img_total = img_pol.proj(axis="a")
- std_filter(radius: float = 1, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Standard deviation filter.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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
Filtered image
- Return type
- stokes(*, along: str = 'a') dict [source]¶
Generate stocks images from an image stack with polarized images. Currently, Degree of Linear Polarization (DoLP) and Angle of Polarization (AoP) will be calculated. Those irregular values (np.nan, np.inf) will be replaced with 0. Be sure that to calculate DoPL correctly background subtraction must be applied beforehand because stokes parameter
s0
is affected by absolute intensities.- Parameters
along (str, default is "a") – To define which axis is polarization angle axis. Along this axis the angle of polarizer must be in order of 0, 45, 90, 135 degree.
- Returns
Dictionaly with keys “dolp” and “aop”, which correspond to DoPL and AoP respectively.
- Return type
dict
Examples
Calculate AoP image from the raw image and display them.
>>> img_pol = img.split_polarization() >>> dpol = img_pol.stokes() >>> ip.gui.add(img_pol.proj()) >>> ip.gui.add(dpol.aop.rad2deg())
References
Yang, J., Qiu, S., Jin, W., Wang, X., & Xue, F. (2020). Polarization imaging model considering the non-ideality of polarizers. Applied optics, 59(2), 306-314.
Feng, B., Guo, R., Zhang, F., Zhao, F., & Dong, Y. (2021). Calculation and hue mapping of AoP in polarization imaging. May. https://doi.org/10.1117/12.2523643
- stretch(scale, center='center', *, mode: str = 'constant', cval: float = 0, dims: Optional[Union[str, int]] = None, order: int = 1) impy.arrays.imgarray.ImgArray [source]¶
2D stretching of an image from a point.
- Parameters
scale (array-like) – Stretch factors.
center (str or array-like, optional) – Rotation center coordinate. By default the center of image will be the rotation center.
mode (str) – Padding mode. See
scipy.ndimage.affine_transform
for details.cval (float, default is 0) – Constant value to fill outside the image for mode == “constant”.
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"
.order (int, default is 1) –
Spline interpolation order. For more details see here.
- Returns
Stretched image.
- Return type
- structure_tensor_eig(sigma: Union[Sequence[float], float] = 1, *, dims: Optional[Union[str, int]] = None) tuple[impy.arrays.imgarray.ImgArray, impy.arrays.imgarray.ImgArray] [source]¶
Calculate structure tensor’s eigenvalues and eigenvectors.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
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
Arrays of eigenvalues and eigenvectors. The axis
"l"
denotes the index of eigenvalues. l=0 means the smallest eigenvalue."r"
denotes the index of spatial dimensions. For 3D image, r=0 means z-element of an eigenvector.- Return type
ImgArray and ImgArray
- structure_tensor_eigval(sigma: Union[Sequence[float], float] = 1, *, dims: Optional[Union[str, int]] = None) impy.arrays.imgarray.ImgArray [source]¶
Calculate structure tensor’s eigenvalues and eigenvectors.
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
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
Array of eigenvalues. The axis
"l"
denotes the index of eigenvalues. l=0 means the smallest eigenvalue.- Return type
- threshold(thr: float | str = 'otsu', *, along: str = None, **kwargs) ImgArray [source]¶
- Parameters
thr (float or str or None, optional) – Threshold value, or thresholding algorithm.
along (str, optional) – Dimensions that will not share the same threshold. For instance, if
along="c"
then threshold intensities are determined for every channel. Ifthr
is float,along
will be ignored.**kwargs – Keyword arguments that will passed to function indicated in ‘method’.
- Returns
Boolian array.
- Return type
Examples
- Substitute outliers to 0.
>>> thr = img.threshold("99%") >>> img[thr] = 0
- tiled_lowpass_filter(cutoff: float = 0.2, chunks='auto', order: int = 2, overlap: int = 16, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Tile-by-tile Butterworth low-pass filter. This method is an approximation of the standard low-pass filter, which would be useful when the image is large.
- Parameters
cutoff (float or array-like, default is 0.2) – Cutoff frequency.
chunks (str or sequence of int) – Chunk size of each lowpass filter task.
order (float, default is 2) – Steepness of cutoff.
overlap (int, default is 16) – Overlapping pixels at the edges of tiles.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- tophat(radius: float = 30, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Tophat morphological image processing. This is useful for background subtraction.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- track_drift(along: str = None, show_drift: bool = False, upsample_factor: int = 10) MarkerFrame [source]¶
Calculate yx-directional drift using the method of skimage.registration.phase_cross_correlation.
- Parameters
along (str, optional) – Along which axis drift will be calculated.
show_drift (bool, default is False) – If True, plot the result.
upsample_factor (int, default is 10) – Up-sampling factor when calculating phase cross correlation.
- Returns
DataFrame structure with x,y columns
- Return type
- track_template(template: np.ndarray, bg=None, along: str = 't') MarkerFrame [source]¶
Tracking using template matching. For every time frame, matched region is interpreted as a new template and is used for the next template. To avoid slight shifts accumulating to the template image, new template image will be fitteg to the old one by phase cross correlation.
- Parameters
template (np.ndarray) – Template image. Must be 2 or 3 dimensional.
bg (float, optional) – Background intensity. If not given, it will calculated as the minimum value of the original image.
along (str, default is "t") – Which axis will be the time axis.
- Returns
Centers of matched templates.
- Return type
- unmix(matrix, bg=None, *, along: str = 'c', update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Unmix fluorescence leakage between channels in a linear way. For example, a blue/green image, fluorescent leakage can be written as following equation:
\(\left\{\begin{array}{ll} B_{obs} = B_{real} + a \cdot G_{real} & \\G_{obs} = b \cdot B_{real} + G_{real} & \end{array} \right.\)
where “obs” means observed intensities, “real” means the real intensity. In this linear case, leakage matrix:
\(M = \begin{bmatrix} 1 & a \\b & 1 \end{bmatrix} \\\)
\(V_{obs} = M \cdot V_{real}\)
must be predefined. If M is given, then real intensities can be restored by:
\(V_{real} = M^{-1} \cdot V_{obs}\)
- Parameters
matrix (array-like) – Leakage matrix. The (i, j) component of the matrix is the leakage from i-th channel to j-th channel.
bg (array-like, optional) – Vector of background intensities for each channel. If not given, it is assumed to be the minimum value of each channel.
along (str, default is "c") – The axis of channel.
update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Unmixed image.
- Return type
Examples
- Complement the channel-0 to channel-1 leakage.
>>> mtx = [[1.0, 0.4], >>> [0.0, 1.0]] >>> bg = [1500, 1200] >>> unmixed_img = img.unmix(mtx, bg)
- voronoi(coords: Coords, *, inf: nDInt = None, dims: Dims = 2) ImgArray [source]¶
Voronoi segmentation of an image. Image region labeled with $i$ means that all the points in the region are closer to the $i$-th point than any other points.
- Parameters
coords (MarkerFrame or (N, 2) array-like) – Coordinates of points.
inf (int, array of int, optional) – Distance to infinity points. If not provided, infinity points are placed at 100 times further positions relative to the image shape.
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
Image labeled with segmentation.
- Return type
- watershed(coords: MarkerFrame = None, *, connectivity: int = 1, input: str = 'distance', min_distance: float = 2, dims: Dims = None) Label [source]¶
Label segmentation using watershed algorithm.
- Parameters
coords (MarkerFrame, optional) – Returned by such as peak_local_max(). Array of coordinates of peaks.
{connectivity} –
input (str, optional) –
What image will be the input of watershed algorithm.
”self” … self is used.
”distance” … distance map of self.labels is used.
{dims} –
- Returns
Updated labels.
- Return type
- wavelet_denoising(noise_sigma: float = None, *, wavelet: str = 'db1', mode: str = 'soft', wavelet_levels: int = None, method: str = 'BayesShrink', max_shifts: int | tuple = 0, shift_steps: int | tuple = 1, dims: Dims = None) ImgArray [source]¶
Wavelet denoising. Because it is not shift invariant,
cycle_spin
is called inside the function.- Parameters
noise_sigma (float, optional) – Standard deviation of noise, if known.
wavelet (str, default is "db1") – Any options of pywt.wavelist.
mode ({"soft", "hard"}, default is "soft") – Type of denoising.
wavelet_levels (int, optional) – The number of wavelet decomposition levels to use.
method ({"BayesShrink", "VisuShrink"}, default is "BayesShrink") – Thresholding method to be used
max_shifts (int or tuple, default is 0) – Shifts in range(0, max_shifts+1) will be used.
shift_steps (int or tuple, default is 1) – Step size of shifts.
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
Denoised image.
- Return type
- wiener(psf: numpy.ndarray, lmd: float = 0.1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Classical wiener deconvolution. This algorithm has the serious ringing problem if parameters are set to wrong values.
\(F[Y_{res}] = \frac{F[Y_{obs}] \cdot \bar{H}}{|H|^2 + \lambda}\)
\(Y_{obs}\): observed image; \(Y_{res}\): restored image; \(H\) : FFT of point spread function (PSF);
- Parameters
psf (np.ndarray) – Point spread function.
lmd (float, default is 0.1) – Constant value used in the deconvolution. See Formulation below.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Deconvolved image.
- Return type
- impy.arrays.imgarray.wave_num(sl: slice, s: int, uf: int) numpy.ndarray [source]¶
A function that makes wave number vertical vector. Returned vector will be [k/s, (k + 1/uf)/s, (k + 2/uf)/s, …] (where k = sl.start)
- Parameters
sl (slice) – Slice that specify which part of the image will be transformed.
s (int) – Size along certain dimension.
uf (int) – Up-sampling factor of certain dimension.
impy.arrays.label module¶
- class impy.arrays.label.Label(obj, name=None, axes=None, dirpath=None, history=None, metadata=None, dtype=None)[source]¶
Bases:
impy.arrays.bases.historyarray.HistoryArray
- dirpath: str¶
- expand_labels(distance: int = 1, *, dims=None) impy.arrays.label.Label [source]¶
Expand areas of labels.
- Parameters
distance (int, optional) – The distance to expand, by default 1
{dims} –
- Returns
Same array but labels are updated.
- Return type
- increment(n: int) impy.arrays.label.Label [source]¶
- increment_iter(axes) impy.arrays.label.Label [source]¶
- name: str¶
- opening(radius: float = 1, *, dims=None, update: bool = False) impy.arrays.label.Label [source]¶
Morphological opening.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Opened labels
- Return type
- optimize() impy.arrays.label.Label [source]¶
- proj(axis=None, forbid_overlap=False) impy.arrays.label.Label [source]¶
Label projection. This function is useful when zyx-labels are drawn but you want to reduce the dimension.
- Parameters
axis (str, optional) – Along which axis projection will be calculated. If None, most plausible one will be chosen.
forbid_overlap (bool, default is False) – If True and there were any label overlap, this function will raise ValueError.
- Returns
Projected labels.
- Return type
- relabel() impy.arrays.label.Label [source]¶
impy.arrays.labeledarray module¶
- class impy.arrays.labeledarray.LabeledArray(obj, name=None, axes=None, dirpath=None, history=None, metadata=None, dtype=None)[source]¶
Bases:
impy.arrays.bases.historyarray.HistoryArray
- append_label(label_image: numpy.ndarray, new: bool = False) impy.arrays.label.Label [source]¶
Append new labels from an array. This function works for boolean or signed int arrays.
- Parameters
label_image (np.ndarray) – Labeled image.
new (bool, default is False) – If True, existing labels will be removed anyway.
- Returns
New labels.
- Return type
Example
Make label from different channels.
>>> thr0 = img["c=0"].threshold("90%") >>> thr0.label() # binary to label >>> thr1 = img["c=1"].threshold("90%") >>> thr1.label() # binary to label >>> img.append_label(thr0.labels) >>> img.append_label(thr1.labels)
If thr0 has 100 labels and thr1 has 150 labels then img will have \(100+150=250\) labels.
- as_float() impy.arrays.labeledarray.LabeledArray [source]¶
- as_img_type(dtype=<class 'numpy.uint16'>) impy.arrays.labeledarray.LabeledArray [source]¶
- as_uint16() impy.arrays.labeledarray.LabeledArray [source]¶
- as_uint8() impy.arrays.labeledarray.LabeledArray [source]¶
- crop_center(scale: Union[Sequence[float], float] = 0.5, *, dims=2) impy.arrays.labeledarray.LabeledArray [source]¶
Crop out the center of an image.
- Parameters
scale (float or array-like, default is 0.5) – Scale of the cropped image. If an array is given, each axis will be cropped in different scales, using each value respectively.
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
CroppedImage
- Return type
Examples
Create a \(512\times512\) image from a \(1024\times1024\) image.
>>> img_cropped = img.crop_center(scale=0.5)
Create a \(21\times256\times256\) image from a \(63\times1024\times1024\) image.
>>> img_cropped = img.crop_center(scale=[1/3, 1/2, 1/2])
- crop_kernel(radius: Union[Sequence[int], int] = 2) impy.arrays.labeledarray.LabeledArray [source]¶
Make a kernel from an image by cropping out the center region. This function is useful especially in ImgArray.defocus().
- Parameters
radius (int or array-like of int, default is 2) – Radius of the kernel.
- Returns
Kernel
- Return type
Examples
Make a \(4\times4\times4\) kernel from a point spread function image (suppose the image shapes are all even numbers).
>>> psf = ip.imread(r".../PSF.tif") >>> psfker = psf.crop_kernel() >>> psfer.shape (4, 4, 4)
- dirpath: str¶
- extract(label_ids=None, filt=None, cval: float = 0) impy.collections.DataList[impy.arrays.labeledarray.LabeledArray] [source]¶
Extract certain regions of the image and substitute others to cval.
- Parameters
label_ids (int or iterable of int, by default all the label IDs.) – Which label regions are extracted.
filt (callable, optional) – If given, only regions X that satisfy filt(self, X) will extracted.
cval (float, default is 0.) – Constant value to fill regions outside the extracted labeled regions.
- Returns
Extracted image(s)
- Return type
DataList of LabeledArray
- for_each_channel(func: str, along: str = 'c', **kwargs) impy.arrays.labeledarray.LabeledArray [source]¶
Apply same function with different parameters for each channel. This function will be useful when the parameters are dependent on channels, like wave length.
- Parameters
func (str) – Function name to apply over channel axis.
along (str, default is "c") – Along which axis function will be applied to.
- Returns
output image stack
- Return type
- for_params(func: Callable | str, var: dict[str, Iterable] = None, **kwargs) DataList [source]¶
Apply same function with different parameters with same input. This function will be useful when you want to try different conditions to the same image.
- Parameters
func (callable or str) – Function to apply repetitively. If str, then member method will be called.
var (dict[str, Iterable], optional) – Name of variable and the values to try. If you want to try sigma=1,2,3 then you should give var={“sigma”: [1, 2, 3]}.
kwargs – Fixed paramters that will be passed to func. If var is not given and only one parameter is provided in kwargs, then kwargs will be var.
- Returns
List of outputs.
- Return type
Example
Try LoG filter with different Gaussian kernel size and visualize all of them in napari.
>>> out = img.for_params("log_filter", var={"sigma":[1, 2, 3, 4]}) # or >>> out = img.for_params("log_filter", sigma=[1, 2, 3, 4]) # then >>> ip.gui.add(out)
- imsave(save_path: str, dtype: DTypeLike = None)[source]¶
Save image at the same directory as the original image by default. For tif file format, if the image contains wrong axes for ImageJ (= except for tzcyx), then it will converted automatically if possible. For mrc file format, only zyx and yx is allowed. zyx-scale is also saved.
- Parameters
save_path (str) – File name.
dtype (dtype-like, optional) – In what data type img will be saved.
- Returns
- Return type
None
- imshow_comparewith(other: impy.arrays.labeledarray.LabeledArray, **kwargs)[source]¶
- label(label_image=None, *, dims=None, connectivity=None) impy.arrays.label.Label [source]¶
Run skimage’s label() and store the results as attribute.
- Parameters
label_image (array, optional) – Image to make label, by default self is used.
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"
.connectivity (int, optional) – Connectivity of pixels. See
skimage.measure.label
.
- Returns
Labeled image.
- Return type
Examples
Label the image with threshold and visualize with napari.
>>> thr = img.threshold() >>> img.label(thr) >>> ip.gui.add(img)
- label_if(label_image=None, filt=None, *, dims=None, connectivity=None) impy.arrays.label.Label [source]¶
Label image using label_image as reference image only if certain condition dictated in filt is satisfied. skimage.measure.regionprops_table is called inside every time image is labeled.
def filt(img, lbl, area, major_axis_length): return area>10 and major_axis_length>5
- Parameters
label_image (array, optional) – Image to make label, by default self is used.
filt (callable, positional argument but not optional) – Filter function. The first argument is intensity image sliced from self, the second is label image sliced from labeled label_image, and the rest arguments is properties that will be calculated using regionprops function. The property arguments must be named exactly same as the properties in regionprops. Number of arguments can be two.
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"
.connectivity (int, optional) – Connectivity of pixels. See
skimage.measure.label
.
- Returns
Labeled image
- Return type
Example
- Label regions if only intensity is high.
>>> def high_intensity(img, lbl, slice): >>> return np.mean(img[slice]) > 10000 >>> img.label_if(lbl, filt)
- Label regions if no hole exists.
>>> def no_hole(img, lbl, euler_number): >>> return euler_number > 0 >>> img.label_if(lbl, filt)
- Label regions if centroids are inside themselves.
>>> def no_hole(img, lbl, centroid): >>> yc, xc = map(int, centroid) >>> return lbl[yc, xc] > 0 >>> img.label_if(lbl, filt)
- name: str¶
- proj_labels(axis=None, forbid_overlap=False) impy.arrays.label.Label [source]¶
Label projection. This function is useful when zyx-labels are drawn but you want to reduce the dimension.
- Parameters
axis (str, optional) – Along which axis projection will be calculated. If None, most plausible one will be chosen.
forbid_overlap (bool, default is False) – If True and there were any label overlap, this function will raise ValueError.
- Returns
Projected labels.
- Return type
- property range¶
- remove_edges(pixel: Union[Sequence[int], int] = 1, *, dims=2) impy.arrays.labeledarray.LabeledArray [source]¶
Remove pixels from the edges.
- Parameters
pixel (int or array-like, default is 1) – Number of pixels to remove. If an array is given, each axis will be cropped with different pixels, using each value respectively.
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
Cropped image.
- Return type
- reslice(a, b=None, *, order: int = 1) impy.arrays.specials.PropArray [source]¶
Measure line profile (kymograph) iteratively for every slice of image. This function is almost same as skimage.measure.profile_line, but can reslice 3D-images. The argument linewidth is not implemented here because it is useless.
- Parameters
a (array-like) – Path or source coordinate. If the former, it must be like: a = [[y0, x0], [y1, x1], …, [yn, xn]]
b (array-like, optional) – Destination coordinate. If specified, a must be the source coordinate.
order (int, default is 1) –
Spline interpolation order. For more details see here.
- Returns
Line scans.
- Return type
Examples
Rescile along a line and fit to a model function for every time frame.
>>> scan = img.reslice([18, 32], [53, 48]) >>> out = scan.curve_fit(func, init, return_fit=True) >>> plt.plot(scan[0]) >>> plt.plot(out.fit[0])
Rescile along a path.
>>> scan = img.reslice([[18,32], [53,48], [22,45], [28, 32]])
- rotated_crop(origin, dst1, dst2, dims=2) impy.arrays.labeledarray.LabeledArray [source]¶
Crop the image at four courners of an rotated rectangle. Currently only supports rotation within yx-plane. An rotated rectangle is specified with positions of a origin and two destinations dst1 and dst2, i.e., vectors (dst1-origin) and (dst2-origin) represent a rotated rectangle. Let origin be the origin of a xy-plane, the rotation direction from dst1 to dst2 must be counter- clockwise, or the cropped image will be reversed.
- Parameters
origin ((float, float)) –
dst1 ((float, float)) –
dst2 ((float, float)) –
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
Cropped array.
- Return type
- set_scale(other=None, **kwargs) None [source]¶
Set scales of each axis.
- Parameters
other (dict or object with axes) – New scales. If dict, it should be like {“x”: 0.1, “y”: 0.1}. If MetaArray, only scales of common axes are copied.
kwargs – This enables function call like set_scale(x=0.1, y=0.1).
- specify(center: Coords, radius: Coords, *, dims: Dims = None, labeltype: str = 'square') Label [source]¶
Make rectangle or ellipse labels from points.
- Parameters
center (array like or MarkerFrame) – Coordinates of centers. For MarkerFrame, it must have the same axes order.
radius (float or array-like) – Radius of labels.
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"
.labeltype (str, default is "square") – The shape of labels.
- Returns
Labeled regions.
- Return type
Examples
- Find single molecules, draw circular labels around them if mean values were greater than 100.
>>> coords = img.find_sm() >>> filter_func = lambda a: np.mean(a) > 100 >>> img.specify(coords, 3.5, filt=filter_func, labeltype="circle") >>> ip.gui.add(img)
- split(axis=None) impy.collections.DataList[impy.arrays.labeledarray.LabeledArray] [source]¶
Split n-dimensional image into (n-1)-dimensional images. This function is different from np.split, which split an array into smaller pieces (n-D to n-D).
- Parameters
axis (str or int, optional) – Along which axis the original image will be split, by default “c”
- Returns
Separate images
- Return type
list of arrays
- tile(shape: Optional[tuple[int, int]] = None, along: Optional[str] = None, order: Optional[str] = None) impy.arrays.labeledarray.LabeledArray [source]¶
Tile images in a certain order. Label is also tiled in the same manner.
- Parameters
shape (tuple[int, int], optional) – Grid shape. This parameter must be specified unless the length of along is 2.
along (str, optional) – Axis (Axes) over which will be iterated.
order – Order of iteration. “r” means row-wise and “c” means column-wise.
- Returns
Tiled array
- Return type
Examples
Read images as stack and tile them in grid shape \(5 \times 4\).
>>> img = ip.imread_collection(r"C:\...") >>> tiled_img = img.tile((5, 4))
Read OME-TIFF images
>>> img = ip.imread_stack(r"C:\...\Images_MMStack-Pos_$i_$j.ome.tif") >>> tiled_img = img.tile()
impy.arrays.lazy module¶
- class impy.arrays.lazy.LazyImgArray(obj: da.core.Array, name: str = None, axes: str = None, dirpath: str = None, history: list[str] = None, metadata: dict = None)[source]¶
Bases:
impy.arrays.axesmixin.AxesMixin
- additional_props = ['dirpath', 'metadata', 'name']¶
- affine(matrix=None, scale=None, rotation=None, shear=None, translation=None, *, mode='constant', cval=0, output_shape=None, order=1, dims=None) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.affine. This function returns the same result but the value is evaluated lazily as an dask array.
Convert image by Affine transformation. 2D Affine transformation is written as:
\[\begin{split}\begin{bmatrix} y'\\ x' \\1 \end{bmatrix} = \begin{bmatrix} A_{00} & A_{01} & A_{02} \\ A_{10} & A_{11} & A_{12} \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} y \\x\\ 1 \end{bmatrix}\end{split}\]and similarly, n-D Affine transformation can be described as (n+1)-D matrix.
- Parameters
matrix – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.scale – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.rotation – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.shear – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.translation – Affine transformation parameters. See
skimage.transform.AffineTransform
for details.mode – Padding mode, constant value and the shape of output. See
scipy.ndimage.affine_transform
for details.cval – Padding mode, constant value and the shape of output. See
scipy.ndimage.affine_transform
for details.output_shape – Padding mode, constant value and the shape of output. See
scipy.ndimage.affine_transform
for details.order (int, default is 1) –
Spline interpolation order. For more details see here.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Transformed image.
- Return type
- apply_dask_func(funcname: str, *args, **kwargs) impy.arrays.lazy.LazyImgArray [source]¶
Apply dask array function to the connected dask array.
- Parameters
funcname (str) – Name of function to apply.
args – Parameters that will be passed to funcname.
kwargs – Parameters that will be passed to funcname.
- Returns
Updated one
- Return type
- as_float() impy.arrays.lazy.LazyImgArray [source]¶
- as_img_type(dtype=<class 'numpy.uint16'>) impy.arrays.lazy.LazyImgArray [source]¶
- as_uint16() impy.arrays.lazy.LazyImgArray [source]¶
- as_uint8() impy.arrays.lazy.LazyImgArray [source]¶
- binning(binsize: int = 2, method='mean', *, check_edges: bool = True, dims: Optional[Union[str, int]] = None) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.binning. This function returns the same result but the value is evaluated lazily as an dask array.
Binning of images. This function is similar to
rescale
but is strictly binned by \(N \times N\) blocks. Also, any numpy functions that accept “axis” argument are supported for reduce functions.- Parameters
binsize (int, default is 2) – Bin size, such as 2x2.
method (str or callable, default is numpy.mean) – Reduce function applied to each bin.
check_edges (bool, default is True) – If True, only divisible
binsize
is accepted. If False, image is cropped at the end to match binsize.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
Binned image
- Return type
- property chunk_info¶
- property chunksize¶
- closing(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.closing. This function returns the same result but the value is evaluated lazily as an dask array.
Morphological closing. If input is binary image, the running function will automatically switched to
binary_closing
to speed up calculation.- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- compute(ignore_limit: bool = False) impy.arrays.imgarray.ImgArray [source]¶
Compute all the task and convert the result into ImgArray. If image size overwhelms MAX_GB then MemoryError is raised.
- convolve(kernel, *, mode: str = 'reflect', cval: float = 0, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.convolve. This function returns the same result but the value is evaluated lazily as an dask array.
General linear convolution by running kernel filtering.
- Parameters
kernel (array-like) – Convolution kernel.
mode (str, default is "reflect".) – Padding mode. See scipy.ndimage.convolve.
cval (int, default is 0) – Constant value to fill outside the image if mode == “constant”.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Convolved image.
- Return type
- crop_center(scale=0.5, *, dims=2) impy.arrays.lazy.LazyImgArray [source]¶
Copy of LabeledArray.crop_center. This function returns the same result but the value is evaluated lazily as an dask array.
Crop out the center of an image.
- Parameters
scale (float or array-like, default is 0.5) – Scale of the cropped image. If an array is given, each axis will be cropped in different scales, using each value respectively.
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
CroppedImage
- Return type
Examples
Create a \(512\times512\) image from a \(1024\times1024\) image.
>>> img_cropped = img.crop_center(scale=0.5)
Create a \(21\times256\times256\) image from a \(63\times1024\times1024\) image.
>>> img_cropped = img.crop_center(scale=[1/3, 1/2, 1/2])
- property data¶
- dilation(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.dilation. This function returns the same result but the value is evaluated lazily as an dask array.
Morphological dilation. If input is binary image, the running function will automatically switched to
binary_dilation
to speed up calculation.- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- drift_correction(shift: Coords = None, ref: ImgArray = None, *, zero_ave: bool = True, along: str = None, dims: Dims = 2, update: bool = False, **affine_kwargs) LazyImgArray [source]¶
Copy of ImgArray.drift_correction. This function returns the same result but the value is evaluated lazily as an dask array.
Drift correction using iterative Affine translation. If translation vectors
shift
is not given, then it will be determined usingtrack_drift
method of ImgArray.- Parameters
shift (DataFrame or (N, D) array, optional) – Translation vectors. If DataFrame, it must have columns named with all the symbols contained in
dims
.ref (ImgArray, optional) – The reference n-D image to determine drift, if
shift
was not given.zero_ave (bool, default is True) – If True, average shift will be zero.
along (str, optional) – Along which axis drift will be corrected.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
affine_kwargs – Keyword arguments that will be passed to
warp
.
- Returns
Corrected image.
- Return type
Examples
- Drift correction of multichannel image using the first channel as the reference.
>>> img.drift_correction(ref=img["c=0"])
- property dtype¶
- edge_filter(method: str = 'sobel', *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.edge_filter. This function returns the same result but the value is evaluated lazily as an dask array.
Sobel filter. This filter is useful for edge detection.
- Parameters
method (str, {"sobel", "farid", "scharr", "prewitt"}, default is "sobel") – Edge operator name.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- erosion(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.erosion. This function returns the same result but the value is evaluated lazily as an dask array.
Morphological erosion. If input is binary image, the running function will automatically switched to
binary_erosion
to speed up calculation.- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
{cval} –
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- fft(*, shape: int | Iterable[int] | str = 'same', shift: bool = True, dims: Dims = None) LazyImgArray [source]¶
Copy of ImgArray.fft. This function returns the same result but the value is evaluated lazily as an dask array.
Fast Fourier transformation. This function returns complex array, which is inconpatible with some ImgArray functions.
- Parameters
shape (int, iterable of int, "square" or "same") – Output shape. Input image is padded or cropped according to this value: - integers: padded or cropped to the specified shape. - “square”: padded to smallest 2^N-long square. - “same” (default): no padding or cropping.
shift (bool, default is True) – If True, call
np.fft.fftshift
in the end.double_precision (bool, default is False) – If True, FFT will be calculated using 64-bit float and 128-bit complex.
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
FFT image.
- Return type
See also
local_dft
- gaussian_filter(sigma: Union[Sequence[float], float] = 1.0, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.gaussian_filter. This function returns the same result but the value is evaluated lazily as an dask array.
Run Gaussian filter (Gaussian blur).
- Parameters
sigma (float or array of float, optional) – Standard deviation(s) of Gaussian filter. If a scalar value is given, same standard deviation will applied to all the spatial dimensions.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- property gb¶
- ifft(real: bool = True, *, shift: bool = True, dims=None) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.ifft. This function returns the same result but the value is evaluated lazily as an dask array.
Fast Inverse Fourier transformation. Complementary function with fft().
- Parameters
real (bool, default is True) – If True, only the real part is returned.
shift (bool, default is True) – If True, call
np.fft.ifftshift
at the first.double_precision (bool, default is False) – If True, FFT will be calculated using 64-bit float and 128-bit complex.
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
IFFT image.
- Return type
- property img¶
- imsave(tifname: str, dtype=None)[source]¶
Copy of LabeledArray.imsave. This function returns the same result but the value is evaluated lazily as an dask array.
Save image at the same directory as the original image by default. For tif file format, if the image contains wrong axes for ImageJ (= except for tzcyx), then it will converted automatically if possible. For mrc file format, only zyx and yx is allowed. zyx-scale is also saved.
- Parameters
save_path (str) – File name.
dtype (dtype-like, optional) – In what data type img will be saved.
- Returns
- Return type
None
- property itemsize¶
- kalman_filter(gain: float = 0.8, noise_var: float = 0.05, *, along: str = 't', dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.kalman_filter. This function returns the same result but the value is evaluated lazily as an dask array.
Kalman filter for image smoothing. This function is same as “Kalman Stack Filter” in ImageJ but support batch processing. This filter is useful for preprocessing of particle tracking.
- Parameters
gain (float, default is 0.8) – Filter gain.
noise_var (float, default is 0.05) – Initial estimate of noise variance.
along (str, default is "t") – Which axis will be the time axis.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image
- Return type
- laplacian_filter(radius: int = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.laplacian_filter. This function returns the same result but the value is evaluated lazily as an dask array.
Edge detection using Laplacian filter. Kernel is made by skimage’s function.
- Parameters
radius (int, default is 1) – Radius of kernel. Shape of kernel will be (2*radius+1, 2*radius+1).
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- mean_filter(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.mean_filter. This function returns the same result but the value is evaluated lazily as an dask array.
Mean filter. Kernel is filled with same values.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image
- Return type
- median_filter(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.median_filter. This function returns the same result but the value is evaluated lazily as an dask array.
Running median filter. This filter is useful for deleting outliers generated by noise.
- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- property ndim¶
- opening(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.opening. This function returns the same result but the value is evaluated lazily as an dask array.
Morphological opening. If input is binary image, the running function will automatically switched to
binary_opening
to speed up calculation.- Parameters
radius (float, optional) –
Radius of kernel structure. For instance, if input has two spatial dimensions,
radius=1
gives a structure[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
and
radius=1.8
gives a structure[[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- pad(pad_width, mode: str = 'constant', *, dims: Optional[Union[str, int]] = None, **kwargs) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.pad. This function returns the same result but the value is evaluated lazily as an dask array.
Pad image only for spatial dimensions.
- Parameters
pad_width – See documentation of np.pad().
mode – See documentation of np.pad().
**kwargs – See documentation of np.pad().
dims (int or str, optional) – Which dimension to pad.
- Returns
Padded image.
- Return type
Examples
Suppose
img
has zyx-axes.- Padding 5 pixels in zyx-direction:
>>> img.pad(5)
- Padding 5 pixels in yx-direction:
>>> img.pad(5, dims="yx")
- Padding 5 pixels in yx-direction and 2 pixels in z-direction:
>>> img.pad([(5,5), (4,4), (4,4)])
- Padding 10 pixels in z-(-)-direction and 5 pixels in z-(+)-direction.
>>> img.pad([(10, 5)], dims="z")
- power_spectra(shape='same', norm: bool = False, zero_norm: bool = False, *, dims: Optional[Union[str, int]] = None) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.power_spectra. This function returns the same result but the value is evaluated lazily as an dask array.
Return n-D power spectra of images, which is defined as:
\[P = Re(F[I_{img}])^2 + Im(F[I_{img}])^2\]- Parameters
shape (int, iterable of int, "square" or "same") – Output shape. Input image is padded or cropped according to this value: - integers: padded or cropped to the specified shape. - “square”: padded to smallest 2^N-long square. - “same” (default): no padding or cropping.
norm (bool, default is False) – If True, maximum value of power spectra is adjusted to 1.
double_precision (bool, default is False) – If True, FFT will be calculated using 64-bit float and 128-bit complex.
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
Power spectra
- Return type
See also
local_power_spectra
- proj(axis: str = None, method: str = 'mean') impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.proj. This function returns the same result but the value is evaluated lazily as an dask array.
Z-projection along any axis.
- Parameters
axis (str, optional) – Along which axis projection will be calculated. If None, most plausible one will be chosen.
method (str or callable, default is mean-projection.) – Projection method. If str is given, it will converted to numpy function.
mask (array-like, optional) – If provided, input image will be converted to np.ma.array and
method
will also be interpreted as an masked functio if possible.**kwargs – Other keyword arguments that will passed to projection function.
- Returns
Projected image.
- Return type
- rechunk(chunks='auto', *, threshold=None, block_size_limit=None, balance=False, update=False) impy.arrays.lazy.LazyImgArray [source]¶
Rechunk the bound dask array.
- Parameters
chunks – Passed directly to dask.array’s rechunk
threshold – Passed directly to dask.array’s rechunk
block_size_limit – Passed directly to dask.array’s rechunk
balance – Passed directly to dask.array’s rechunk
- Returns
Rechunked dask array is bound. History will not be updated.
- Return type
- release(update: bool = True) impy.arrays.lazy.LazyImgArray [source]¶
Compute all the tasks and store the data in memory map, and read it as a dask array again.
- property shape¶
- property size¶
- tiled_lowpass_filter(cutoff: float = 0.2, order: int = 2, overlap: int = 16, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.lazy.LazyImgArray [source]¶
Copy of ImgArray.tiled_lowpass_filter. This function returns the same result but the value is evaluated lazily as an dask array.
Tile-by-tile Butterworth low-pass filter. This method is an approximation of the standard low-pass filter, which would be useful when the image is large.
- Parameters
cutoff (float or array-like, default is 0.2) – Cutoff frequency.
chunks (str or sequence of int) – Chunk size of each lowpass filter task.
order (float, default is 2) – Steepness of cutoff.
overlap (int, default is 16) – Overlapping pixels at the edges of tiles.
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"
.update (bool, default is False) – If True, input itself is updated to the output.
- Returns
Filtered image.
- Return type
- track_drift(along: str = None, upsample_factor: int = 10) da.core.Array [source]¶
Copy of ImgArray.track_drift. This function returns the same result but the value is evaluated lazily as an dask array.
Calculate yx-directional drift using the method of skimage.registration.phase_cross_correlation.
- Parameters
along (str, optional) – Along which axis drift will be calculated.
show_drift (bool, default is False) – If True, plot the result.
upsample_factor (int, default is 10) – Up-sampling factor when calculating phase cross correlation.
- Returns
DataFrame structure with x,y columns
- Return type
impy.arrays.phasearray module¶
- class impy.arrays.phasearray.PhaseArray(obj, name=None, axes=None, dirpath=None, history=None, metadata=None, dtype=None, unit='rad', border=None)[source]¶
Bases:
impy.arrays.labeledarray.LabeledArray
- additional_props = ['dirpath', 'metadata', 'name', 'unit', 'border']¶
- binning(binsize: int = 2, *, check_edges: bool = True, dims: Optional[Union[str, int]] = None)[source]¶
- deg2rad() impy.arrays.phasearray.PhaseArray [source]¶
- dirpath: str¶
- fix_border() None [source]¶
Considering periodic boundary condition, fix the values by __mod__ method.
- mean_filter(radius: float = 1, *, dims: Optional[Union[str, int]] = None, update: bool = False) impy.arrays.phasearray.PhaseArray [source]¶
Mean filter using phase averaging method:
\(\arg{\sum_{k}{e^{i X_k}}}\)
- Parameters
radius (float, default is 1) – Radius of kernel.
dims (str or int, optional) – Spatial dimensions.
update (bool, default is False) – If update self to filtered image.
- Returns
Filtered image.
- Return type
- name: str¶
- property periodicity: float¶
- rad2deg() impy.arrays.phasearray.PhaseArray [source]¶
- regionprops(properties: tuple[str, ...] | str = ('phase_mean',), *, extra_properties=None) DataDict[str, PropArray] [source]¶
Run
skimage
’sregionprops()
function and return the results as PropArray, so that you can access using flexible slicing. For example, if a tcyx-image is analyzed withproperties=("X", "Y")
, then you can get X’s time-course profile of channel 1 at label 3 byprop["X"]["p=5;c=1"]
orprop.X["p=5;c=1"]
. In PhaseArray, instead of mean_intensity you should use “phase_mean”. The phase_mean function is included so that it can be passed inproperties
argument.- Parameters
properties (iterable, optional) – properties to analyze, see skimage.measure.regionprops.
extra_properties (iterable of callable, optional) – extra properties to analyze, see skimage.measure.regionprops.
- Returns
- Return type
DataDict of PropArray
Example
- Measure region properties around single molecules.
>>> coords = reference_img.centroid_sm() >>> img.specify(coords, 3, labeltype="circle") >>> props = img.regionprops()
- reslice(src, dst, *, order: int = 1) impy.arrays.specials.PropArray [source]¶
Measure line profile iteratively for every slice of image. Because input is phase, we can not apply standard interpolation to calculate intensities on float-coordinates.
- Parameters
src (array-like) – Source coordinate.
dst (array-like) – Destination coordinate.
order (int, default is 1) – Spline interpolation order.
dims (int or str, optional) – Spatial dimensions.
- Returns
Line scans.
- Return type
impy.arrays.specials module¶
- class impy.arrays.specials.PropArray(obj, *, name=None, axes=None, dirpath=None, metadata=None, propname=None, dtype=None)[source]¶
Bases:
impy.arrays.bases.metaarray.MetaArray
- additional_props = ['dirpath', 'metadata', 'name', 'propname']¶
- as_frame(colname: str = 'f') AxesFrame [source]¶
N-dimensional data to DataFrame. The intensity data is stored in the colname column.
- Parameters
colname (str, default is "f") – The name of new column.
- Returns
DataFrame with PropArray data.
- Return type
- curve_fit(f: Callable, p0=None, dims='t', return_fit: bool = True) impy.collections.DataDict[str, impy.arrays.specials.PropArray] [source]¶
Run scipy.optimize.curve_fit for each dimesion.
- Parameters
f (callable) – Model function.
p0 (array or callable, optional) – Initial parameter. Callable object that estimate initial paramter can also be passed here.
dims (str, by default "t") – Along which axes fitting algorithms are conducted.
return_fit (bool, by default True) – If fitting trajectories are returned. If the input array is large, this will save much memory.
- Returns
params : Fitting parameters covs : Covariances fit : fitting trajectories (if return_fit==True)
- Return type
- dirpath: str¶
- hist(along: str = 'p', bins: Optional[int] = None, cmap: str = 'jet', cmap_range: tuple[float, float] = (0.0, 1.0)) impy.arrays.specials.PropArray [source]¶
Plot histogram.
- Parameters
along (str, optional) – Which axis will be the x-axis of plot, by default None
bins (int, optional) – Bin number of histogram.
cmap (str, default is "jet") – Colormap of each graph.
cmap_range (tuple, default is (0, 1)) – Range of float for colormap iteration.
- Returns
- Return type
self
- name: str¶
- plot(along=None, cmap='jet', cmap_range=(0, 1))[source]¶
Plot all the results with x-axis defined by along.
- Parameters
along (str, optional) – Which axis will be the x-axis of plot, by default None
cmap (str, default is "jet") – Colormap of each graph.
cmap_range (tuple, default is (0, 1)) – Range of float for colormap iteration.