biapy.engine.denoisingο
Denoising workflow and utilities for BiaPy.
This module provides the Denoising_Workflow class for training and inference on image denoising tasks, as well as utility functions for patch manipulation, stratified coordinate sampling, and structN2V masking. It supports both 2D and 3D data, and includes implementations of various pixel manipulation strategies used in self-supervised denoising approaches such as Noise2Void (N2V).
- class biapy.engine.denoising.Denoising_Workflow(cfg, job_identifier, device, system_dict, args, **kwargs)[source]ο
Bases:
Base_WorkflowDenoising workflow where the goal is to remove noise from an image.
More details in our documentation.
- Parameters:
cfg (YACS configuration) β Running configuration.
job_identifier (str) β Complete name of the running job.
device (torch.device) β Device used.
args (argparse.Namespace) β Arguments used in BiaPyβs call.
- define_activations_and_channels()[source]ο
Define the activations to be applied to the model output and the channels that the model will output.
This function must define the following variables:
- self.model_output_channelsList of int
Number of channels for each output head of the model. E.g. [3] for a model with one head outputting 3 channels, [1, 5] for a model with two heads outputting 1 and 5 channels respectively, etc.
- self.model_output_channel_infoList of str
Information about the output channels. A value per output head of the model must be defined.
- self.separated_class_channelbool
Whether if we should expect a separated output channel for classification.
- self.head_activationsList of str
Activations to be applied to the model output. A value per output channel (not output head) of the model must be defined. βlinearβ and βce_sigmoidβ will not be applied. E.g. [βlinearβ] for a model with one channel, [βlinearβ, βsigmoidβ] for a model with two channels, etc.
Example of a correct definition of the function for a model with two output heads: 1) the first one will be predicting foreground and contours; 2) the second one will classify into 3 classes the predicted objects. In this case the following definition would be correct:
self.model_output_channels = [1, 3] self.model_output_channel_info = ["mask", "class"] self.separated_class_channel = True self.head_activations = ["ce_sigmoid", "ce_sigmoid", "ce_softmax", "ce_softmax", "ce_softmax"]
- define_metrics()[source]ο
Define the metrics to be used during training and test/inference.
This function must define the following variables:
- self.train_metricsList of functions
Metrics to be calculated during modelβs training.
- self.train_metric_namesList of str
Names of the metrics calculated during training.
- self.train_metric_bestList of str
To know which value should be considered as the best one. Options must be: βmaxβ or βminβ.
- self.test_metricsList of functions
Metrics to be calculated during modelβs test/inference.
- self.test_metric_namesList of str
Names of the metrics calculated during test/inference.
- self.lossFunction
Loss function used during training and test.
- metric_calculation(output: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor, targets: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor, train: bool = True, metric_logger: MetricLogger | None = None) Dict[source]ο
Execute the calculation of metrics defined in
define_metrics()function.- Parameters:
output (Torch Tensor) β Prediction of the model.
targets (Torch Tensor) β Ground truth to compare the prediction with.
train (bool, optional) β Whether to calculate train or test metrics.
metric_logger (MetricLogger, optional) β Class to be updated with the new metric(s) value(s) calculated.
- Returns:
out_metrics β Value of the metrics for the given prediction.
- Return type:
dict
- torchvision_model_call(in_img: Tensor, is_train: bool = False) Tensor | None[source]ο
Call a regular Pytorch model.
- Parameters:
in_img (torch.Tensor) β Input image to pass through the model.
is_train (bool, optional) β Whether if the call is during training or inference.
- Returns:
prediction β Image prediction.
- Return type:
torch.Tensor
- after_merge_patches(pred: Tensor)[source]ο
Execute steps needed after merging all predicted patches into the original image.
- Parameters:
pred (Torch Tensor) β Model prediction.
- after_full_image(pred: ndarray[tuple[int, ...], dtype[_ScalarType_co]])[source]ο
Execute steps needed after generating the prediction by supplying the entire image to the model.
- Parameters:
pred (NDArray) β Model prediction.
- biapy.engine.denoising.get_subpatch(patch, coord, local_sub_patch_radius, crop_patch=True)[source]ο
Extract a subpatch centered at a given coordinate, handling border cropping.
- Parameters:
patch (np.ndarray) β Input patch.
coord (tuple of int) β Center coordinate for the subpatch.
local_sub_patch_radius (int) β Radius of the subpatch to extract.
crop_patch (bool, optional) β Whether to crop the patch at the borders (default: True).
- Returns:
subpatch (np.ndarray) β Extracted subpatch.
crop_neg (int) β Negative crop offset.
crop_pos (int) β Positive crop offset.
- biapy.engine.denoising.random_neighbor(shape, coord)[source]ο
Sample a random neighbor coordinate different from the given coordinate.
- Parameters:
shape (tuple of int) β Shape of the patch.
coord (tuple of int) β Center coordinate.
- Returns:
rand_coords β Random neighbor coordinate.
- Return type:
list of int
- biapy.engine.denoising.sample_coords(shape, coord, sigma=4)[source]ο
Sample random coordinates from a normal distribution centered at coord.
- Parameters:
shape (tuple of int) β Shape of the patch.
coord (tuple of int) β Center coordinate.
sigma (float, optional) β Standard deviation for the normal distribution (default: 4).
- Returns:
coords β Sampled coordinates.
- Return type:
list of int
- biapy.engine.denoising.normal_int(mean, sigma, w)[source]ο
Sample an integer from a normal distribution and clip to valid range.
- Parameters:
mean (float) β Mean of the normal distribution.
sigma (float) β Standard deviation.
w (int) β Maximum allowed value (exclusive).
- Returns:
Sampled and clipped integer.
- Return type:
int
- biapy.engine.denoising.mask_center(local_sub_patch_radius, ndims=2)[source]ο
Create a mask with the center pixel set to zero.
- Parameters:
local_sub_patch_radius (int) β Radius of the patch.
ndims (int, optional) β Number of dimensions (default: 2).
- Returns:
mask β Boolean mask with center pixel set to zero.
- Return type:
np.ndarray
- biapy.engine.denoising.pm_normal_withoutCP(local_sub_patch_radius)[source]ο
Return a function that samples a random neighbor from a normal distribution (without center pixel).
- Parameters:
local_sub_patch_radius (int) β Radius of the local subpatch.
- Returns:
Function that takes (patch, coords, dims, structN2Vmask) and returns values from random neighbors.
- Return type:
Callable
- biapy.engine.denoising.pm_mean(local_sub_patch_radius)[source]ο
Return a function that computes the mean of the local neighborhood (excluding center pixel).
- Parameters:
local_sub_patch_radius (int) β Radius of the local subpatch.
- Returns:
Function that takes (patch, coords, dims, structN2Vmask) and returns mean values.
- Return type:
Callable
- biapy.engine.denoising.pm_median(local_sub_patch_radius)[source]ο
Return a function that computes the median of the local neighborhood (excluding center pixel).
- Parameters:
local_sub_patch_radius (int) β Radius of the local subpatch.
- Returns:
Function that takes (patch, coords, dims, structN2Vmask) and returns median values.
- Return type:
Callable
- biapy.engine.denoising.pm_uniform_withCP(local_sub_patch_radius)[source]ο
Return a function that samples a random value from the local neighborhood (including center pixel).
- Parameters:
local_sub_patch_radius (int) β Radius of the local subpatch.
- Returns:
Function that takes (patch, coords, dims, structN2Vmask) and returns random values.
- Return type:
Callable
- biapy.engine.denoising.pm_uniform_withoutCP(local_sub_patch_radius)[source]ο
Return a function that samples a random value from the local neighborhood (excluding center pixel).
- Parameters:
local_sub_patch_radius (int) β Radius of the local subpatch.
- Returns:
Function that takes (patch, coords, dims, structN2Vmask) and returns random values.
- Return type:
Callable
- biapy.engine.denoising.pm_normal_additive(pixel_gauss_sigma)[source]ο
Return a function that adds Gaussian noise to the center pixel.
- Parameters:
pixel_gauss_sigma (float) β Standard deviation of the Gaussian noise.
- Returns:
Function that takes (patch, coords, dims, structN2Vmask) and returns noisy values.
- Return type:
Callable
- biapy.engine.denoising.pm_normal_fitted(local_sub_patch_radius)[source]ο
Return a function that samples from a Gaussian fitted to the local neighborhood.
- Parameters:
local_sub_patch_radius (int) β Radius of the local subpatch.
- Returns:
Function that takes (patch, coords, dims, structN2Vmask) and returns sampled values.
- Return type:
Callable
- biapy.engine.denoising.pm_identity(local_sub_patch_radius)[source]ο
Return a function that simply returns the center pixel value (identity).
- Parameters:
local_sub_patch_radius (int) β Radius of the local subpatch (unused).
- Returns:
Function that takes (patch, coords, dims, structN2Vmask) and returns the center pixel value.
- Return type:
Callable
- biapy.engine.denoising.get_stratified_coords2D(box_size, shape)[source]ο
Generate stratified random coordinates for 2D patches.
- Parameters:
box_size (int) β Size of the box for stratification.
shape (tuple of int) β Shape of the 2D image.
- Returns:
(y_coords, x_coords) for sampled points.
- Return type:
tuple of lists
- biapy.engine.denoising.get_stratified_coords3D(box_size, shape)[source]ο
Generate stratified random coordinates for 3D patches.
- Parameters:
box_size (int) β Size of the box for stratification.
shape (tuple of int) β Shape of the 3D image.
- Returns:
(z_coords, y_coords, x_coords) for sampled points.
- Return type:
tuple of lists
- biapy.engine.denoising.apply_structN2Vmask(patch, coords, mask)[source]ο
Apply a structN2V mask to a 2D patch.
Each point in coords corresponds to the center of the mask. For each point in the mask with value=1, assign a random value.
- Parameters:
patch (np.ndarray) β Input patch to modify.
coords (np.ndarray or list) β Coordinates of mask centers.
mask (np.ndarray) β Binary mask to apply.
- biapy.engine.denoising.apply_structN2Vmask3D(patch, coords, mask)[source]ο
Apply a structN2V mask to a 3D patch.
Each point in coords corresponds to the center of the mask. For each point in the mask with value=1, assign a random value.
- Parameters:
patch (np.ndarray) β Input 3D patch to modify.
coords (np.ndarray or list) β Coordinates of mask centers (z, y, x).
mask (np.ndarray) β Binary mask to apply.
- biapy.engine.denoising.manipulate_val_data(X_val: ~numpy.ndarray[tuple[int, ...], ~numpy.dtype[~numpy._typing._array_like._ScalarType_co]], Y_val: ~numpy.ndarray[tuple[int, ...], ~numpy.dtype[~numpy._typing._array_like._ScalarType_co]], perc_pix: float = 0.198, shape: ~typing.Tuple[int, ...] = (64, 64), value_manipulation: ~typing.Callable = <function pm_uniform_withCP.<locals>.random_neighbor_withCP_uniform>)[source]ο
Manipulate validation data for self-supervised denoising.
Applies a value manipulation strategy (e.g., uniform, mean, median) to a percentage of pixels in the validation set, as used in Noise2Void/structN2V validation.
- Parameters:
X_val (NDArray) β Validation input data.
Y_val (NDArray) β Validation target data (will be overwritten).
perc_pix (float, optional) β Percentage of pixels to manipulate (default: 0.198).
shape (tuple of int, optional) β Shape of the patch (default: (64, 64)).
value_manipulation (Callable, optional) β Function to manipulate pixel values (default: pm_uniform_withCP(5)).
- biapy.engine.denoising.get_value_manipulation(n2v_manipulator, n2v_neighborhood_radius)[source]ο
Return a value manipulation function for N2V/structN2V based on the given strategy.
- Parameters:
n2v_manipulator (str) β Name of the manipulation strategy (e.g., βuniform_withCPβ).
n2v_neighborhood_radius (int) β Neighborhood radius for the manipulation.
- Returns:
Value manipulation function.
- Return type:
Callable