Transforms#
Normalize images before prediction, using the settings supplied with your checkpoint. For training, use the target functions and classes below.
Min-max normalization#
from cellseg_models_pytorch.transforms import minmax_normalize
- minmax_normalize(img, amin=0.0, amax=1.0, copy=False)#
Rescale an image’s pixel values to a chosen range, usually 0 to 1.
Use one minimum and maximum across the whole image, including all colour channels. This differs from normalizing each channel separately.
- Parameters:
img (ndarray | Tensor) – Image with shape (height, width, channels) or (height, width). NumPy arrays and PyTorch tensors are accepted. Tensors stay on their input device.
amin (float) – One output endpoint. Constant images use the lower endpoint.
amax (float) – Other output endpoint; the endpoints may be supplied in either order.
copy (bool) – Copy the NumPy input before normalization. Tensor results are always newly allocated. Defaults to False.
- Returns:
Min-max normalized image of the same shape and array/tensor type, with float32 dtype. The input is not modified.
- Raises:
ValueError – Input image does not have shape (H, W) or (H, W, C).
- Return type:
ndarray | Tensor
Example
>>> import numpy as np >>> from cellseg_models_pytorch.transforms import minmax_normalize >>> image = np.array([[10, 20], [30, 40]], dtype=np.uint8) >>> normalized = minmax_normalize(image) >>> normalized.shape == image.shape True >>> np.allclose([normalized.min(), normalized.max()], [0, 1], atol=1e-7) True
Other normalization functions#
These functions accept NumPy images and return new arrays. Choose the scaling used by your checkpoint. HW means height, width; HWC adds a channel axis.
Function |
Scaling |
|---|---|
|
Subtract channel means and multiply by channel scales; no clipping |
|
One pair of global percentiles, clipped to 0–1 |
|
Separate 1st/99th percentiles per channel; clipping optional |
|
Convert a floating image to uint8 for display/saving |
- normalize(img, mean=None, denom=None, copy=False)#
Subtract a mean and multiply by a scale for each image channel.
- Parameters:
img (ndarray) – NumPy HW or HWC image; H is height, W width and C channels.
mean (ndarray) – Per-channel values to subtract, shape (C,). None uses the input’s own channel means. For a grayscale image, a scalar is accepted.
denom (ndarray) – Per-channel multiplier, not divisor. To standardize, supply 1 / standard_deviation. None calculates this from the input image. A constant channel has zero standard deviation; supply a finite scale explicitly if such channels are possible.
copy (bool) – Copy input before conversion. The returned float32 array is new regardless; the input is not modified.
- Returns:
Float32 NumPy array with the original shape. No clipping is applied; output values need not lie between 0 and 1.
- Raises:
ValueError – The input does not have HW or HWC axes.
- Return type:
ndarray
Example
>>> image = np.array([[1, 3]], dtype=np.float32) >>> normalize(image, mean=np.array(2), denom=np.array(0.5)).tolist() [[-0.5, 0.5]]
- percentile_normalize(img, lower=0.01, upper=99.99, copy=False)#
Rescale global image percentiles to the range 0–1.
Use one pair of percentiles across all pixels and channels. This is different from percentile_normalize99, which computes separate channel percentiles.
- Parameters:
img (ndarray) – NumPy HW or HWC image; H is height, W width and C channels.
lower (float) – Lower percentile, in the range 0–100, mapped to 0.
upper (float) – Upper percentile, in the range 0–100, mapped to 1. Values outside the chosen interval are clipped by interpolation.
copy (bool) – Retained option. The current implementation copies input regardless.
- Returns:
A new float32 NumPy image with the original shape. The input is unchanged. If both percentile endpoints coincide, interpolation maps that value to 1.
- Raises:
ValueError – The image does not have HW or HWC axes; NumPy also validates percentile arguments.
- Return type:
ndarray
- percentile_normalize99(img, amin=None, amax=None, copy=False)#
Normalize each channel using its 1st and 99th spatial percentiles.
A zero percentile span maps to zero before optional clipping. Without clipping, values outside the percentile interval can fall outside [0, 1].
- Parameters:
img (ndarray) – NumPy image with (height, width) or (height, width, channels) axes. Percentiles are computed over height and width for each channel.
amin (float | None) – Optional lower bound for the normalized output.
amax (float | None) – Optional upper bound for the normalized output.
copy (bool) – If True, normalize the copy of the input. Defaults to False.
- Returns:
Normalized float32 image with the original shape. Constant channels are zero unless clipping moves zero to a requested bound.
- Raises:
ValueError – If the image does not have HW or HWC axes, or amin > amax.
- Return type:
ndarray
Examples
>>> percentile_normalize99(np.array([[0, 1], [2, 3]]), 0, 1).round(2) array([[0. , 0.33], [0.67, 1. ]], dtype=float32)
- float2ubyte(mat, normalize=False)#
Convert floating image values to uint8 pixel values.
- Parameters:
mat (ndarray) – Floating NumPy image. Output keeps its shape.
normalize (bool) – True first applies global min-max normalization to 0–1. False clips to -1–1 before conversion; negative values become zero.
- Returns:
A new uint8 image with values 0–255. The input is unchanged.
- Return type:
ndarray
Functions for training targets#
Generate training targets from 2D instance masks: 0 is background and a positive ID identifies each object. Apply image/mask augmentation first. These functions keep the input mask unchanged.
Function |
Output |
Meaning |
|---|---|---|
|
Float64 |
Vertical then horizontal CellPose flows |
|
Float64 |
Vertical then horizontal Omnipose flows |
|
Float64 |
Vertical then horizontal normalized positions |
|
Float32 |
Radial boundary distances in pixels |
|
Float64 |
Per-object distance, optionally normalized |
|
Float64 |
Smooth distance targets |
|
Float64 |
Boundary band |
|
Float64 |
Gap/border loss weights, zero inside objects |
H is height and W width. Empty masks return zeros. Contours can extend outside
objects; gen_hv_maps removes objects below min_size. For StarDist, pass the
model’s ray count as n_rays.
import numpy as np
from cellseg_models_pytorch.transforms import gen_hv_maps, gen_stardist_maps
instances = np.zeros((16, 16), dtype=np.int32)
instances[4:12, 4:12] = 1
position_target = gen_hv_maps(instances)
ray_target = gen_stardist_maps(instances, n_rays=8)
The target shapes are (2, 16, 16) and (8, 16, 16). Convert them to tensors
with the dtype needed by your loss. Use the classes below to integrate target
generation with training datasets.
- gen_flow_maps(inst_map, pad=1)#
Generate vertical and horizontal CellPose flow targets.
- Parameters:
inst_map (ndarray) – Integer NumPy mask (H, W). Zero is background and positive IDs identify individual objects. H is height and W width.
pad (int) – Constant padding around each object while generating its flows.
- Returns:
Float64 array (2, H, W), vertical then horizontal flow. Background and empty masks are zero.
- Return type:
ndarray
Notes
Stringer, C., Wang, T., Michaelos, M. et al. Cellpose: a generalist algorithm for cellular segmentation. Nat Methods 18, 100-106 (2021). https://doi.org/10.1038/s41592-020-01018-x
- gen_omni_flow_maps(inst_map, pad=1)#
Generate Omnipose flow targets from smooth object distances.
- Parameters:
inst_map (ndarray) – Integer NumPy mask (H, W). Zero is background and positive IDs identify individual objects. H is height and W width.
pad (int) – Constant padding around each object during flow generation.
- Returns:
Float64 array (2, H, W), vertical then horizontal flow. Background and empty masks are zero.
- Return type:
ndarray
Notes
Omnipose: a high-precisionmorphology-independent solution for bacterial cell segmentation Kevin J. Cutler, Carsen Stringer, Paul A. Wiggins, Joseph D. Mougous bioRxiv 2021.11.03.467199; doi: https://doi.org/10.1101/2021.11.03.467199
- gen_hv_maps(inst_map, min_size=5)#
Generate vertical and horizontal position targets inside objects.
- Parameters:
inst_map (ndarray) – Integer NumPy mask (H, W). Zero is background and positive IDs identify individual objects. H is height and W width.
min_size (int) – Remove objects smaller than this pixel count from target generation.
- Returns:
Float64 array (2, H, W), vertical then horizontal positions normalized to [-1, 1] within each object. Background and empty masks are zero.
- Return type:
ndarray
Notes
Based on HoVer-Net (Graham et al., 2019).
- gen_stardist_maps(inst_map, n_rays)#
Measure radial distances from object pixels to their boundaries.
Adapted from stardist/stardist
- Parameters:
inst_map (ndarray) – Integer NumPy mask (H, W). Zero is background and positive IDs identify individual objects. H is height and W width.
n_rays (int) – Required positive number of ray directions. Match the network and training targets; this function has no default ray count.
- Returns:
Float32 radial distances (n_rays, H, W), in pixels, with zero background. Empty masks return zeros. Ray 0 points along increasing columns; later rays rotate toward increasing rows (clockwise in image coordinates).
- Return type:
ndarray
- gen_dist_maps(inst_map, normalize=True, euclidean=True)#
Generate a distance-to-boundary map for each object.
- Parameters:
inst_map (ndarray) – Integer NumPy mask (H, W). Zero is background and positive IDs identify individual objects. H is height and W width.
normalize (bool) – Rescale distances separately within each object to 0–1.
euclidean (bool) – True uses straight-line distance; False uses chessboard distance.
- Returns:
Float64 distance map (H, W). Background and empty masks are zero. Tiny regions with a spatial dimension below two pixels are skipped.
- Return type:
ndarray
- gen_contour_maps(inst_map, thickness=1)#
Mark the contours of labelled objects.
- Parameters:
inst_map (ndarray) – Integer NumPy mask (H, W). Zero is background and positive IDs identify individual objects. H is height and W width.
thickness (int) – Disk radius in pixels for erosion/dilation. The resulting boundary band extends inside and outside each object.
- Returns:
Float64 contour mask (H, W), with boundary pixels marked by 1 and other pixels 0. An empty mask returns zeros.
- Return type:
ndarray
- gen_weight_maps(inst_map, sigma=5.0, w0=10.0)#
Generate larger loss weights in gaps between nearby objects.
- Parameters:
inst_map (ndarray) – Integer NumPy mask (H, W). Zero is background and positive IDs identify individual objects. H is height and W width.
sigma (float) – Positive distance scale in pixels; larger values spread weighting farther.
w0 (float) – Multiplier for the boundary penalty.
- Returns:
Float64 weight map (H, W). Object interiors have weight zero. Zero or one object returns all zeros; this is not a binary contour mask.
- Return type:
ndarray
- smooth_distance(inst_map, device='cpu', pad=1)#
Generate smooth distance targets inside labelled objects.
https://www.biorxiv.org/content/10.1101/2021.11.03.467199v2
- Parameters:
inst_map (ndarray) – Integer NumPy mask (H, W). Zero is background and positive IDs identify individual objects. H is height and W width.
device (str) – Torch computation device, normally “cpu”. A CUDA device is optional; the input and returned array still use CPU NumPy memory.
pad (int) – Constant border padding; use at least one pixel for neighbor access.
- Returns:
Float64 NumPy distance map (H, W), with zero background. Empty masks return zeros. GPU computation transfers intermediate data to/from the device.
- Return type:
ndarray
Image transforms for Compose#
Install Albumentations to use these classes inside albumentations.Compose.
Pass an image with height, width, channels axes as image=image, then read the
result’s image entry.
Import the classes from cellseg_models_pytorch.transforms.albu_transforms.
import albumentations as A
from cellseg_models_pytorch.transforms.albu_transforms import (
MinMaxNormalization,
)
from cellseg_models_pytorch.utils import FileHandler
normalization = A.Compose([MinMaxNormalization(copy=True)])
image = FileHandler.read_img("data/image.png")
normalized_image = normalization(image=image)["image"]
Normalization changes image values and leaves masks unchanged. Apply colour and intensity changes to uint8 images before normalization.
- class MinMaxNormalization(amin=0.0, amax=1.0, p=1.0, copy=False, **kwargs)#
Rescale image values using one minimum and maximum across all channels.
Use in
albumentations.Composeand call withimage=image. The returned dictionary contains a float32 image of the same shape when applied; masks are passed through unchanged. Input images use height, width, channels axes.Choose the output range for global min-max normalization.
- Parameters:
amin (float) – One end of the output range, normally 0.
amax (float) – Other end, normally 1. Reversed endpoints are accepted. Constant images use the lower endpoint.
p (float) – Probability of applying this image-only transform.
copy (bool) – Copy the NumPy input before normalization. The input is not modified.
**kwargs – Additional arguments are accepted but unused.
Example
>>> import albumentations as A >>> import numpy as np >>> from cellseg_models_pytorch.transforms.albu_transforms import ( ... MinMaxNormalization, ... ) >>> transform = A.Compose([MinMaxNormalization(copy=True)]) >>> result = transform(image=np.array([[0, 255]], dtype=np.uint8)) >>> result["image"].tolist() [[0.0, 1.0]]
- class PercentileNormalization(lower=0.01, upper=99.99, p=1.0, copy=False, **kwargs)#
Rescale image values using global lower and upper percentiles.
Use in
albumentations.Composeand call withimage=image. The returned dictionary contains a float32 image of the same shape when applied; masks are passed through unchanged. Input images use height, width, channels axes.Choose the percentiles mapped to 0 and 1.
- Parameters:
lower (float) – Lower percentile across all pixels and channels, from 0 to 100.
upper (float) – Upper percentile across all pixels and channels, from 0 to 100. Values beyond the chosen interval are clipped by interpolation.
p (float) – Probability of applying the transform.
copy (bool) – Accepted by the underlying function, which currently copies input regardless of this value.
**kwargs – Additional arguments are accepted but unused.
Note
This transform uses global percentiles, not separate channel percentiles.
- class Normalization(mean, std, p=1.0, copy=False, **kwargs)#
Normalize images using supplied channel means and scale values.
Use in
albumentations.Composeand call withimage=image. The returned dictionary contains a float32 image of the same shape when applied; masks are passed through unchanged. Input images use height, width, channels axes.Choose the channel subtraction and scaling values.
- Parameters:
mean (ndarray) – Per-channel values in input pixel units to subtract, shape (C,).
std (ndarray) – Per-channel values, shape (C,). Applied as
(image - mean) / (255 * std); mean is not multiplied by 255. Match these values and input range to the checkpoint preprocessing.p (float) – Probability of applying the transform.
copy (bool) – Copy input before calling the normalization helper. Output is a new float32 array.
**kwargs – Additional arguments are accepted but unused.
Instance target classes#
These classes generate training targets from instance masks. Augment images and masks together first, then generate targets from the augmented masks.
Class |
Target name |
Output axes |
Meaning |
|---|---|---|---|
|
|
|
Vertical/horizontal flows |
|
|
|
Vertical/horizontal position |
|
|
|
Vertical/horizontal Omnipose flows |
|
|
|
Radial boundary distances |
|
|
|
Smooth interior distance |
|
|
|
Normalized interior distance |
|
|
|
Object boundaries |
|
|
|
Weights for gaps between objects |
|
|
|
Foreground/background |
H is height and W width. name supplies the target suffix; out_channels gives
the channel count. Outputs are float64, except StarDist rays (float32) and binary
masks (uint8).
deduplicate=True gives disconnected objects separate labels. CellposeTransform
currently ignores this option; supply distinct object labels yourself.
- class CellposeTransform(deduplicate=True)#
Generate two flow channels that guide pixels toward each object.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
cellpose.
- out_channels#
Number of target channels, 2. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Generate two flow channels that guide pixels toward each object.
- Parameters:
deduplicate (bool) – Retained for compatibility; this class currently does not apply duplicate-label correction.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
Floating flow map (2, H, W), with vertical then horizontal channels. H is height and W is width.
- Return type:
ndarray
- class HoverNetTransform(deduplicate=True)#
Generate horizontal and vertical position maps inside each object.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
hovernet.
- out_channels#
Number of target channels, 2. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Generate horizontal and vertical position maps inside each object.
- Parameters:
deduplicate (bool) – Give disconnected objects separate labels before target generation. Enable when the same ID may identify disconnected objects.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
Floating position maps (2, H, W), vertical then horizontal. H is height and W is width.
- Return type:
ndarray
- class OmniposeTransform(deduplicate=True)#
Generate two flow channels from smooth distances inside each object.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
omnipose.
- out_channels#
Number of target channels, 2. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Generate two flow channels from smooth distances inside each object.
- Parameters:
deduplicate (bool) – Give disconnected objects separate labels before target generation. Enable when the same ID may identify disconnected objects.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
Floating flow map (2, H, W), with vertical then horizontal channels. H is height and W is width.
- Return type:
ndarray
- class StardistTransform(n_rays=32, deduplicate=True, **kwargs)#
Generate radial distances from each object pixel to its boundary.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
stardist.
- out_channels#
Number of target channels, n_rays. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Generate radial distances from each object pixel to its boundary.
- Parameters:
n_rays (int) – Number of ray directions; match the network output channels.
deduplicate (bool) – Give disconnected objects separate labels before target generation. Enable when the same ID may identify disconnected objects.
**kwargs – Additional arguments are accepted but unused.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
Floating ray-distance map (n_rays, H, W), in pixels. H is height and W is width.
- Return type:
ndarray
- class SmoothDistTransform(deduplicate=True)#
Generate a smooth distance-to-boundary target inside each object.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
smoothdist.
- out_channels#
Number of target channels, 1. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Generate a smooth distance-to-boundary target inside each object.
- Parameters:
deduplicate (bool) – Give disconnected objects separate labels before target generation. Enable when the same ID may identify disconnected objects.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
Floating smooth-distance map (H, W). H is height and W is width.
- Return type:
ndarray
- class DistTransform(deduplicate=True)#
Generate a distance-to-boundary target inside each object.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
dist.
- out_channels#
Number of target channels, 1. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Generate a distance-to-boundary target inside each object.
- Parameters:
deduplicate (bool) – Give disconnected objects separate labels before target generation. Enable when the same ID may identify disconnected objects.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
Floating distance map (H, W), using the functional generator defaults. H is height and W is width.
- Return type:
ndarray
- class ContourTransform(deduplicate=True)#
Mark the boundaries of objects in an instance mask.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
contour.
- out_channels#
Number of target channels, 1. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Mark the boundaries of objects in an instance mask.
- Parameters:
deduplicate (bool) – Give disconnected objects separate labels before target generation. Enable when the same ID may identify disconnected objects.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
Floating contour map (H, W), with boundary pixels marked. H is height and W is width.
- Return type:
ndarray
- class EdgeWeightTransform(deduplicate=True)#
Assign larger loss weights to gaps between nearby objects.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
edgeweight.
- out_channels#
Number of target channels, 1. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Assign larger loss weights to gaps between nearby objects.
- Parameters:
deduplicate (bool) – Give disconnected objects separate labels before target generation. Enable when the same ID may identify disconnected objects.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
Float64 boundary-weight map (H, W), not a contour label mask. H is height and W is width.
- Return type:
ndarray
- class BinarizeTransform#
Convert instance labels to foreground and background.
Call on an integer instance mask: 0 is background and positive labels identify objects. Use with
ApplyEachafter joint image/mask augmentation.- name#
Target-key suffix,
binary.
- out_channels#
Number of target channels, 1. Scalar maps are HW;
ApplyEach(as_list=True)adds their final singleton channel.
Configure binary target generation.
- __call__(inst, **kwargs)#
Generate this target from one instance mask.
- Parameters:
inst (ndarray) – Integer NumPy mask (H, W). Zero is background; positive IDs identify individual objects. The input mask is not modified.
**kwargs – Extra call arguments are accepted for composition and ignored.
- Returns:
0 for background and 1 for foreground. H is height and W is width.
- Return type:
Uint8 mask (H, W)
Compose instance targets#
ApplyEach generates several targets from the same mask. With as_list=True, it
returns a list of HWC arrays for the training datasets. Otherwise, it returns a
dictionary such as {"inst-cellpose": ...} with CHW or HW arrays.
import numpy as np
from cellseg_models_pytorch.transforms.albu_transforms import (
ApplyEach,
BinarizeTransform,
)
instances = np.zeros((8, 8), dtype=np.int32)
instances[2:6, 2:6] = 1
targets = ApplyEach([BinarizeTransform()], as_list=True)(inst=instances)
targets[0] has shape (8, 8, 1). Results follow transform order, then input
keyword order. See the training guide for dataset use.
- class ApplyEach(transforms, p=1.0, as_list=False, **kwargs)#
Generate several training targets independently from the same instance mask.
This is not a sequence of spatial augmentations. Apply joint image/mask augmentation first, then derive all targets from the resulting instance mask.
- names#
Target names in the configured transform order.
- out_channels#
Channel count corresponding to each name.
Choose target generators and the output layout.
- Parameters:
transforms (List[OnlyInstMapTransform]) – Configured instance-mask transforms, such as CellposeTransform.
p (float) – Retained composition probability; this implementation always calls each configured target generator.
as_list (bool) – Return HWC arrays in a list, as expected by the training datasets. False returns a dictionary instead.
**kwargs – Additional Albumentations BaseCompose options.
- __call__(**data)#
Generate every configured target for each supplied mask.
- Parameters:
**data – Named integer HW instance masks, such as
inst=mask. Zero is background and positive labels identify objects.- Returns:
With as_list=False, a dictionary keyed as
input-name, for exampleinst-cellpose; vector targets are CHW and scalar targets HW. With as_list=True, a list of HWC arrays, adding a singleton channel for scalar targets. Ordering is by transform, then input keyword order.
Vary image appearance with StrongAugment#
Use AlbuStrongAugment in Compose to vary image appearance while keeping masks
unchanged. Apply it to uint8 RGB images before normalization.
The parameter probabilites uses that spelling.
import albumentations as A
from cellseg_models_pytorch.transforms.albu_transforms import (
AlbuStrongAugment,
MinMaxNormalization,
)
from cellseg_models_pytorch.utils import FileHandler
augmentation = A.Compose([
AlbuStrongAugment(seed=42),
MinMaxNormalization(copy=True),
])
image = FileHandler.read_img("data/image.png")
instances = FileHandler.read_mat("data/labels.mat")["inst"]
result = augmentation(image=image, masks=[instances])
seed controls operation choices and strengths. Some decisions also use NumPy’s
random state; see the training guide for repeatable
augmentation.
- class AlbuStrongAugment(augment_space=AUGMENT_SPACE, operations=(3, 4, 5), probabilites=(0.2, 0.3, 0.5), seed=None, p=1.0)#
Apply a random selection of image appearance augmentations.
Use in
albumentations.Composebefore normalization. It expects an RGB NumPy image in the uint8 range 0–255 and leaves supplied masks unchanged. Call withimage=imageand optionallymasks=[mask, ...]. Returns a dictionary containing the image and any supplied masks.The policy follows StrongAugment, described in https://arxiv.org/abs/2206.15274.
Choose augmentation operations and how many to apply per image.
- Parameters:
augment_space (Dict[str, tuple]) – Dictionary mapping operation names to magnitude bounds. The default supplies the package’s supported appearance operations.
operations (Tuple[int]) – Candidate numbers of distinct operations per image. Each count must fit the number of configured operations.
probabilites (Tuple[float]) – Sampling probabilities for those counts, in the same order. This spelling is the current public parameter name.
seed (int | None) – Seed for selecting operations and magnitudes. Operation count and application probability also use NumPy’s global random state.
p – Probability of applying the sampled operations.
- Raises:
ValueError – Operation names/bounds are invalid or the operations and probabilites lengths differ. NumPy also validates sampling arguments.
- __call__(*args, force_apply=False, **data)#
Augment one image while retaining its masks.
- Parameters:
*args – Use keyword inputs; positional values are not used.
force_apply (bool) – Apply sampled operations regardless of p.
**data –
imageas an HWC uint8 RGB array, optionallymasksas a list of aligned HW masks. Other keys are not retained.
- Returns:
Dictionary containing
imageand any suppliedmasks. Image shape and dtype are preserved; masks keep their labels and geometry.- Return type:
Dict[str, Any]