playnano.processing.video_processing module¶
Processing functions for whole AFM image stacks (time series of frames).
These functions take a 3D numpy.ndarray of shape
(n_frames, height, width) and return the processed stack and a dictionary of
metadata, which the ProcessingPipeline
stores in the step’s provenance. They cover:
frame alignment, to correct drift (
align_frames(),rolling_frame_align());cropping the NaN borders left by alignment (
intersection_crop(),crop_square());filling NaN pixels (
replace_nan()).
temporal_median_filter() and temporal_mean_filter() are planned
and not implemented yet.
- playnano.processing.video_processing.align_frames(stack: ndarray, reference_frame: int = 0, method: str = 'fft_cross_correlation', mode: str = 'pad', debug: bool = False, max_shift: int | None = None, pre_filter_sigma: float | None = None, max_jump: int | None = None)[source]¶
Align every frame of a stack to one reference frame by whole-pixel shifts.
The shift of each frame is the position of the peak of its cross-correlation with the reference frame. Each frame’s mean is subtracted before correlating, so height offsets between frames do not affect the result.
- Parameters:
stack (numpy.ndarray) – 3D image stack of shape (n_frames, height, width).
reference_frame (int, optional) – Index of the frame the others are aligned to. Default is 0.
method ({"fft_cross_correlation", "full_cross_correlation"}, optional) – How the cross-correlation is computed. Both find the same shifts; the FFT method is much faster and uses less memory on large frames. Default is
"fft_cross_correlation".mode ({"pad", "crop", "crop_square"}, optional) –
What to do with the borders after shifting. Default is
"pad"."pad": keep every pixel of every frame on a larger canvas, filling the gaps with NaN."crop": crop to the region covered by all frames (intersection_crop())."crop_square": crop to the largest centred square in that region (crop_square()).
debug (bool, optional) – If True, also return a third value with diagnostic output. Default is False.
max_shift (int, optional) – Largest shift to search for, in pixels along each axis. Default is None (no limit).
pre_filter_sigma (float, optional) – If given, frames are smoothed with a Gaussian filter of this standard deviation, in pixels, before correlating. The output frames are not smoothed. Default is None.
max_jump (int, optional) – Largest change in shift, in pixels, allowed between consecutive frames. For frame 1 the change from frame 0 is clipped to this value; from frame 2 on, a shift that changes by more is replaced by a linear extrapolation of the previous two shifts. Default is None (no limit).
- Returns:
aligned_stack (numpy.ndarray) – The aligned stack, as float32. With
mode="pad"it is larger than the input so every frame fits; with the crop modes it is smaller.metadata (dict) – Details of the alignment:
"reference_frame"(int): the reference frame used."method"(str): themethodused."mode"(str): themodeused."shifts"(numpy.ndarray of int, shape (n_frames, 2)): the (dy, dx) shift applied to each frame, in pixels."original_shape"(tuple): (height, width) of the input frames."aligned_shape"(tuple): (height, width) of the padded canvas, before any cropping."border_mask"(numpy.ndarray of bool): True where at least one frame has data, with the same height and width as the output."pre_filter_sigma","max_shift","max_jump": the values used."crop"(dict): only withmode="crop"or"crop_square"; the metadata fromintersection_crop()orcrop_square().
debug_outputs (dict) – Only returned if
debug=True:{"shifts": <copy of the shifts>}.
- Raises:
ValueError – If
stackis not 3D,reference_frameis outside0 .. n_frames - 1,methodormodeis not recognised, or a frame has no finite pixels.
Notes
Shifts are whole pixels; there is no subpixel interpolation. NaN and infinite pixels are ignored when finding the shifts (they are filled with the frame mean for the correlation only) and are kept in the output. Version 0.2.0 subtracts each frame’s mean for
"full_cross_correlation"too; before, that method found no drift on typical AFM data.Examples
>>> import numpy as np >>> from playnano.processing.video_processing import align_frames >>> rng = np.random.default_rng(0) >>> frame = rng.random((64, 64)) >>> moved = np.roll(frame, (2, -3), axis=(0, 1)) # 2 px down, 3 px left >>> aligned, meta = align_frames(np.stack([frame, moved])) >>> meta["shifts"] array([[ 0, 0], [-2, 3]]) >>> aligned.shape (2, 66, 67)
- playnano.processing.video_processing.crop_square(stack: ndarray, pad: int | tuple[int, ...] = 0) tuple[ndarray, dict][source]¶
Crop an aligned stack to the largest centred square where every frame has data.
The square is centred in the region found by
intersection_crop(), and its side is the shorter side of that region.- Parameters:
stack (numpy.ndarray) – 3D image stack of shape (n_frames, height, width), usually the output of an alignment with NaN borders.
pad (int or tuple of int, optional) –
Extra pixels to add around the crop. Default is 0.
int: the same on every side.
(v, h):vat the top and bottom,hat the left and right.(top, bottom, left, right): each side separately.
Where the padded crop goes beyond the stack, the new pixels are NaN.
- Returns:
cropped (numpy.ndarray) – The cropped (and padded) stack.
meta (dict) – Details of the crop, with the same keys as
intersection_crop()("operation"is"crop_square"), and also:"square_size": side of the square, in pixels."square_bounds":(y0, y1, x0, x1)of the square before padding."offset": (row, column) of the square’s corner within the intersection region.
If no pixel is finite in all frames, a copy of
stackis returned unchanged, the bounds are None andmeta["note"]says so.
- Raises:
ValueError – If
padis not an int or a tuple of 2 or 4 ints.
- playnano.processing.video_processing.intersection_crop(stack: ndarray, pad: int | tuple[int, ...] = 0) tuple[ndarray, dict][source]¶
Crop an aligned stack to the region where every frame has data.
The crop is the smallest rectangle containing every pixel that is finite in all frames. Use it after alignment with
mode="pad"to remove the NaN borders.- Parameters:
stack (numpy.ndarray) – 3D image stack of shape (n_frames, height, width), usually the output of an alignment with NaN borders.
pad (int or tuple of int, optional) –
Extra pixels to add around the crop. Default is 0.
int: the same on every side.
(v, h):vat the top and bottom,hat the left and right.(top, bottom, left, right): each side separately.
Where the padded crop goes beyond the stack, the new pixels are NaN.
- Returns:
cropped (numpy.ndarray) – The cropped (and padded) stack.
meta (dict) – Details of the crop. Bounds are
(y0, y1, x0, x1)in the input’s pixel coordinates, withy1andx1exclusive."operation":"crop_intersection"."original_shape","new_shape": (height, width) before and after."intersection_shape","intersection_bounds": the region where all frames are finite."requested_bounds": the intersection pluspad."applied_pad": (top, bottom, left, right) pixels of NaN added beyond the edges of the input."pad_param":padas (top, bottom, left, right).
If no pixel is finite in all frames, a copy of
stackis returned unchanged, the bounds are None andmeta["note"]says so.
- Raises:
ValueError – If
padis not an int or a tuple of 2 or 4 ints.
- playnano.processing.video_processing.register_video_processing() dict[str, Callable][source]¶
Return the built-in video processing functions.
Each takes a 3D stack and returns either the processed stack or a tuple of (stack, metadata).
- Returns:
Maps each step name (str) to its function, for example
"align_frames"toalign_frames().- Return type:
- playnano.processing.video_processing.replace_nan(stack: ndarray, mode: Literal['zero', 'mean', 'median', 'global_mean', 'constant'] = 'zero', value: float | None = None) tuple[ndarray, dict][source]¶
Replace NaN pixels in a stack.
Often used after alignment with
mode="pad", before steps that do not accept NaN.- Parameters:
stack (numpy.ndarray) – 3D image stack of shape (n_frames, height, width).
mode ({"zero", "mean", "median", "global_mean", "constant"}, optional) –
What to replace NaN with. Default is
"zero"."zero": 0."mean","median": the mean or median of the finite pixels of the same frame."global_mean": the mean of the finite pixels of the whole stack."constant":value.
value (float, optional) – Value to use with
mode="constant", where it is required.
- Returns:
filled (numpy.ndarray) – A copy of
stackwith NaN replaced, with the same shape and dtype.meta (dict) –
{"nans_filled": <number of NaN pixels>, "mode": mode, "value_used": value};"value_used"is None unlessmode="constant".
- Raises:
ValueError – If
modeis not recognised, ormode="constant"andvalueis None.
- playnano.processing.video_processing.rolling_frame_align(stack: ndarray, window: int = 5, mode: str = 'pad', debug: bool = False, max_shift: int | None = None, pre_filter_sigma: float | None = None, max_jump: int | None = None)[source]¶
Align each frame to the average of the frames aligned just before it.
The first frame is the starting reference. Each later frame is aligned, by phase cross-correlation and whole-pixel shifts, to the average of the last
windowaligned frames, so slow changes in the sample are followed.- Parameters:
stack (numpy.ndarray) – 3D image stack of shape (n_frames, height, width).
window (int, optional) – Number of most recently aligned frames averaged to make the reference. Default is 5.
mode ({"pad", "crop", "crop_square"}, optional) –
What to do with the borders after shifting. Default is
"pad"."pad": keep every pixel of every frame on a larger canvas, filling the gaps with NaN."crop": crop to the region covered by all frames (intersection_crop())."crop_square": crop to the largest centred square in that region (crop_square()).
debug (bool, optional) – If True, also return a third value with diagnostic output. Default is False.
max_shift (int, optional) – Largest shift allowed, in pixels along each axis; larger shifts are clipped to it. Default is None (no limit).
pre_filter_sigma (float, optional) – If given, frames are smoothed with a Gaussian filter of this standard deviation, in pixels, before correlating. The output frames are not smoothed. Default is None.
max_jump (int, optional) – From frame 2 on, a shift that differs from the previous one by more than this many pixels is replaced by a linear extrapolation of the previous two shifts. Default is None (no limit).
- Returns:
aligned_stack (numpy.ndarray) – The aligned stack, as float32. With
mode="pad"it is larger than the input so every frame fits; with the crop modes it is smaller.metadata (dict) – Details of the alignment:
"window"(int): thewindowused."method"(str): always"phase_cross_correlation"."mode"(str): themodeused."shifts"(numpy.ndarray of int, shape (n_frames, 2)): the (dy, dx) shift applied to each frame, in pixels."original_shape"(tuple): (height, width) of the input frames."aligned_shape"(tuple): (height, width) of the padded canvas, before any cropping."border_mask"(numpy.ndarray of bool): True where at least one frame has data, with the same height and width as the output."pre_filter_sigma","max_shift","max_jump": the values used."crop"(dict): only withmode="crop"or"crop_square"; the metadata fromintersection_crop()orcrop_square().
debug_outputs (dict) – Only returned if
debug=True:"shifts": a copy of the shifts."aligned_refs": list of the frames in the final reference window, each as(frame_index, y0, y1, x0, x1, fy0, fy1, fx0, fx1): the region of the working canvas and the matching region of the frame.
- Raises:
ValueError – If
stackis not 3D,windowis less than 1,modeis not recognised, or a frame has no finite pixels.
Notes
Shifts are whole pixels; there is no subpixel interpolation. NaN and infinite pixels are left out of the correlation and of the rolling reference, and are kept in the output. Version 0.1.1 crops
border_masktogether with the frames in the crop modes.See also
skimage.registration.phase_cross_correlationThe correlation used.
Examples
>>> import numpy as np >>> from playnano.processing.video_processing import rolling_frame_align >>> rng = np.random.default_rng(0) >>> frame = rng.random((64, 64)) >>> moved = np.roll(frame, (2, -3), axis=(0, 1)) >>> aligned, meta = rolling_frame_align(np.stack([frame, moved]), window=3) >>> meta["shifts"] array([[ 0, 0], [-2, 3]])
- playnano.processing.video_processing.temporal_mean_filter(stack: ndarray, window: int = 3) ndarray[source]¶
Not implemented yet: mean filter along the time axis.
Planned for a future release; calling it raises
NotImplementedError. It is not registered as a processing step.- Parameters:
stack (numpy.ndarray) – 3D image stack of shape (n_frames, height, width).
window (int, optional) – Number of frames in the filter window. Default is 3.
- Raises:
NotImplementedError – Always.
- playnano.processing.video_processing.temporal_median_filter(stack: ndarray, window: int = 3) ndarray[source]¶
Not implemented yet: median filter along the time axis.
Planned for a future release; calling it raises
NotImplementedError. It is not registered as a processing step.- Parameters:
stack (numpy.ndarray) – 3D image stack of shape (n_frames, height, width).
window (int, optional) – Number of frames in the filter window. Default is 3.
- Raises:
NotImplementedError – Always.