Skip to content

API

cc.special: Meta transforms:

Meta-transforms act on other transforms:

cc.SequentialTransform(list[Transform])
Apply multiple transforms in sequence

cornucopia.special.SequentialTransform

SequentialTransform(transforms, **kwargs)

Bases: _SharedMixin, SpecialTransform

A sequence of transforms

Example

Sequences can be built explicitly, or simply by adding transforms together:

t1 = MultFieldTransform()
t2 = GaussianNoiseTransform()
seq = SequentialTransform([t1, t2])     # explicit
seq = t1 + t2                           # implicit

Sequences can also be extended by addition:

seq += SmoothTransform()

Parameters:

Name Type Description Default
transforms list[Transform]

A list of transforms to apply sequentially.

required

Other Parameters:

Name Type Description
shared

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.RandomizedTransform(type[Transform], tuple[Sampler], dict[str, Sampler])
Randomize the input parameters of a transform

cornucopia.special.RandomizedTransform

RandomizedTransform(transform, sample=tuple(), ksample=dict(), *, shared=False, **kwargs)

Bases: SpecialTransform, NonFinalTransform

Transform generated by randomizing some parameters of another transform.

Gaussian noise with randomized variance

Object call

import cornucopia as cc
hypernoise = cc.RandomizedTransform(cc.GaussianNoise, [cc.Uniform()])
img = hypernoise(img)

Delayed call

import cornucopia as cc
MyRandomNoise = cc.randomize(cc.GaussianNoise)
hypernoise = MyRandomNoise(cc.Uniform())
img = hypernoise(img)

Parameters:

Name Type Description Default
transform callable(...) -> Transform

A Transform subclass or a function that constructs a Transform.

required
sample [list or dict of] callable

A collection of functions that generate parameter values provided to transform. Can be args-like or kwargs-like arguments.

tuple()
ksample dict[callable]

Must be kwargs-like arguments.

dict()

Other Parameters:

Name Type Description
shared (channels, tensors, channels + tensors, '')

Share random parameters across tensors and/or channels

cc.SwitchTransform(list[Transform], prob: float = 0, shared: bool | str = False)
Apply one out of a set of transforms

cornucopia.special.SwitchTransform

SwitchTransform(transforms, prob=0, *, shared=True, **kwargs)

Bases: _SharedMixin, SpecialTransform

Randomly choose a transform to apply

ctx.switch is an alias for SwitchTransform

Randomly apply either Gaussian or Chi noise

import cornucopia as cc
gauss = cc.GaussianNoiseTransform()
chi = cc.ChiNoiseTransform()
Explicit call to the class:
img = cc.SwitchTransform([gauss, chi])(img)
Implicit call using syntactic sugar:
img = (gauss | chi)(img)
Functional call:
img = cc.switch({gauss: 0.5, chi: 0.5})(img)

v0.4 Default for shared changed from False to True

Parameters:

Name Type Description Default
transforms list[Transform]

A list of transforms to sample from

required
prob list[float]

Probability of applying each transform

0
shared (channels, tensors, channels + tensor, '')

Roll the dice once for all input tensors

'channels'
cc.MaybeTransform(Transform, prob: float = 0.5, shared: bool | str = False)
Apply a transform with some probability

cornucopia.special.MaybeTransform

MaybeTransform(transform, prob=0.5, *, shared=True, **kwargs)

Bases: _SharedMixin, SpecialTransform

Randomly apply a transform

ctx.maybe is an alias for MaybeTransform

20% chance of adding noise

import cornucopia as cc
gauss = cc.GaussianNoiseTransform()
Explicit call to the class:
 img = cc.MaybeTransform(gauss, 0.2)(img)
Implicit call using syntactic sugar:
img = (0.2 * gauss)(img)
```

v0.4 Default for shared changed from False to True

Parameters:

Name Type Description Default
transform Transform

A transform to randomly apply

required
prob float

Probability to apply the transform

0.5
shared (channels, tensors, channels + tensor, '')

Roll the dice once for all input tensors

'channels'
cc.MappedTransform(*tuple[Transform], **dict[str, Transform], nested: bool = False)
Apply different transforms to different tensors

cornucopia.special.MappedTransform

MappedTransform(*mapargs, nested=False, default=None, **mapkwargs)

Bases: SpecialTransform

Transforms that are applied to specific positional or arguments

ctx.map is an alias for MappedTransform

Example

img = torch.randn([1, 32, 32])
seg = torch.randn([3, 32, 32]).softmax(0)

# positional variant
trf = MappedTransform(GaussianNoise(), None)
img, seg = trf(img, seg)

# keyword variant
trf = MappedTransform(image=GaussianNoise())
img, seg = trf(image=img, label=seg)

# alternative version
dat = {'img': torch.randn([1, 32, 32]),
       'seg': torch.randn([3, 32, 32]).softmax(0)}
dat = MappedTransform(img=GaussianNoise(), nested=True)(dat)

Parameters:

Name Type Description Default
mapargs tuple[Transform]

Transform to apply to positional arguments

()
mapkwargs dict[str, Transform]

Transform to apply to keyword arguments

{}
nested bool

Recursively traverse the inputs until we find matching dictionaries. Only mapkwargs are accepted if "nested".

False
default Transform

Transform to apply if nothing is specifically mapped

None
cc.IncludeKeysTransform(Transform, keys: str | list[str])
Only apply a transform to a set of keys

cornucopia.special.IncludeKeysTransform

IncludeKeysTransform(transform, keys, union=True)

Bases: SpecialTransform

Context manager for keys to include

Use as a transform

from cornucopia import IncludeKeysTransform
newxform = IncludeKeysTransform(xform, "image)
image, label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import IncludeKeysTransform
with IncludeKeysTransform(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import IncludeKeysTransform
with IncludeKeysTransform(xform, "image"):
    image, label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.include(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Include the union of what was already included and keys

True
cc.ExcludeKeysTransform(Transform, keys: str | list[str])
Do not apply a transform to a set of keys

cornucopia.special.ExcludeKeysTransform

ExcludeKeysTransform(transform, keys, union=True)

Bases: SpecialTransform

Context manager for keys to exclude. Can also be used as a transform.

Use as a transform

from cornucopia import ExcludeKeysTransform
newxform = ExcludeKeysTransform(xform, "image)
image, label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import ExcludeKeysTransform
with ExcludeKeysTransform(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import ExcludeKeysTransform
with ExcludeKeysTransform(xform, "image"):
    image, label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.exclude(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Exclude the union of what was already excluded and keys

True
cc.ConsumeKeysTransform(Transform, keys: str | list[str])
Consume (= do not return) a set of keys

cornucopia.special.ConsumeKeysTransform

ConsumeKeysTransform(transform, keys, union=True)

Bases: SpecialTransform

Context manager for keys to consume. Can also be used as a transform.

Use as a transform

from cornucopia import ConsumeKeysTransform
newxform = ConsumeKeysTransform(xform, "image)
label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import ConsumeKeysTransform
with ConsumeKeysTransform(xform, "image") as newxform:
    label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import ConsumeKeysTransform
with ConsumeKeysTransform(xform, "image"):
    label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.consume(xform, "image") as newxform:
    label = newxform(image=image, label=label)

v0.5 Added in v0.5

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Consume the union of what was already consumed and keys

True
cc.SplitChannels()
Transform multi-channel tensors into tuples of single-channel tensors

cornucopia.special.SplitChannels

SplitChannels()

Bases: Transform

Unbind tensors across first dimension (without collapsing it)

cc.CatChannels()
Concatenate tensors along the channel dimension

cornucopia.special.CatChannels

CatChannels()

Bases: Transform

Concatenate tensors across first dimension Assumes that the nested-most level in the structure is the one to concatenate.

cc.ctx: Context managers

Most meta-transforms can be used as context managers. We define aliases for these meta-transforms under cc.ctx:

cc.ctx.randomize is cc.RandomizedTransform

cornucopia.ctx.randomize

randomize(transform, sample=tuple(), ksample=dict(), *, shared=False, **kwargs)

Bases: SpecialTransform, NonFinalTransform

Transform generated by randomizing some parameters of another transform.

Gaussian noise with randomized variance

Object call

import cornucopia as cc
hypernoise = cc.RandomizedTransform(cc.GaussianNoise, [cc.Uniform()])
img = hypernoise(img)

Delayed call

import cornucopia as cc
MyRandomNoise = cc.randomize(cc.GaussianNoise)
hypernoise = MyRandomNoise(cc.Uniform())
img = hypernoise(img)

Parameters:

Name Type Description Default
transform callable(...) -> Transform

A Transform subclass or a function that constructs a Transform.

required
sample [list or dict of] callable

A collection of functions that generate parameter values provided to transform. Can be args-like or kwargs-like arguments.

tuple()
ksample dict[callable]

Must be kwargs-like arguments.

dict()

Other Parameters:

Name Type Description
shared (channels, tensors, channels + tensors, '')

Share random parameters across tensors and/or channels

cc.ctx.switch is cc.SwitchTransform

cornucopia.ctx.switch

switch(transforms, prob=0, *, shared=True, **kwargs)

Bases: _SharedMixin, SpecialTransform

Randomly choose a transform to apply

ctx.switch is an alias for SwitchTransform

Randomly apply either Gaussian or Chi noise

import cornucopia as cc
gauss = cc.GaussianNoiseTransform()
chi = cc.ChiNoiseTransform()
Explicit call to the class:
img = cc.SwitchTransform([gauss, chi])(img)
Implicit call using syntactic sugar:
img = (gauss | chi)(img)
Functional call:
img = cc.switch({gauss: 0.5, chi: 0.5})(img)

v0.4 Default for shared changed from False to True

Parameters:

Name Type Description Default
transforms list[Transform]

A list of transforms to sample from

required
prob list[float]

Probability of applying each transform

0
shared (channels, tensors, channels + tensor, '')

Roll the dice once for all input tensors

'channels'
cc.ctx.maybe is cc.MaybeTransform

cornucopia.ctx.maybe

maybe(transform, prob=0.5, *, shared=True, **kwargs)

Bases: _SharedMixin, SpecialTransform

Randomly apply a transform

ctx.maybe is an alias for MaybeTransform

20% chance of adding noise

import cornucopia as cc
gauss = cc.GaussianNoiseTransform()
Explicit call to the class:
 img = cc.MaybeTransform(gauss, 0.2)(img)
Implicit call using syntactic sugar:
img = (0.2 * gauss)(img)
```

v0.4 Default for shared changed from False to True

Parameters:

Name Type Description Default
transform Transform

A transform to randomly apply

required
prob float

Probability to apply the transform

0.5
shared (channels, tensors, channels + tensor, '')

Roll the dice once for all input tensors

'channels'
cc.ctx.map is cc.MappedTransform

cornucopia.ctx.map

map(*mapargs, nested=False, default=None, **mapkwargs)

Bases: SpecialTransform

Transforms that are applied to specific positional or arguments

ctx.map is an alias for MappedTransform

Example

img = torch.randn([1, 32, 32])
seg = torch.randn([3, 32, 32]).softmax(0)

# positional variant
trf = MappedTransform(GaussianNoise(), None)
img, seg = trf(img, seg)

# keyword variant
trf = MappedTransform(image=GaussianNoise())
img, seg = trf(image=img, label=seg)

# alternative version
dat = {'img': torch.randn([1, 32, 32]),
       'seg': torch.randn([3, 32, 32]).softmax(0)}
dat = MappedTransform(img=GaussianNoise(), nested=True)(dat)

Parameters:

Name Type Description Default
mapargs tuple[Transform]

Transform to apply to positional arguments

()
mapkwargs dict[str, Transform]

Transform to apply to keyword arguments

{}
nested bool

Recursively traverse the inputs until we find matching dictionaries. Only mapkwargs are accepted if "nested".

False
default Transform

Transform to apply if nothing is specifically mapped

None
cc.ctx.include is cc.IncludeKeysTransform

cornucopia.ctx.include

include(transform, keys, union=True)

Bases: SpecialTransform

Context manager for keys to include

Use as a transform

from cornucopia import IncludeKeysTransform
newxform = IncludeKeysTransform(xform, "image)
image, label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import IncludeKeysTransform
with IncludeKeysTransform(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import IncludeKeysTransform
with IncludeKeysTransform(xform, "image"):
    image, label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.include(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Include the union of what was already included and keys

True
cc.ctx.exclude is cc.RandomizedTransform

cornucopia.ctx.exclude

exclude(transform, keys, union=True)

Bases: SpecialTransform

Context manager for keys to exclude. Can also be used as a transform.

Use as a transform

from cornucopia import ExcludeKeysTransform
newxform = ExcludeKeysTransform(xform, "image)
image, label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import ExcludeKeysTransform
with ExcludeKeysTransform(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import ExcludeKeysTransform
with ExcludeKeysTransform(xform, "image"):
    image, label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.exclude(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Exclude the union of what was already excluded and keys

True
cc.ctx.consume is cc.ExcludeKeysTransform

cornucopia.ctx.consume

consume(transform, keys, union=True)

Bases: SpecialTransform

Context manager for keys to consume. Can also be used as a transform.

Use as a transform

from cornucopia import ConsumeKeysTransform
newxform = ConsumeKeysTransform(xform, "image)
label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import ConsumeKeysTransform
with ConsumeKeysTransform(xform, "image") as newxform:
    label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import ConsumeKeysTransform
with ConsumeKeysTransform(xform, "image"):
    label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.consume(xform, "image") as newxform:
    label = newxform(image=image, label=label)

v0.5 Added in v0.5

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Consume the union of what was already consumed and keys

True
cc.ctx.shared is cc.RandomizedTransform

cornucopia.ctx.shared

shared(transform, mode=UNSET)

Bases: _SharedMixin, SpecialTransform

Context manager for sharing transforms across channels / tensors. Can also be used as a transform.

ctx.shared is an alias for SharedTransform

Use as a context manager (alias)

from cornucopia import ctx
with ctx.shared(xform, "channels") as newxform:
    image = newxform(image)

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
mode (channels, tensors, channels + tensor, '')
  • 'channel': the same transform is applied to all channels in a tensor, but different transforms are used in different tensors.
  • 'tensors': the same transform is applied to all tensors, but with a different transform for each channel.
  • 'channels+tensors' or True: the same transform is applied to all channels of all tensors.
  • '' or False: A different transform is applied to each channel and each tensor.
'channels'
cc.ctx.returns is cc.SharedTransform

cornucopia.ctx.returns

returns(transform, returns=None)

Bases: SpecialTransform

Context manager for sharing transforms across channels / tensors

Use as a context manager (alias)

from cornucopia import ctx
with ctx.returns(xform, "channels") as newxform:
    image = newxform(image)
cc.ctx.batch is cc.BatchedTransform

cornucopia.ctx.batch

batch(transform)

Bases: Module

Apply a transform to a batch

ctx.batch is an alias for BatchedTransform

Functional call

batched_transform = cc.ctx.batch(transform)
img, lab = batched_transform(img, lab)  # input shapes: [B, C, X, Y, Z]

Object call

batched_transform = cc.BatchedTransform(transform)
img, lab = batched_transform(img, lab)  # input shapes: [B, C, X, Y, Z]

Parameters:

Name Type Description Default
transform Transform

Transform to apply to a batched tensor or to a nested structure of batched tensors

required

cc.io: Data loaders and converters

cc.ToTensorTransform(ndim: int | None, dtype: dtype | None, device: device | None)
Ensure that an array is a tensor (with required properties)

cornucopia.io.ToTensorTransform

ToTensorTransform(ndim=None, dtype=None, device=None, **kwargs)

Bases: FinalTransform

Convert to Tensor (or to other dtype/device)

Parameters:

Name Type Description Default
ndim int

Number of spatial dimensions (default: guess from data)

None
dtype dtype

Returned data type (default: keep same)

None
device device

Returned device (default: keep same)

None

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.LoadTransform(ndim: int | None, dtype: dtype | None, *, device: device | None)
Load a tensor from disk

cornucopia.io.LoadTransform

LoadTransform(ndim=None, dtype=None, *, device=None, returns=None, append=False, prefix=False, include=None, exclude=None, consume=None, **kwargs)

Bases: FinalTransform

Load data from disk.

Available loaders are:

  • BabelLoader: for medical image formats (nifti, mgz, minc, etc.)
  • TiffLoader: for TIFF files (including multi-page)
  • PillowLoader: for common image formats (png, jpg, etc., with optional rot90)
  • NumpyLoader: for .npy and .npz files (with optional field name)

Custom loaders can be added by registering them in cornucopia.utils.io.loaders.

Parameters:

Name Type Description Default
ndim int | None

Number of spatial dimensions (default: guess from file)

None
dtype dtype | str | None

Data type (default: guess from file)

None
device device | str | None

Device on which to load data (default: cpu)

None

Other Parameters:

Name Type Description
to_ras bool

Reorient data so that it has a RAS layout. Only used by BabelLoader.

rot90 bool

Rotate by 90 degrees in-plane. Only used by PillowLoader.

field str

Field to load from a npz file. Only used by NumpyLoader.

returns Optional[ReturnsT]

See Transform for details.

append Optional[ReturnsT]

See Transform for details.

prefix Optional[ReturnsT]

See Transform for details.

include Optional[ReturnsT]

See Transform for details.

exclude Optional[ReturnsT]

See Transform for details.

consume Optional[ReturnsT]

See Transform for details.

cc.fov: Modify the field-of-view

Deterministic transforms

cc.FlipTransform(axis: int | list[int] | None = None)
Flip one or more axes

cornucopia.fov.FlipTransform

FlipTransform(axis=None, **kwargs)

Bases: FinalTransform

Flip one or more axes.

Parameters:

Name Type Description Default
axis [list of] int

Axes to flip. By default, flip all spatial axes.

None

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.PermuteAxesTransform(permutation: int | list[int] | None = None)
Permute axes

cornucopia.fov.PermuteAxesTransform

PermuteAxesTransform(permutation=None, **kwargs)

Bases: FinalTransform

Permute axes

Parameters:

Name Type Description Default
permutation [list of] int

Axes permutation. By default, reverse axes. Only applies to spatial axes, so axes are numbered [C, 0, 1, 2]

None

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.Rot90Transform(axis: int | list[int] = 0, negative: bool | list[bool] = False)
Apply a 90 rotation along one or several axes

cornucopia.fov.Rot90Transform

Rot90Transform(axis=0, negative=False, double=False, **kwargs)

Bases: FinalTransform

Apply a 90 (or 180) rotation along one or several axes.

Parameters:

Name Type Description Default
axis [list of] int

Rotation axis (indexing does not account for the channel axis)

0
negative [list of] bool

Rotate by -90 deg instead of 90 deg

False
double [list of] bool

Rotate be 180 instead of 90 (negative is then unused)

False

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.Rot180Transform(axis: int | list[int] = 0)
Apply a 180 rotation along one or several axes

cornucopia.fov.Rot180Transform

Rot180Transform(axis=0, **kwargs)

Bases: Rot90Transform

Apply a 180 deg rotation along one or several axes

Parameters:

Name Type Description Default
axis [list of] int

Rotation axis (indexing does not account for the channel axis)

0

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.CropPadTransform(crop: list[slice] = (), pad: list[int] = (), ...)
Crop and/or pad a tensor

cornucopia.fov.CropPadTransform

CropPadTransform(crop=(), pad=(), bound='zero', value=0, **kwargs)

Bases: FinalTransform

Crop and/or pad a tensor.

Parameters:

Name Type Description Default
crop list[slice]

Slicing operator per dimension.

()
pad list[int]

Left and right padding per dimensions

()
bound [list of] str

Boundary condition for padding

'zero'
value number

Padding value in case bound='constant

0

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.CropTransform(cropping: number | list[number], unit: {'fov','vox'} = 'vox', side: {'pre','post','both'} = 'both')
Crop a tensor

cornucopia.fov.CropTransform

CropTransform(cropping, unit='vox', side='both', **kwargs)

Bases: NonFinalTransform

Crop a tensor by some amount

Parameters:

Name Type Description Default
cropping [list of] int or float

Amount of cropping. If side is None, pre and post cropping must be provided in turn.

required
unit (vox, pct)

Padding unit

'vox'
side (pre, post, both, None)

Side to crop

'pre'

Other Parameters:

Name Type Description
shared

See NonFinalTransform for details.

v0.5 Default for shared changed from "channels" to True

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.PadTransform(padding: number | list[number], unit: {'fov','vox'} = 'vox', side: {'pre','post','both'} = 'both', ...)
Pad a tensor

cornucopia.fov.PadTransform

PadTransform(padding, unit='vox', side='both', bound='zero', value=0, **kwargs)

Bases: NonFinalTransform

Pad a tensor by some amount

Parameters:

Name Type Description Default
padding [list of] int or float

Amount of padding. If side is None, pre and post padding must be provided in turn.

required
unit (vox, pct)

Padding unit

'vox'
side (pre, post, both, None)

Side to pad

'pre'
bound str

Boundary condition

'zero'
value float

Value for case bound='constant'

0

Other Parameters:

Name Type Description
shared

See NonFinalTransform for details.

v0.5 Default for shared changed from "channels" to True

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = CropPadTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = CropPadTransform

The transform type returned by unroll, next and final.

cc.PatchTransform(shape: int | list[int] = 64, center: float | list[float] = 0, ...)
Extract a patch from the tensor

cornucopia.fov.PatchTransform

PatchTransform(shape=64, center=0, bound='zero', *, shared=True, **kwargs)

Bases: NonFinalTransform

Extract a patch from the volume

Parameters:

Name Type Description Default
shape [list of] int

Patch shape

64
center [list of] float

Patch center, in relative coordinates -1..1

0
bound [list of]str

Boundary condition in case padding is needed

'zero'

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

v0.5 Default for shared changed from "channels" to True

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = CropPadTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = CropPadTransform

The transform type returned by unroll, next and final.

cc.PowerTwoTransform(exponent: int | list[int] = 1, ...)
Pad the volume such that the tensor shape can be divided by 2**x

cornucopia.fov.PowerTwoTransform

PowerTwoTransform(exponent=1, bound='zero', **kwargs)

Bases: NonFinalTransform

Pad the volume such that the tensor shape can be divided by 2**x

Parameters:

Name Type Description Default
exponent [list of] int

Ensure that the shape can be divided by 2 ** exponent

1
bound [list of] str

Boundary condition for padding

'zero'

Other Parameters:

Name Type Description
shared

See NonFinalTransform for details.

v0.5 Default for shared changed from "channels" to True

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = PatchTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = CropPadTransform

The transform type returned by final.

Random transforms

cc.RandomFlipTransform(axes: Sampler | int | list[int] | None = None, *, shared: bool | str = True)
Randomly flip one or more axes

cornucopia.fov.RandomFlipTransform

RandomFlipTransform(axes=None, *, shared=True, **kwargs)

Bases: NonFinalTransform

Randomly flip one or more axes.

Parameters:

Name Type Description Default
axes Sampler | [list of] int

Axes that can be flipped (default: all spatial axes)

None

Other Parameters:

Name Type Description
shared bool

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = FlipTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = FlipTransform

The transform type returned by unroll, next and final.

cc.RandomPermuteAxesTransform(permutation: list[int] | None = None, *, shared: bool | str = True)
Randomly permute axes

cornucopia.fov.RandomPermuteAxesTransform

RandomPermuteAxesTransform(axes=None, *, shared=True, **kwargs)

Bases: NonFinalTransform

Randomly permute axes.

Parameters:

Name Type Description Default
axes [list of] int

Axes that can be permuted (default: all)

None

Other Parameters:

Name Type Description
shared bool

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = PermuteAxesTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = PermuteAxesTransform

The transform type returned by unroll, next and final.

cc.RandomRot90Transform(axes: int | list[int] | None = None, max_rot: Sampler | int = 2, negative: bool | list[bool] = False, *, shared: bool | str = True)
Random set of 90 transforms

cornucopia.fov.RandomRot90Transform

RandomRot90Transform(axes=None, max_rot=2, negative=True, *, shared=True, **kwargs)

Bases: NonFinalTransform

Random set of 90 transforms.

Parameters:

Name Type Description Default
axes [list of] int

Axes along which rotations can happen. If None, all axes.

None
max_rot Sampler | int

Maximum number of consecutive rotations.

2
negative bool

Whether to authorize negative rotations.

True

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = Rot90Transform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = Rot90Transform

The transform type returned by unroll, next and final.

cc.RandomPatchTransform(shape: int | list[int], *, shared: bool | str = True)
Extract a random patch from the tensor

cornucopia.fov.RandomPatchTransform

RandomPatchTransform(shape, bound='zero', *, shared=True, **kwargs)

Bases: NonFinalTransform

Extract a (randomly located) patch from the volume.

This transform ensures that the patch is fully contained within the original field of view (unless the patch size is larger than the input shape).

Parameters:

Name Type Description Default
shape [list of] int

Patch shape

required
bound [list of] str

Boundary condition in case padding is needed

'zero'

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

v0.5 Default for shared changed from "channels" to True

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = PatchTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = CropPadTransform

The transform type returned by final.

cc.noise: Inject noise

Deterministic parameters

cc.GaussianNoiseTransform(sigma: float | list[float] = 0.1, *, shared: bool | str = False)
Inject Gaussian noise

cornucopia.noise.GaussianNoiseTransform

GaussianNoiseTransform(sigma=0.1, *, shared=False, **kwargs)

Bases: NonFinalTransform

Additive Gaussian noise

Parameters:

Name Type Description Default
sigma float | list[float] | Tensor

Standard deviation [per channel].

0.1

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'noise'}

Which tensors to return

shared (channels, tensors, channels + tensors, '')

Add the exact same nosie to all channels/images

Final class-attribute instance-attribute

Final = GaussianNoiseFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = GaussianNoiseFinalTransform

The transform type returned by unroll, next and final.

cc.ChiNoiseTransform(sigma: float | list[float] = 0.1, nb_channels: int = 2, *, shared: bool | str = False)
Inject non-central Chi noise

cornucopia.noise.ChiNoiseTransform

ChiNoiseTransform(sigma=0.1, nb_channels=2, *, shared=False, **kwargs)

Bases: NonFinalTransform

Additive Noncentral Chi noise

(Rician is a special case with nb_channels = 2)

Parameters:

Name Type Description Default
sigma float | list[float] | Tensor

Standard deviation [per channel].

0.1
nb_channels int

Number of independent noise channels

2

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'noise'}

Which tensors to return

shared (channels, tensors, channels + tensors, '')

Add the exact same values to all channels/images

Final class-attribute instance-attribute

Final = ChiNoiseFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ChiNoiseFinalTransform

The transform type returned by unroll, next and final.

cc.GammaNoiseTransform(sigma: float | list[float] = 0.1, mean: float | list[float] = 1, *, shared: bool | str = False)
Inject Gamma noise

cornucopia.noise.GammaNoiseTransform

GammaNoiseTransform(sigma=0.1, mean=1, *, shared=False, **kwargs)

Bases: NonFinalTransform

Multiplicative Gamma noise

Parameters:

Name Type Description Default
sigma float | list[float] | Tensor

Standard deviation [per channel].

0.1
mean float | list[float] | Tensor

Expected value [per channel].

1

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'noise'}

Which tensors to return

shared (channels, tensors, channels + tensors, '')

Use the exact same noise for all channels/tensors

Final class-attribute instance-attribute

Final = GammaNoiseFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = GammaNoiseFinalTransform

The transform type returned by unroll, next and final.

cc.GFactorTransform(noise: Transform, shape: int = 5, vmin: float = 0.5, vmax: float = 1.5, order: int = 3, *, shared: bool | str = False)
Inject noise with spatially varying variance

cornucopia.noise.GFactorTransform

GFactorTransform(noise, shape=5, vmin=0.5, vmax=1.5, order=3, *, shared=False, **kwargs)

Bases: NonFinalTransform

Noise with spatially varying variance

Parameters:

Name Type Description Default
noise Transform

A transform that applies additive noise

required
shape float

Number of control points

5
vmin float

Minimum g-factor

0.5
vmax float

Maximum g-factor

1.5
order int

Spline order

3

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'gfactor', 'noise', 'scalednoise'}

Which tensors to return

shared (channels, tensors, channels + tensors, '')

Use the same field for all channels/tensors

Final class-attribute instance-attribute

Final = GFactorFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = GFactorFinalTransform

The transform type returned by unroll, next and final.

Random parameters

cc.RandomGaussianNoiseTransform(sigma: Sampler | float = 0.1, *, shared: bool | str = False)
Inject Gaussian noise with random parameters

cornucopia.noise.RandomGaussianNoiseTransform

RandomGaussianNoiseTransform(sigma=0.1, *, shared=False, shared_noise=None, **kwargs)

Bases: RandomizedTransform

Additive Gaussian noise with random standard deviation

Parameters:

Name Type Description Default
sigma Sampler | float

Distribution from which to sample the standard deviation. If a float, sample from Uniform(0, value). To use a fixed value, pass Fixed(value).

0.1

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'noise'}

Which tensors to return

shared (channels, tensors, channels + tensors, '')

Use the same sd for all channels/tensors

shared_noise (channels, tensors, channels + tensors, '')

Use the exact same noise for all channels/tensors

Next class-attribute instance-attribute

Next = GaussianNoiseTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = GaussianNoiseFinalTransform

The transform type returned by final.

cc.RandomChiNoiseTransform(sigma: Sampler | float = 0.1, nb_channels: Sampler | int = 8, *, shared: bool | str = False)
Inject non-central Chi noise with random parameters

cornucopia.noise.RandomChiNoiseTransform

RandomChiNoiseTransform(sigma=0.1, nb_channels=8, *, shared=False, shared_noise=None, **kwargs)

Bases: RandomizedTransform

Additive Chi noise with random standard deviation and channels

Parameters:

Name Type Description Default
sigma Sampler | float

Distribution from which to sample the standard deviation. If a float, sample from Uniform(0, value). To use a fixed value, pass Fixed(value).

0.1
nb_channels Sampler | int

Distribution from which to sample the standard deviation. If a int, sample from RandInt(1, value). To use a fixed value, pass Fixed(value).

8

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'noise'}

Which tensors to return

shared (channels, tensors, channels + tensors, '')

Use the same sd for all channels/tensors

shared_noise (channels, tensors, channels + tensors, '', None)

Use the exact same noise for all channels/tensors

Next class-attribute instance-attribute

Next = ChiNoiseTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = ChiNoiseFinalTransform

The transform type returned by final.

cc.RandomGammaNoiseTransform(sigma: Sampler | float = 0.1, mean: Sampler | float = Fixed(1), *, shared: bool | str = False)
Inject Gamma noise with random parameters

cornucopia.noise.RandomGammaNoiseTransform

RandomGammaNoiseTransform(sigma=0.1, mean=Fixed(1.0), *, shared=False, shared_noise=None, **kwargs)

Bases: RandomizedTransform

Multiplicative Gamma noise with random standard deviation and mean

Parameters:

Name Type Description Default
sigma Sampler or float

Distribution from which to sample the standard deviation. If a float, sample from Uniform(0, value). To use a fixed value, pass Fixed(value).

0.1
mean Sampler or float

Distribution from which to sample the mean. If a float, sample from Uniform(0, value). To use a fixed value, pass Fixed(value).

Fixed(1.0)

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'noise'}

Which tensors to return

shared (channels, tensors, channels + tensors, '')

Use the same sd for all channels/tensors

shared_noise (channels, tensors, channels + tensors, '', None)

Use the exact same noise for all channels/tensors

Next class-attribute instance-attribute

Next = GammaNoiseTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = GammaNoiseFinalTransform

The transform type returned by final.

cc.intensity: Modify image intensities

Deterministic transforms

cc.AddValueTransform(value: float | list[float] | tensor)
Add a constant value

cornucopia.intensity.AddValueTransform

AddValueTransform(value, op=None, value_name='value', **kwargs)

Bases: OpConstTransform

Add a constant value

cc.MulValueTransform(value: float | list[float] | tensor)
Multiply by a constant value

cornucopia.intensity.MulValueTransform

MulValueTransform(value, op=None, value_name='value', **kwargs)

Bases: OpConstTransform

Multiply with a constant value

cc.FillValueTransform(mask: tensor, value: float | list[float] | tensor)
Fill with a constant value

cornucopia.intensity.FillValueTransform

FillValueTransform(mask, value, mask_name='mask', value_name='value', **kwargs)

Bases: FinalTransform

Fills the tensor with a value inside a mask

Parameters:

Name Type Description Default
mask tensor

Mask of voxels in which to set the value

required
value number or tensor

right-hand side of the operation

required
mask_name str

Name used when returning the mask

'mask'
value_name str

Name used when returning the rhs value

'value'

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.ReturnValueTransform(value: float | list[float] | tensor)
Return a constant value

cornucopia.intensity.ReturnValueTransform

ReturnValueTransform(value, value_name='output', dtype=None, **kwargs)

Bases: FinalTransform

Fills the tensor with a value inside a mask

Parameters:

Name Type Description Default
value number or tensor

right-hand side of the operation

required
value_name str

Name used when returning the rhs value

'output'

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.AddMulTransform(slope: float | list[float] | tensor = 1, offset: float | list[float] | tensor = 0)
Element wise affine transform

cornucopia.intensity.AddMulTransform

AddMulTransform(slope=1, offset=0, **kwargs)

Bases: FinalTransform

Constant intensity affine transform: y = x * slope + offset

Parameters:

Name Type Description Default
slope number or tensor

Affine slope

1
offset number or tensor

Affine offset

0

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.ClipTransform(vmin: float | list[float] | tensor | None = None, vmax: float | list[float] | tensor | None = None)
Clip extremum values

cornucopia.intensity.ClipTransform

ClipTransform(vmin=None, vmax=None, **kwargs)

Bases: FinalTransform

Clip extremum values

Parameters:

Name Type Description Default
vmin number or tensor

Min value

None
vmax number or tensor

Max value

None

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.SplineUpsampleTransform(order: int = 3, prefilter: bool = False)
Upsample a field using spline interpolation

cornucopia.intensity.SplineUpsampleTransform

SplineUpsampleTransform(order=3, prefilter=False, **kwargs)

Bases: FinalTransform

Upsample a field using spline interpolation

Parameters:

Name Type Description Default
order int

Spline interpolation order

3
prefilter bool

Spline prefiltering (True for interpolation, False for spline evaluation)

False

Other Parameters:

Name Type Description
returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.GammaTransform(gamma: float = 1, vmin: float = 0, vmax: float = 1)
Gamma correction

cornucopia.intensity.GammaTransform

GammaTransform(gamma=1, vmin=None, vmax=None, *, shared=False, **kwargs)

Bases: NonFinalTransform

Gamma correction

References
  1. https://en.wikipedia.org/wiki/Gamma_correction

Parameters:

Name Type Description Default
gamma float

Exponent of the Gamma transform

1
vmin float | None

Value to use as the minimum (default: x.min())

None
vmax float | None

Value to use as the maximum (default: x.max())

None

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns [list or dict of] {'input', 'output', 'vmin', 'vmax', 'gamma'}

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = GammaFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = GammaFinalTransform

The transform type returned by unroll, next and final.

cc.ZTransform(mu: float = 0, sigma: float = 1, *, shared: bool | str = False)
Gamma correction

cornucopia.intensity.ZTransform

ZTransform(mu=0, sigma=1, *, shared=False, **kwargs)

Bases: NonFinalTransform

Z-transform the data -> zero mean, unit standard deviation

Parameters:

Name Type Description Default
mu float

Target mean. If None, keep the input mean.

0
sigma float

Target standard deviation. If None, keep the input sd.

1

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = AddMulTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = AddMulTransform

The transform type returned by unroll, next and final.

cc.QuantileTransform(pmin: float = 0.01, pmax: float = 0.99, vmin: float = 0, vmax: float = 1, clip: bool = False, *, shared: bool | str = False)
Match lower and upper quantiles to (0, 1)

cornucopia.intensity.QuantileTransform

QuantileTransform(pmin=0.01, pmax=0.99, vmin=0, vmax=1, clip=False, max_samples=10000, **kwargs)

Bases: NonFinalTransform

Match lower and upper quantiles to (0, 1)

Parameters:

Name Type Description Default
pmin (0..1)

Lower quantile

0.01
pmax (0..1)

Upper quantile

0.99
vmin float

Lower target value

0
vmax float

Upper target value

1
clip bool

Clip values outside (vmin, vmax)

False
max_samples int

Maximum number of pixels to use for quantile estimation (for speed)

10000

Other Parameters:

Name Type Description
shared

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = AddMulTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = AddMulTransform

The transform type returned by unroll, next and final.

cc.MinMaxTransform(vmin: float = 0, vmax: float = 1, clip: bool = False, *, shared: bool | str = False)
Match min and max values to (0, 1)

cornucopia.intensity.MinMaxTransform

MinMaxTransform(vmin=0, vmax=1, clip=False, **kwargs)

Bases: NonFinalTransform

Match min and max values to (0, 1)

Parameters:

Name Type Description Default
vmin float

Lower target value

0
vmax float

Upper target value

1
clip bool

Clip values outside (vmin, vmax)

False

Other Parameters:

Name Type Description
shared

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = AddMulTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = AddMulTransform

The transform type returned by unroll, next and final.

Transforms with fixed parameters (but random coefficients)

cc.AddFieldTransform(shape: int | list[int] = 5, vmin: float = 0, vmax: float = 1, order: int = 3, ...)
Smooth additive field

cornucopia.intensity.AddFieldTransform

AddFieldTransform(shape=5, vmin=0, vmax=1, order=3, slice=None, thickness=None, *, shared=False, **kwargs)

Bases: BaseFieldTransform

Smooth additive (bias) field

Final class-attribute instance-attribute

Final = AddValueTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = AddValueTransform

The transform type returned by unroll, next and final.

cc.MulFieldTransform(shape: int | list[int] = 5, vmin: float = 0, vmax: float = 1, order: int = 3, ...)
Smooth multiplicative field

cornucopia.intensity.MulFieldTransform

MulFieldTransform(shape=5, vmin=0, vmax=1, order=3, slice=None, thickness=None, *, shared=False, **kwargs)

Bases: BaseFieldTransform

Smooth multiplicative (bias) field

Final class-attribute instance-attribute

Final = MulValueTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = MulValueTransform

The transform type returned by unroll, next and final.

Transforms with random parameters

cc.RandomAddTransform(value: Sampler | float | tuple[float, float] = 1, *, shared: bool = False)
Add a random value

cornucopia.intensity.RandomAddTransform

RandomAddTransform(value=1, *, shared=False, **kwargs)

Bases: RandomizedTransform

Random additive transform.

Parameters:

Name Type Description Default
value Sampler | [pair of] float

Bound for additive value

1

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = AddValueTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = AddValueTransform

The transform type returned by unroll, next and final.

cc.RandomMulTransform(value: Sampler | float | tuple[float, float] = (0.5, 2), *, bool | str: bool = False)
Multiply by a random value

cornucopia.intensity.RandomMulTransform

RandomMulTransform(value=(0.5, 2), *, shared=False, **kwargs)

Bases: RandomizedTransform

Random multiplicative transform.

Parameters:

Name Type Description Default
value Sampler | [pair of] float

Bound for multiplicative value

(0.5, 2)

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = MulValueTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = MulValueTransform

The transform type returned by unroll, next and final.

cc.RandomAddMulTransform(slope: Sampler | float | tuple[float, float] = 1, offset: Sampler | float | tuple[float, float] = 0.5, *, shared: bool | str = False)
Random element-wise affine transform

cornucopia.intensity.RandomAddMulTransform

RandomAddMulTransform(slope=1, offset=0.5, *, shared=False, **kwargs)

Bases: RandomizedTransform

Random intensity affine transform.

Parameters:

Name Type Description Default
slope Sampler | [pair of] float

Bound for slope

1
offset Sampler | [pair of] float

Bound for offset

0.5

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = AddMulTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = AddMulTransform

The transform type returned by unroll, next and final.

cc.RandomAddFieldTransform(shape: Sampler | int = 8, vmin: Sampler | float = -1, vmax: Sampler | float = 1, order: int = 3, *, shared: bool | str = False)
Random smooth multiplicative field

cornucopia.intensity.RandomAddFieldTransform

RandomAddFieldTransform(shape=8, vmin=-1, vmax=1, order=3, *, shared=False, shared_field=None, **kwargs)

Bases: NonFinalTransform

Random additive bias field transform

Parameters:

Name Type Description Default
shape Sampler | int

Sampler or Upper bound for number of control points

8
vmin Sampler | float

Sampler or Lower bound for minimum value

-1
vmax Sampler | float

Sampler or Upper bound for maximum value

1
order Sampler | int

Spline order

3

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

shared_field Union[str, bool, None]

Whether to share random field across tensors and/or channels. By default: same as shared

returns [list or dict of] {'input', 'output', 'field'}

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.RandomMulFieldTransform(shape: Sampler | int = 8, vmax: Sampler | float = 1, order: int = 3, symmetric: bool | float = False, *, shared: bool | str = False)
Random smooth multiplicative field

cornucopia.intensity.RandomMulFieldTransform

RandomMulFieldTransform(shape=8, vmax=1, order=3, symmetric=False, *, shared=False, shared_field=None, **kwargs)

Bases: NonFinalTransform

Random multiplicative bias field transform

Parameters:

Name Type Description Default
shape Sampler | int

Sampler or Upper bound for number of control points

8
vmax Sampler | float

Sampler or Upper bound for maximum value

1
order int

Spline order

3
symmetric bool | float

If a float, the bias field will take values in (symmetric-vmax, symmetric+vmax). If False, it will take values in (0, vmax). If True, it will take values in (1-vmax, 1+vmax).

False

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

shared_field Union[str, bool, None]

Whether to share random field across tensors and/or channels. By default: same as shared

returns [list or dict of] {'input', 'output', 'field'}

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = MulFieldTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = MulValueTransform

The transform type returned by final.

cc.RandomSlicewiseMulFieldTransform(shape: Sampler | int = 8, vmax: Sampler | float = 1, order: int = 3, slice: int | None = None, thickness: Sampler | int = 32,shape_through: Sampler | int | None = None, *, shared: bool | str = False)
Random smooth slicewise multiplicative field

cornucopia.intensity.RandomSlicewiseMulFieldTransform

RandomSlicewiseMulFieldTransform(shape=8, vmax=1, order=3, slice=None, thickness=32, shape_through=None, *, shared=False, shared_field=None, **kwargs)

Bases: NonFinalTransform

Random multiplicative bias field transform, per slice or slab

Parameters:

Name Type Description Default
shape Sampler | int

Sampler or Upper bound for number of control points

8
vmax Sampler | float

Sampler or Upper bound for maximum value

1
order int

Spline order

3
slice int | None

Slice axis. If None, sample one randomly

None
thickness Sampler | int

Sampler or Upper bound for slice thickness

32
shape_through Sampler | int | None

Sampler or Upper bound for number of control points along the slice direction. If None, same as shape.

None

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

shared_field Union[str, bool, None]

Whether to share random field across tensors and/or channels. By default: same as shared

returns [list or dict of] {'input', 'output', 'field'}

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = MulFieldTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = MulValueTransform

The transform type returned by final.

cc.RandomGammaTransform(gamma: Sampler | float | tuple[float, float] = (0.5, 2), *, shared: bool | str = False)
Gamma correction

cornucopia.intensity.RandomGammaTransform

RandomGammaTransform(gamma=(0.5, 2), *, shared=False, shared_minmax=None, **kwargs)

Bases: NonFinalTransform

Random Gamma transform.

Parameters:

Name Type Description Default
gamma Sampler or [pair of] float

Sampler or range for the exponent value

(0.5, 2)

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

shared_minmax Optional[SharedT]

Use the same vmin/vmax for all channels. Default: same as shared.

returns [list or dict of] {'input', 'output', 'vmin', 'vmax', 'gamma'}

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = GammaTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = GammaFinalTransform

The transform type returned by final.

cc.contrast: Modify image contrast

cc.ContrastMixtureTransform(nk: int = 16, keep_background: bool = True, *, shared: bool = False)
Change the means and covariances of intensity modes

cornucopia.contrast.ContrastMixtureTransform

ContrastMixtureTransform(nk=16, keep_background=True, *, shared=False, **kwargs)

Bases: NonFinalTransform

Find intensity modes using a GMM and change their means and covariances.

Reference

Meyer, M.I., de la Rosa, E., Pedrosa de Barros, N., Paolella, R., Van Leemput, K. and Sima, D.M., 2021. A contrast augmentation approach to improve multi-scanner generalization in MRI. Frontiers in Neuroscience, 15, p.708196.

@article{meyer2021,
    title     = {A contrast augmentation approach to improve multi-scanner generalization in MRI},
    author    = {Meyer, Maria Ines and de la Rosa, Ezequiel and Pedrosa de Barros, Nuno and Paolella, Roberto and Van Leemput, Koen and Sima, Diana M},
    journal   = {Frontiers in Neuroscience},
    volume    = {15},
    pages     = {708196},
    year      = {2021},
    publisher = {Frontiers Media SA},
    url       = {https://www.frontiersin.org/articles/10.3389/fnins.2021.708196}
}

Parameters:

Name Type Description Default
nk int

Number of classes

16
keep_background bool

Do not change background mean/cov. The background class is the class with minimum mean value.

True

Other Parameters:

Name Type Description
shared bool

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = ContrastMixtureFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ContrastMixtureFinalTransform

The transform type returned by unroll, next and final.

cc.ContrastLookupTransform(nk: int = 16, keep_background: bool = True, *, shared: bool = False)
Segment intensities into equidistant bins and change their mean value

cornucopia.contrast.ContrastMixtureTransform

ContrastMixtureTransform(nk=16, keep_background=True, *, shared=False, **kwargs)

Bases: NonFinalTransform

Find intensity modes using a GMM and change their means and covariances.

Reference

Meyer, M.I., de la Rosa, E., Pedrosa de Barros, N., Paolella, R., Van Leemput, K. and Sima, D.M., 2021. A contrast augmentation approach to improve multi-scanner generalization in MRI. Frontiers in Neuroscience, 15, p.708196.

@article{meyer2021,
    title     = {A contrast augmentation approach to improve multi-scanner generalization in MRI},
    author    = {Meyer, Maria Ines and de la Rosa, Ezequiel and Pedrosa de Barros, Nuno and Paolella, Roberto and Van Leemput, Koen and Sima, Diana M},
    journal   = {Frontiers in Neuroscience},
    volume    = {15},
    pages     = {708196},
    year      = {2021},
    publisher = {Frontiers Media SA},
    url       = {https://www.frontiersin.org/articles/10.3389/fnins.2021.708196}
}

Parameters:

Name Type Description Default
nk int

Number of classes

16
keep_background bool

Do not change background mean/cov. The background class is the class with minimum mean value.

True

Other Parameters:

Name Type Description
shared bool

See NonFinalTransform for details.

returns

See Transform for details.

append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = ContrastMixtureFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ContrastMixtureFinalTransform

The transform type returned by unroll, next and final.

cc.psf: Modify point-spread function (or resolution)

Deterministic transforms

cc.SmoothTransform(fwhm: float | list[float] = 1)
Apply Gaussian smoothing

cornucopia.psf.SmoothTransform

SmoothTransform(fwhm=1, **kwargs)

Bases: FinalTransform

Apply Gaussian smoothing

Parameters:

Name Type Description Default
fwhm float | list[float]

Full-width at half-maximum of the Gaussian kernel (per dimension)

1

Other Parameters:

Name Type Description
returns [(list | dict) of] {'input', 'output'}

Which tensors to return.

cc.LowResSliceTransform(resolution: float = 3, thickness: float = 0.8, axis: int = -1, noise: Transform | None = None)
Model a low-resolution slice direction, with Gaussian profile

cornucopia.psf.LowResSliceTransform

LowResSliceTransform(resolution=3, thickness=0.8, axis=-1, noise=None, **kwargs)

Bases: NonFinalTransform

Model a low-resolution slice direction, with Gaussian profile

Parameters:

Name Type Description Default
resolution float

Resolution of the slice dimension, in terms of high-res voxels. This is the distance between the centers of two consecutive slices.

3
thickness float in 0..1

Slice thickness, as a proportion of resolution. This is how much data is averaged into one low-resolution slice.

0.8
axis int

Slice axis

-1
noise Transform

A transform that adds noise in the low-resolution space

None

Other Parameters:

Name Type Description
returns [(list | dict) of] {'input', 'lowres', 'output'}

Which tensors to return.

Final class-attribute instance-attribute

Final = LowResSliceFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = LowResSliceFinalTransform

The transform type returned by unroll, next and final.

cc.LowResTransform(resolution: float | list[float] = 2, noise: Transform | None = None)
Model a lower-resolution image

cornucopia.psf.LowResSliceTransform

LowResSliceTransform(resolution=3, thickness=0.8, axis=-1, noise=None, **kwargs)

Bases: NonFinalTransform

Model a low-resolution slice direction, with Gaussian profile

Parameters:

Name Type Description Default
resolution float

Resolution of the slice dimension, in terms of high-res voxels. This is the distance between the centers of two consecutive slices.

3
thickness float in 0..1

Slice thickness, as a proportion of resolution. This is how much data is averaged into one low-resolution slice.

0.8
axis int

Slice axis

-1
noise Transform

A transform that adds noise in the low-resolution space

None

Other Parameters:

Name Type Description
returns [(list | dict) of] {'input', 'lowres', 'output'}

Which tensors to return.

Final class-attribute instance-attribute

Final = LowResSliceFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = LowResSliceFinalTransform

The transform type returned by unroll, next and final.

Random transforms

cc.RandomSmoothTransform(fwhm: Sampler | float = 2, *, shared: bool | str = False)
Apply Gaussian smoothing with random width

cornucopia.psf.RandomSmoothTransform

RandomSmoothTransform(fwhm=2, *, shared=False, **kwargs)

Bases: RandomizedTransform

Apply Gaussian smoothing with random FWHM

Parameters:

Name Type Description Default
fwhm Sampler | float

Sampler or upper bound for the full-width at half-maximum

2

Other Parameters:

Name Type Description
returns [(list | dict) of] {'input', 'output'}

Which tensors to return.

shared (channels, tensors, channels + tensors, '')

Use the same fwhm for all channels/tensors

Final class-attribute instance-attribute

Final = SmoothTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = SmoothTransform

The transform type returned by unroll, next and final.

cc.RandomLowResSliceTransform(resolution: Sampler | float = 3, thickness: Sampler | float = 0.1, axis: Sampler | int | None = None, noise: Transform | None = None, *, shared: bool | str = False)
Random low-resolution slice direction

cornucopia.psf.RandomLowResSliceTransform

RandomLowResSliceTransform(resolution=3, thickness=0.1, axis=None, noise=None, *, shared=False, **kwargs)

Bases: RandomizedTransform

Random low-resolution slice direction, with Gaussian profile

Parameters:

Name Type Description Default
resolution Sampler | float

Distribution from which to sample the resolution. If a float, sample from Uniform(1, value). To force a fixed value, pass Fixed(value). The resolution is the distance (in terms of high-res voxels) between the centers of two consecutive low-res slices.

3
thickness Sampler | float in 0..1

Distribution from which to sample the resolution. If a float, sample from Uniform(value, 1). To force a fixed value, pass Fixed(value). Thickness is defined as a proportion of the resolution, and determines how much data is averaged into one low-resolution slice.

0.1
axis Sampler | int | None

Slice axis. If None, select one randomly.

None
noise Transform | None

A transform that adds noise in the low-resolution space

None

Other Parameters:

Name Type Description
returns [(list | dict) of] {'input', 'lowres', 'output'}

Which tensors to return.

shared (channels, tensors, channels + tensors, '')

Use the same resolution for all channels/tensors

Next class-attribute instance-attribute

Next = LowResSliceTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = LowResSliceFinalTransform

The transform type returned by final.

cc.RandomLowResTransform(resolution: Sampler | float = 2, noise: Transform | None = None, *, shared: bool | str = False)
Random lower-resolution image

cornucopia.psf.RandomLowResTransform

RandomLowResTransform(resolution=2, noise=None, *, shared=False, **kwargs)

Bases: RandomizedTransform

Random lower-resolution image

Parameters:

Name Type Description Default
resolution Sampler | float

Distribution from which to sample the resolution. If a float, sample from Uniform(1, value). To force a fixed value, pass Fixed(value). The resolution is the distance (in terms of high-res voxels) between the centers of two consecutive low-res voxels.

2
noise Transform | None

A transform that adds noise in the low-resolution space

None

Other Parameters:

Name Type Description
returns [(list | dict) of] {'input', 'lowres', 'output'}

Which tensors to return.

shared (channels, tensors, channels + tensors, '')

Use the same resolution for all channels/tensors

Next class-attribute instance-attribute

Next = LowResTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = LowResFinalTransform

The transform type returned by final.

cc.geometric: Geometric transformations

Deterministic transforms

cc.ApplyAffineTransform(matrix: tensor | None = None, flow: tensor | None = None, ...)
Apply an affine matrix (or precomputed flow field)

cornucopia.geometric.ApplyAffineTransform

ApplyAffineTransform(matrix, flow=None, bound='border', nearest_if_label=False, dtype=None, device=None, **kwargs)

Bases: FinalTransform

Apply an affine transform encoded by an affine matrix

Parameters:

Name Type Description Default
matrix ([C], D+1, D+1) tensor

Matrix

required
flow ([C], D, *spatial) tensor

Precomputed flow field.

None
bound (zeros, border, reflection)

Padding mode

'zeros'
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

False

Other Parameters:

Name Type Description
returns [list or dict of] str
  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'matrix': The affine matrix
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

make_flow

make_flow(shape, matrix=None)

Make a flow field from an affine matrix.

Parameters:

Name Type Description Default
shape list of int

Shape of the output flow field

required
matrix ([C], D+1, D+1) tensor

Affine matrix (if not provided, self.matrix will be used)

None

Returns:

Name Type Description
flow ([C], D, *shape) tensor

The flow field

cc.ApplySlicewiseAffineTransform(matrix: tensor, flow: tensor | None = None, ...)
Apply a slice-wise affine transformation

cornucopia.geometric.ApplySlicewiseAffineTransform

ApplySlicewiseAffineTransform(matrix, flow=None, slice=-1, spacing=1, subsample=1, bound='border', **kwargs)

Bases: FinalTransform

Precomputed slicewise transform

Parameters:

Name Type Description Default
matrix (Nz, D+1, D+1) tensor

Affine matrices for each slice

required
flow (D, *spatial) tensor

Precomputed flow fields for each slice. If not provided, it will be computed from the matrices.

None
slice (0, 1, 2)

Slice direction

0
spacing int

Spacing between thick slices (as a number of high-res voxels)

1
subsample int

Additional isotropic subsampling

1
bound (zeros, border, reflection)

Padding mode

'zeros'

Other Parameters:

Name Type Description
returns [list or dict of] str
  • 'input': First transformed image
  • 'output': Second transformed image
  • 'flow': Displacement field
  • 'matrix': Stacked affine matrices (one per slice)
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

make_flow

make_flow(shape, matrix=None)

Compute the flow field for a given shape and matrix.

Parameters:

Name Type Description Default
shape list of int

Shape of the output flow field

required
matrix (Nz, D+1, D+1) tensor

Slicewise affine matrix (if not provided, self.matrix will be used)

None

Returns:

Name Type Description
flow (D, *shape) tensor

The flow field

cc.ApplyElasticTransform(flow: tensor | None = None, controls: tensor | None = None, ...)
Apply an elastic tranform

cornucopia.geometric.ApplyElasticTransform

ApplyElasticTransform(flow=None, controls=None, steps=0, order=3, bound='border', zero_center=False, nearest_if_label=True, dtype=None, device=None, **kwargs)

Bases: FinalTransform

Apply a (deterministic) elastic transform.

See also: ElasticTransform, RandomElasticTransform

Example

A transform can be used to obtain a flow field, instead of an output image, by specifying the returns argument. This flow field can then be applied to another image using the ApplyElasticTransform transform.

f = ElasticTransform(returns="flow")(x)
y = ApplyElasticTransform(flow=f)(x)

It is also possible to specify that the flow field should be read from one of the input arguments at call time, instead of being passed at instantiation time:

f = ElasticTransform(returns="flow")(x)
y = ApplyElasticTransform(flow="flow", consume="flow")(x, flow=f)

Parameters:

Name Type Description Default
flow (C, D, *spatial) tensor | (list | dict)[str | int] | None

Flow field. If not a tensor, it must be a (nested) input key. (if not provided, controls must be provided)

None
controls (C, D, *shape) tensor | (list | dict)[str | int] | None

Spline control points If not a tensor, it must be a (nested) input key. (if not provided, flow must be provided)

None
steps int

Number of scaling and squaring steps

0
order 1..7

Order of the splines that encode the smooth deformation.

3
bound (zeros, border, reflection)

Padding mode used for the deformed image.

'zeros'
zero_center bool

Subtract its mean displacement to the flow field so that it has an empirical mean of zero.

False
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

True

Other Parameters:

Name Type Description
returns [list or dict of] str

See Transform for details.

  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'controls': The control points of the displacement field
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

make_flow

make_flow(shape, controls=None)

Make a flow field from its spline control points.

Parameters:

Name Type Description Default
shape list of int

Shape of the output flow field

required
controls (C, D, *spatial) tensor

Spline control points (if not provided, self.controls will be used)

None

Returns:

Name Type Description
flow (C, D, *shape) tensor

The flow field

cc.ApplyAffineElasticTransform(flow: tensor | None = None, controls: tensor | None = None, affine: tensor | None = None, ...)
Apply an affine + elastic tranform

cornucopia.geometric.ApplyAffineElasticTransform

ApplyAffineElasticTransform(flow, controls, affine, bound='border', nearest_if_label=False, backend=None, **kwargs)

Bases: FinalTransform

Determinstic affine+elastic transform

Parameters:

Name Type Description Default
flow (C, D, *spatial) tensor

Flow field (if not provided, controls must be provided)

required
controls (C, D, *shape) tensor

Spline control points (if not provided, flow must be provided)

required
affine ([C], D+1, D+1) tensor

Affine matrix

required
bound str

Padding mode

'border'
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

False

Other Parameters:

Name Type Description
returns [list or dict of] str
  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'controls': The control points of the nonlinear field
  • 'matrix': The affine matrix
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

cc.AffineTransform(translations: vector_like[float] = 0, rotations: vector_like[float] = 0, shears: vector_like[float] = 0, zooms: vector_like[float] = 0)
Apply an affine transformation, encoded by its parameters

cornucopia.geometric.AffineTransform

AffineTransform(translations=0, rotations=0, shears=0, zooms=0, unit='fov', bound='border', nearest_if_label=False, *, dtype=None, device=None, shared=True, **kwargs)

Bases: NonFinalTransform

Apply an affine transform encoded by translations, rotations, shears and zooms.

The affine matrix is defined as: A = T @ Rx @ Ry @ Rz @ Sx @ Sy Sz @ Z with the center of the field of view used as center of rotation. (A is a matrix so the transforms are applied right to left)

Parameters:

Name Type Description Default
translations [list of] float

Translation (per X/Y/Z)

0
rotations [list of] float

Rotations (about Z/Y/X), in deg

0
shears [list of] float

Translation (about Z/Y/Z)

0
zooms [list of] float

Zoom about 1 (per X/Y/Z)

0
unit (fov, vox)

Unit of translations.

'fov'
bound (zeros, border, reflection)

Padding mode

'zeros'
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

False

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns [list or dict of] str
  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'matrix': The affine matrix
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = ApplyAffineTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ApplyAffineTransform

The transform type returned by unroll, next and final.

cc.SlicewiseAffineTransform(translations: list[float | list[float]] = 0, rotations: list[float | list[float]] = 0, shears: list[float | list[float]] = 0, zooms: list[float | list[float]] = 0)
Apply a slice-wise affine transformation

cornucopia.geometric.SlicewiseAffineTransform

SlicewiseAffineTransform(translations=0, rotations=0, shears=0, zooms=0, bulk_translations=0, bulk_rotations=0, bulk_shears=0, bulk_zooms=0, slice=-1, unit='fov', bound='border', spacing=1, subsample=1, *, shared=True, **kwargs)

Bases: NonFinalTransform

Each slice samples the 3D volume using a different transform

Parameters:

Name Type Description Default
translations list of [list of] float

Translation per slice (per X/Y/Z)

0
rotations list of [list of] float

Rotations per slice (about Z/Y/X), in deg

0
shears list of [list of] float

Shears per slice (about Z/Y/Z)

0
zooms list of [list of] float

Zoom about 1 per slice (per X/Y/Z)

0
bulk_translations [list of] float

Bulk translation (per X/Y/Z)

0
bulk_rotations [list of] float

Bulk rotation (about Z/Y/X), in deg

0
bulk_shears l[list of] float

Bulk shear (about Z/Y/Z)

0
bulk_zooms [list of] float

Bulk zoom about 1 (per X/Y/Z)

0
slice (0, 1, 2)

Slice direction

0
unit (fov, vox)

Unit of translations.

'fov'
bound (zeros, border, reflection)

Padding mode

'zeros'
spacing int

Spacing between thick slices (as a number of high-res voxels)

1
subsample int

Additional isotropic subsampling

1

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns [list or dict of] str
  • 'input': First transformed image
  • 'output': Second transformed image
  • 'flow': Displacement field
  • 'matrix': Stacked affine matrices (one per slice)
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = ApplySlicewiseAffineTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ApplySlicewiseAffineTransform

The transform type returned by unroll, next and final.

Transforms with fixed parameters (but random coefficients)

cc.ElasticTransform(dmax: vector_like[float] = 0.1, unit: {'fov','vox'} = 'fov', shape: int | list[int] = 5, ...)
Sample a smooth elastic deformation.

cornucopia.geometric.ElasticTransform

ElasticTransform(dmax=0.1, unit='fov', shape=5, bound='border', steps=0, order=3, zero_center=False, nearest_if_label=True, *, dtype=None, device=None, shared=True, **kwargs)

Bases: NonFinalTransform

Elastic transform encoded by cubic splines.

The number of control points is fixed but coefficients are randomly sampled from a uniform distribution.

See also: ElasticTransform, RandomElasticTransform

Parameters:

Name Type Description Default
dmax (ndim,) vector_like[float]

Max displacement (per dimension).

0.1
unit (fov, vox)

Unit of dmax.

'fov'
shape [list of] int

Number of spline control points

5
bound (zeros, border, reflection)

Padding mode used for the deformed image.

'zeros'
steps int

Number of scaling-and-squaring integration steps

0
order 1..7

Order of the splines that encode the smooth deformation.

3
zero_center bool

Subtract its mean displacement to the flow field so that it has an empirical mean of zero.

False
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

True

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns [list or dict of] str

See Transform for details.

  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'controls': The control points of the displacement field
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = ApplyElasticTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ApplyElasticTransform

The transform type returned by unroll, next and final.

cc.AffineElasticTransform(dmax: vector_like[float] = 0.1, shape: int | list[int] = 5, steps: int = 0, translations: vector_like[float] = 0, rotations: vector_like[float] = 0, shears: vector_like[float] = 0, zooms: vector_like[float] = 0, ...)
Apply an affine + elastic transformation.

cornucopia.geometric.AffineElasticTransform

AffineElasticTransform(dmax=0.1, shape=5, steps=0, translations=0, rotations=0, shears=0, zooms=0, unit='fov', bound='border', patch=None, order=3, zero_center=False, nearest_if_label=False, *, dtype=None, device=None, shared=True, **kwargs)

Bases: NonFinalTransform

Affine + Elastic [+ Patch] transform.

Parameters:

Name Type Description Default
dmax (ndim,) vector_like[float]

Max displacement per dimension

0.1
shape [list of] int

Number of spline control points

5
steps int

Number of scaling-and-squaring integration steps

0
translations (ndim,) vector_like[float]

Translation (per X/Y/Z)

0
rotations (ndim,) vector_like[float]

Rotations (about Z/Y/X), in deg

0
shears (ndim,) vector_like[float]

Translation (about Z/Y/Z)

0
zooms (ndim,) vector_like[float]

Zoom about 1 (per X/Y/Z)

0
unit (fov, vox)

Unit of translations and dmax.

'fov'
bound (zeros, border, reflection)

Padding mode

'zeros'
patch [list of] int

Size of random patch to extract

None
order int

Spline order

3
zero_center bool

Subtract its mean displacement to the elastic flow field so that it has an empirical mean of zero. This has no effect on the affine component.

False
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

False

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

returns [list or dict of] str
  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'controls': The control points of the nonlinear field
  • 'matrix': The affine matrix
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = ApplyAffineElasticTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ApplyAffineElasticTransform

The transform type returned by unroll, next and final.

Transforms with random parameters

cc.RandomAffineTransform(translations: Sampler | vector_like[float] = 0.1, rotations: Sampler | vector_like[float] = 15, shears: Sampler | vector_like[float] = 0.012, Sampler | zooms: vector_like[float] = 0.15, ..., *, shared: bool | str = True)
Apply a random affine transformation

cornucopia.geometric.RandomAffineTransform

RandomAffineTransform(translations=0.1, rotations=15, shears=0.012, zooms=0.15, iso=False, unit='fov', bound='border', nearest_if_label=False, *, dtype=None, device=None, shared=True, shared_matrix=None, **kwargs)

Bases: NonFinalTransform

Affine Transform with random parameters.

Parameters:

Name Type Description Default
translations Sampler or [list of] float

Sampler or Upper bound for translation (per X/Y/Z)

0.1
rotations Sampler or [list of] float

Sampler or Upper bound for rotations (about Z/Y/X), in deg

15
shears Sampler or [list of] float

Sampler or Upper bound for shears (about Z/Y/Z)

0.012
zooms Sampler or [list of] float

Sampler or Upper bound for zooms about 1 (per X/Y/Z)

0.15
iso bool

Use isotropic zoom

False
unit (fov, vox)

Unit of translations.

'fov'
bound (zeros, border, reflection)

Padding mode

'zeros'
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

False

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

shared_matrix Optional[SharedT]

Apply the same random matrix to all images/channels. Default: same as shared

returns [list or dict of] str
  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'matrix': The affine matrix
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = AffineTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = ApplyAffineTransform

The transform type returned by final.

cc.RandomSlicewiseAffineTransform(translations: list[float | list[float]] = 0, rotations: list[float | list[float]] = 0, shears: list[float | list[float]] = 0, zooms: list[float | list[float]] = 0)
Apply a random slice-wise affine transformation

cornucopia.geometric.RandomSlicewiseAffineTransform

RandomSlicewiseAffineTransform(translations=0.1, rotations=15, shears=0, zooms=0, bulk_translations=0.05, bulk_rotations=15, bulk_shears=0, bulk_zooms=0, iso=False, slice=-1, spacing=1, subsample=1, shots=2, nodes=8, unit='fov', bound='border', *, shared=True, shared_matrix=None, **kwargs)

Bases: NonFinalTransform

Slicewise3DAffineTransform with random parameters.

Parameters:

Name Type Description Default
translations Sampler or [list of] float or (*, 1|D) tensor

Sampler or Upper bound for translation (per X/Y/Z)

0.1
rotations Sampler or [list of] float or (*, 1|D(D-1)/2) tensor

Sampler or Upper bound for rotations (about Z/Y/X), in deg

15
shears Sampler or [list of] float or (*, 1|D(D-1)/2) tensor

Sampler or Upper bound for shears (about Z/Y/Z)

0
zooms Sampler or [list of] float or (*, 1|D) tensor

Sampler or Upper bound for zooms about 1 (per X/Y/Z)

0
bulk_translations [list of] float

Sampler or Upper bound for Bulk translation (per X/Y/Z)

0.05
bulk_rotations [list of] float

Sampler or Upper bound for Bulk rotation (about Z/Y/X), in deg

15
bulk_shears l[list of] float

Sampler or Upper bound for Bulk shear (about Z/Y/Z)

0
bulk_zooms [list of] float

Sampler or Upper bound for Bulk zoom about 1 (per X/Y/Z)

0
iso bool

Use isotropic zoom

False
slice Sampler or int

Slice direction. If None, a random slice direction is selected.

-1
spacing Sampler or int

Spacing between thick slices (as a number of high-res voxels)

1
subsample Sampler or int

Additional isotropic subsampling

1
shots Sampler or int

Number of interleaved sweeps. Typically, two interleaved sequences of slices are acquired to avoid slice cross talk.

2
nodes Sampler or int

Sampler or Upper bound for the number of nodes in the motion trajectory (encoded by cubic splines). If None, independent motions are sampled for each slice.

8
unit (fov, vox)

Unit of translations.

'fov'
bound (zeros, border, reflection)

Padding mode

'zeros'

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

shared_matrix Optional[SharedT]

Apply the same affine matrix to all images/channels. Default: same as shared.

returns [list or dict of] str
  • 'input': First transformed image
  • 'output': Second transformed image
  • 'flow': Displacement field
  • 'matrix': Stacked affine matrices (one per slice)
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = SlicewiseAffineTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = ApplySlicewiseAffineTransform

The transform type returned by final.

cc.RandomElasticTransform(dmax: Sampler | vector_like[float] = 0.1, shape: Sampler | int | list[int] = 5, unit: {'fov','vox'} = 'fov', ...)
Apply a random elsstic transformation

cornucopia.geometric.RandomElasticTransform

RandomElasticTransform(dmax=0.1, shape=5, unit='fov', bound='border', steps=0, order=3, zero_center=False, nearest_if_label=False, *, dtype=None, device=None, shared=True, shared_flow=None, **kwargs)

Bases: NonFinalTransform

Elastic Transform with random parameters.

See also: ElasticTransform, RandomElasticTransform

Example

# Apply the same transform to two images (default)
xform = RandomElasticTransform(dmax=0.2, shape=10)
x, y = xform(x, y)

# Apply one transform per image (but shared across channels)
xform = RandomElasticTransform(dmax=0.2, shape=10, shared='channels')
x, y = xform(x, y)

# Sample a set of transforms, and apply them
xform = RandomElasticTransform(dmax=0.2, shape=10)
a, b, c = [xform.final() for _ in range(3)]
x, y, z = a(x), b(y), c(z)

Parameters:

Name Type Description Default
dmax Sampler or float

Sampler or Upper bound for maximum displacement

0.1
shape Sampler or int

Sampler or Upper bound for number of control points

5
unit (fov, vox)

Unit of dmax

'fov'
bound (zeros, border, reflection)

Padding mode

'zeros'
steps int

Number of scaling-and-squaring integration steps

0
order int

Spline order

3
zero_center bool

Subtract its mean displacement to the flow field so that it has an empirical mean of zero.

False
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

False

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

shared_flow Optional[SharedT]

Apply the same random flow to all images/channels. Default: same as shared

returns [list or dict of] str

See Transform for details.

  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'controls': The control points of the displacement field
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = ElasticTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = ApplyElasticTransform

The transform type returned by final.

cc.RandomAffineElasticTransform(Sampler | dmax: vector_like[float] = 0.1, shape: Sampler | int | list[int] = 5, steps: int = 0, translations: Sampler | vector_like[float] = 0, rotations: Sampler | vector_like[float] = 0, shears: Sampler | vector_like[float] = 0, zooms: Sampler | vector_like[float] = 0, ...)
Apply an affine + elastic transformation.

cornucopia.geometric.RandomAffineElasticTransform

RandomAffineElasticTransform(dmax=0.1, shape=5, steps=0, translations=0, rotations=0, shears=0, zooms=0, iso=False, unit='fov', bound='border', patch=None, order=3, zero_center=False, nearest_if_label=False, *, dtype=None, device=None, shared=True, shared_flow=None, **kwargs)

Bases: NonFinalTransform

Random Affine + Elastic transform.

Parameters:

Name Type Description Default
dmax Sampler or float

Sampler or Upper bound for maximum displacement

0.1
shape Sampler or int

Sampler or Upper bounds for number of control points

5
steps int

Number of scaling-and-squaring integration steps

0
translations Sampler or [list of] float

Sampler or Upper bound for translation (per X/Y/Z)

0
rotations Sampler or [list of] float

Sampler or Upper bound for rotations (about Z/Y/X), in deg

0
shears Sampler or [list of] float

Sampler or Upper bound for shears (about Z/Y/Z)

0
zooms Sampler or [list of] float

Sampler or Upper bound for zooms about 1 (per X/Y/Z)

0
iso bool

Use isotropic zoom

False
unit (fov, vox)

Unit of translations.

'fov'
bound (zeros, border, reflection)

Padding mode

'zeros'
patch [list of] int

Size of random patch to extract

None
order int

Spline order

3
zero_center bool

Subtract its mean displacement to the elastic flow field so that it has an empirical mean of zero. This has no effect on the affine component.

False
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

False

Other Parameters:

Name Type Description
shared SharedT

See NonFinalTransform for details.

shared_flow Optional[SharedT]

Apply the same random flow to all images/channels. Default: same as shared

returns [list or dict of] str
  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The displacement field
  • 'controls': The control points of the nonlinear field
  • 'matrix': The affine matrix
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Next class-attribute instance-attribute

Next = AffineElasticTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = ApplyAffineElasticTransform

The transform type returned by final.

cc.labels: Transforms that act on label maps

Deterministic transforms

cc.OneHotTransform(label_map: list[int | str | list[int | str]] | None = None, label_ref: dict[str, int] | None = None, ...)
Transform a volume of integer labels into a one-hot representation.

cornucopia.labels.OneHotTransform

OneHotTransform(label_map=None, label_ref=None, keep_background=True, dtype=None, **kwargs)

Bases: NonFinalTransform

Transform a volume of integer labels into a one-hot representation

Parameters:

Name Type Description Default
label_map list or [list of] (int | str)

Map one-hot classes to [list of] labels or label names

Should not include the background class

None
label_ref dict[int, str]

Map label values to label names

None
keep_background bool

If True, the first one-hot class is the background class, and the one hot tensor sums to one.

True
dtype dtype

Use a different dtype for the one-hot

None

Final class-attribute instance-attribute

Final = OneHotFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = OneHotFinalTransform

The transform type returned by unroll, next and final.

cc.ArgMaxTransform()
Take the argmax along the channel dimension.

cornucopia.labels.ArgMaxTransform

ArgMaxTransform(*, returns=None, append=False, prefix=True, include=None, exclude=None, consume=None)

Bases: FinalTransform

Take the argmax along the channel dimension

cc.RelabelTransform(labels: list[int | list[int]] | None = None)
Relabel a label map.

cornucopia.labels.RelabelTransform

RelabelTransform(labels=None, **kwargs)

Bases: NonFinalTransform

Relabel a label map.

Note

  • The labels are mapped to the range {1..len(labels)}.

  • If an element of this list is a sublist of indices, indices in the sublist are merged.

  • All labels absent from the list are mapped to 0.

Parameters:

Name Type Description Default
labels list of [list of] int | None

Relabeling scheme.

None

Final class-attribute instance-attribute

Final = RelabelFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = RelabelFinalTransform

The transform type returned by unroll, next and final.

cc.ErodeLabelTransform(labels: int | list[int] = (), radius: int | list[int] = 3, method: {'conv','l1','l2'} = 'conv', ...)
Morphological erosion.

cornucopia.labels.ErodeLabelTransform

ErodeLabelTransform(labels=tuple(), radius=3, method='conv', new_labels=False, **kwargs)

Bases: FinalTransform

Morphological erosion.

Parameters:

Name Type Description Default
labels [sequence of] int

Labels to erode

tuple()
radius [sequence of] int

Erosion radius (per label)

3
method (conv, l1, l2)

Method to use to compute the distance map. If 'conv', use the L1 distance computed using a series of convolutions. The radius will be rounded to the nearest integer. Otherwise, use the appropriate distance transform.

'conv'
new_labels bool | [sequence of] int

If not False, the eroded portion of each label gives rise to a new label. If True, create new unique labels.

False
cc.DilateLabelTransform(labels: int | list[int] = (), radius: int | list[int] = 3, method: {'conv','l1','l2'} = 'conv', ...)
Morphological erosion.

cornucopia.labels.DilateLabelTransform

DilateLabelTransform(labels=tuple(), radius=3, method='conv', **kwargs)

Bases: FinalTransform

Morphological dilation.

Parameters:

Name Type Description Default
labels [sequence of] int

Labels to dilate. By default, all but zero.

tuple()
radius [sequence of] int

Dilation radius (per label)

3
method (conv, l1, l2)

Method to use to compute the distance map. If 'conv', use the L1 distance computed using a series of convolutions. The radius will be rounded to the nearest integer. Otherwise, use the appropriate distance transform.

'conv'

Transforms with fixed parameters (but random coefficients)

cc.GaussianMixtureTransform(mu: vector_like[float] | None = None, sigma: vector_like[float] | None = None, fwhm: vector_like[float] = 0, ...)
Sample from a Gaussian mixture.

cornucopia.labels.GaussianMixtureTransform

GaussianMixtureTransform(mu=None, sigma=None, fwhm=0, background=None, dtype=None, *, shared=False, **kwargs)

Bases: NonFinalTransform

Sample from a Gaussian mixture with known cluster assignment

Parameters:

Name Type Description Default
mu list[float]

Mean of each cluster. Default: random in (0, 1).

None
sigma list[float]

Standard deviation of each cluster. Default: 1/nb_classes.

None
fwhm float | list[float]

Width of a within-class smoothing kernel.

0
background int | None

Index of background channel, which does not get filled. Default: fill all classes.

None
dtype dtype

Output data type. Only used if input is an integer label map.

None

Next class-attribute instance-attribute

Next = GaussianMixtureFinalTransform

The transform type returned by unroll, next and final.

Final class-attribute instance-attribute

Final = GaussianMixtureFinalTransform

The transform type returned by unroll, next and final.

cc.SmoothLabelMap(nb_classes: int = 2, shape: int | list[int] = 5, soft: bool = True, *, shared: bool | str = False)
Generate a random label map.

cornucopia.labels.SmoothLabelMap

SmoothLabelMap(nb_classes=2, shape=5, soft=False, *, shared=False, **kwargs)

Bases: NonFinalTransform

Generate a random label map

Parameters:

Name Type Description Default
nb_classes int

Number of classes

2
shape [list of] int

Number of spline control points

5
soft bool

Return a soft (one-hot) label map

False

Other Parameters:

Name Type Description
shared (channels, tensors, channels + tensors, '')

Apply the same field to all tensors/channels

cc.SmoothMorphoLabelTransform(labels: int | list[int] = (), min_radius: int | list[int] = -3, max_radius: int | list[int] = 3, shape: int | list[int] = 5, conv: {'conv','l1','l2'} = 'conv')
Morphological erosion/dilation with spatially varying radius.

cornucopia.labels.SmoothMorphoLabelTransform

SmoothMorphoLabelTransform(labels=tuple(), min_radius=-3, max_radius=3, shape=5, method='conv', *, shared=False, **kwargs)

Bases: NonFinalTransform

Morphological erosion with spatially varying radius.

Note

We're actually computing the level set of each label and pushing it up and down using a smooth "radius" map. In theory, this can create "holes" or "islands", which would not happen with a normal erosion. With radii that are small and radius map that are smooth compared to the label size, it should be fine.

Warning

The radius maps are sampled for each tensor. It is impossible to share them across tensors. The only shared options are therefore channels or False.

Parameters:

Name Type Description Default
labels [sequence of] int

Labels to erode

tuple()
min_radius [sequence of] int

Minimum erosion (if < 0) or dilation (if > 0) radius (per label)

-3
max_radius [sequence of] int

Maximum erosion (if < 0) or dilation (if > 0) radius (per label)

3
shape [sequence of] int

Number of nodes in the smooth radius map

5
method (conv, l1, l2)

Method to use to compute the distance map. If 'conv', use the L1 distance computed using a series of convolutions. The radius will be rounded to the nearest integer. Otherwise, use the appropriate distance transform.

'conv'

Final class-attribute instance-attribute

Final = SmoothMorphoLabelFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = SmoothMorphoLabelFinalTransform

The transform type returned by unroll, next and final.

cc.SmoothShallowLabelTransform(labels: int | list[int] = (), max_width: int | list[int] = 5, min_width: int | list[int] = 1, shape: int | list[int] = 5, ...)
Make labels "empty", with a border of a given size.

cornucopia.labels.SmoothShallowLabelTransform

SmoothShallowLabelTransform(labels=tuple(), max_width=5, min_width=1, shape=5, background_labels=tuple(), method='l2', *, shared=False, **kwargs)

Bases: NonFinalTransform

Make labels "empty", with a border of a given size.

Parameters:

Name Type Description Default
labels [sequence of] int

Labels to make shallow

tuple()
max_width [sequence of] int

Maximum border width (per label)

5
min_width [sequence of] int

Minimum border width (per label)

1
shape [sequence of] int

Number of nodes in the smooth width map

5
background_labels [sequence of] int

Labels that are allowed to grow into the shallow space (default: all that are not in labels)

tuple()
method (l1, l2)

Method to use to compute the distance map.

'l1'

Final class-attribute instance-attribute

Final = SmoothShallowLabelFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = SmoothShallowLabelFinalTransform

The transform type returned by unroll, next and final.

cc.BernoulliTransform(prob: float = 0.1)
Randomly mask voxels.

cornucopia.labels.BernoulliTransform

BernoulliTransform(prob=0.1, *, shared=False, **kwargs)

Bases: NonFinalTransform

Randomly mask voxels

Parameters:

Name Type Description Default
prob float

Probability of masking out a voxel

0.1

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'noise'}

Which tensor to return

shared bool

Same mask shared across channels

Next class-attribute instance-attribute

Next = MulValueTransform

The transform type returned by unroll, next and final.

Final class-attribute instance-attribute

Final = MulValueTransform

The transform type returned by unroll, next and final.

cc.SmoothBernoulliTransform(prob: float = 0.1, shape: int | list[int] = 5, *, shared: bool | str = False)
Randomly mask voxels.

cornucopia.labels.SmoothBernoulliTransform

SmoothBernoulliTransform(prob=0.1, shape=5, *, shared=False, shared_noise=False, **kwargs)

Bases: NonFinalTransform

Randomly mask voxels

Parameters:

Name Type Description Default
prob float

Probability of masking out a voxel

0.1
shape int or sequence[int]

Number of control points in the smooth field

5

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'noise'}

Which tensor to return

shared bool

Same probability field shared across channels/tensor

shared_noise bool

Same mask shared across channels/tensor

Final class-attribute instance-attribute

Final = MulValueTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = MulValueTransform

The transform type returned by unroll, next and final.

cc.BernoulliDiskTransform(prob: float = 0.1, radius: Sampler | float = 2)
Randomly mask voxels in balls at random locations.

cornucopia.labels.BernoulliDiskTransform

BernoulliDiskTransform(prob=0.1, radius=2, value=0, method='l2', *, shared=False, **kwargs)

Bases: NonFinalTransform

Randomly mask voxels in balls at random locations

Parameters:

Name Type Description Default
prob float

Probability of masking out a voxel

0.1
radius float or Sampler

Disk radius

2
value float or int or {min, max, rand}

Value to set in the disks

0
method (conv, l1, l2)

Method used to compute the distance map

'conv'
returns [list or dict of] {'input', 'output', 'disks'}

Which tensor to return

required
shared bool

Same mask shared across channels

False

Final class-attribute instance-attribute

Final = FillValueTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = FillValueTransform

The transform type returned by unroll, next and final.

cc.SmoothBernoulliDiskTransform(prob: float = 0.1, radius: float | tuple[float, float] = 2, shape: int | list[int] = 5, ..., *, shared: bool | str = False)
Randomly mask voxels in balls at random locations.

cornucopia.labels.SmoothBernoulliDiskTransform

SmoothBernoulliDiskTransform(prob=0.1, radius=2, shape=5, value=0, method='l2', *, shared=False, shared_field=None, **kwargs)

Bases: NonFinalTransform

Randomly mask voxels in balls at random locations

Parameters:

Name Type Description Default
prob float

Probability of masking out a voxel A probability field is sampled from a smooth random field.

0.1
radius float or (float, float)

Max or Min/Max disk radius, sampled from a smooth random field.

2
shape int or sequence[int]

Number of control points in the random field

5
value float or int or {min, max, rand}

Value to set in the disks. If 'rand', a random value in the input range is used for each disk.

0
method (conv, l1, l2)

Method used to compute the distance map

'conv'
returns [list or dict of] {'input', 'output', 'disks'}

Which tensor to return

required
shared bool

Same mask shared across channels

False

Final class-attribute instance-attribute

Final = FillValueTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = FillValueTransform

The transform type returned by unroll, next and final.

Transforms with random parameters

TODO

cc.kspace: Transforms that act on k-space (Fourier domain)

Deterministic transforms

cc.SumOfSquaresTransform()
Compute the sum-of-squares across coils/channels.

cornucopia.kspace.SumOfSquaresTransform

SumOfSquaresTransform(*, returns=None, append=False, prefix=True, include=None, exclude=None, consume=None)

Bases: FinalTransform

Compute the sum-of-squares across coils/channels

Transforms with fixed parameters (but random coefficients)

cc.ArrayCoilTransform(ncoils: int = 8, fwhm: float = 0.5, diameter: float = 0.8, jitter: float = 0.01, ...)
Generate and apply random coil sensitivities (real or complex).

cornucopia.kspace.ArrayCoilTransform

ArrayCoilTransform(ncoils=8, fwhm=0.5, diameter=0.8, jitter=0.01, unit='fov', shape=4, sos=True, *, shared=True, **kwargs)

Bases: NonFinalTransform

Generate and apply random coil sensitivities (real or complex)

Parameters:

Name Type Description Default
ncoils int

Number of complex receiver channels

8
fwhm float

Width of each receiver profile

0.5
diameter float

Diameter of the ellipsoid on wich receivers are centered

0.8
jitter float

Amount of jitter off the ellipsoid

0.01
unit (fov, vox)

Unit of fwhm, diameter, jitter

'fov'
shape [list of] int

Number of control points for the underlying smooth component.

4

Other Parameters:

Name Type Description
shared

See NonFinalTransform for details.

returns [(list | dict) of] str

See Transform for details. Default is 'uncombined'.

Value Description
'sos' Sum of square combined (magnitude) image
'uncombined' Uncombined (complex) coil images
'sens' Uncombined (complex) coil sensitivities
'netsens' Net (magnitude) coil sensitivity
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = ArrayCoilCombinationTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ArrayCoilCombinationTransform

The transform type returned by unroll, next and final.

Transforms with random parameters

cc.IntraScanMotionTransform(shots: int = 4, axis: int = -1, freq: bool = True, ...)
Model intra-scan motion.

cornucopia.kspace.IntraScanMotionTransform

IntraScanMotionTransform(shots=4, axis=-1, freq=True, pattern='sequential', translations=0.1, rotations=15, sos=True, coils=None, *, shared='channels', **kwargs)

Bases: NonFinalTransform

Model intra-scan motion

Parameters:

Name Type Description Default
shots int

Number of acquisition shots. The object is in a different position in each shot.

4
axis int

Axis along which shots are acquired (slice or phase-encode)

-1
freq bool

Motion happens across a phase-encode direction, which means that the k-space is build from pieces with different object position. This typically happens in "3D" acquisitions. If False, motion happens along the slice direction ("2D" acquisition).

True
pattern (sequential, random)

k-space (or slice) sampling pattern. This argument encodes the frequencies (or slices) that are acquired in each shot. The 'sequential' options assumes that frequencies are acquired in order. The 'random' option assumes that frequencies are randomly distributed across shots.

'sequential'
translations Sampler or float

Sampler (or upper-bound) for random translations (in % of FOV)

0.1
rotations Sampler or float

Sampler (or upper-bound) for random rotations (in deg)

15
sos bool

Whether to return the sum-of-squares combined image across coils.

True
coils Transform

A transform that generates a set of complex sensitivity profiles

None

Other Parameters:

Name Type Description
shared Union[str, bool]

See NonFinalTransform for details.

returns [(list | dict) of] str

See Transform for details. Default is 'sos'.

Value Description Shape
'sos' Sum of square combined (magnitude) image (C,X,Y,Z)
'uncombined' Uncombined (complex) coil images (K,X,Y,Z)
'sens' Uncombined (complex) coil sensitivities (K,X,Y,Z)
'netsens' Net (magnitude) coil sensitivity (1,X,Y,Z)
'flow' Displacement field in each shot (N,3,X,Y,Z)
'matrix' Rigid matrix in each shot (N,4,4)
'pattern' Frequencies acquired in each shot (N,X)
append

See Transform for details.

prefix

See Transform for details.

include

See Transform for details.

exclude

See Transform for details.

consume

See Transform for details.

Final class-attribute instance-attribute

Final = IntraScanMotionFinalTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = IntraScanMotionFinalTransform

The transform type returned by unroll, next and final.

cc.SmallIntraScanMotionTransform(translations: Sampler | float = 0.05, rotations: Sampler | float = 5, axis: int = -1)
Model small intra-scan motion.

cornucopia.kspace.SmallIntraScanMotionTransform

SmallIntraScanMotionTransform(translations=0.05, rotations=5, axis=-1, *, shared='channels', **kwargs)

Bases: IntraScanMotionTransform

Model intra-scan motion that happens once across k-space

Parameters:

Name Type Description Default
translations Sampler or float

Sampler (or upper-bound) for random translations (in % of FOV)

0.05
rotations Sampler or float

Sampler (or upper-bound) for random rotations (in deg)

5
axis int

Axis along which shots are acquired (slice or phase-encode)

-1

Other Parameters:

Name Type Description
shared Union[str, bool]

See IntraScanMotionTransform for details.

append Union[str, bool]

See IntraScanMotionTransform for details.

prefix Union[str, bool]

See IntraScanMotionTransform for details.

include Union[str, bool]

See IntraScanMotionTransform for details.

exclude Union[str, bool]

See IntraScanMotionTransform for details.

consume Union[str, bool]

See IntraScanMotionTransform for details.

cc.qmri: Quantitative MRI

Deterministic transforms

cc.SusceptibilityToFieldmapTransform(axis: int | vector_like[float] = -1, ...)
Convert a susceptibiity map (in ppm) into a field map (in Hz).

cornucopia.qmri.SusceptibilityToFieldmapTransform

SusceptibilityToFieldmapTransform(axis=-1, field_strength=3, larmor=42576000.0, s0=0.4, s1=-9.5, voxel_size=1, mask_air=False, **kwargs)

Bases: FinalTransform

Convert a susceptibiity map (in ppm) into a field map (in Hz)

Parameters:

Name Type Description Default
axis int | sequence[float]

Direction of the main magnetic field. - If a vector or floats, it is unit vector that encodes the direction of the main magnetic field in the "scaled voxel" coordinate systems. - If an int, the main magnetic field is assumed to be aligned with one of the dimensions of the voxel grid, and zaxis is the index of this dimension. I.e., 0 is equivalent to [1, 0, 0].

-1
field_strength float

Strength of the main magnetic field, in Tesla. If None, return a fieldmap in ppm.

3
larmor float

Larmor frequency (default: Larmor frequency of water)

42576000.0
s0 float

Susceptibility of air (ppm)

0.4
s1 float

Susceptibility of tissue minus susceptiblity of air (ppm) (only used if ds is a boolean mask)

-9.5
voxel_size [list of] float

Voxel size

1
mask_air bool

Mask air (where delta susceptibility == 0) from resulting fieldmap.

False
cc.ShimTransform(linear: vector_like[float] = 0, quadratic[float] = 0, isocenter: vector_like[float] | None = None)
Apply a shim field to the input field map.

cornucopia.qmri.ShimTransform

ShimTransform(linear=None, quadratic=None, isocenter=None, **kwargs)

Bases: FinalTransform

Apply a shim field to the input field map.

Parameters:

Name Type Description Default
linear (3|1,) tensor | [list of] float

Linear components (3D: [XY, XZ, YX], 2D: [XY])

None
quadratic (2|1,) tensor | [list of] float

Quadratic components (3D: [XXYY, XXZZ], 2D: [XXYY])

None
isocenter (3|2,) tensor | [list of] float

Coordinates of the isocenter, in voxels

None

Other Parameters:

Name Type Description
returns [(list | dict) of] {'input', 'output', 'shim'}
cc.OptimalShimTransform(max_order: int = 2, lam_abs: float = 1, lam_grad: float = 10)
Compute an optimal shim field for the input field map.

cornucopia.qmri.OptimalShimTransform

OptimalShimTransform(max_order=2, lam_abs=1, lam_grad=10, mask=True, isocenter=None, **kwargs)

Bases: NonFinalTransform

Compute a linear combination of spherical harmonics that flattens the input field map

Parameters:

Name Type Description Default
max_order int

Maximum order of spherical basis functions

2
lam_abs float

Regularization factor for absolute values

1
lam_grad float

Regularization factor for first order gradients

10
mask bool | Tensor

Mask zeros/NaNs from objective functions

True
isocenter (3|2,) tensor | [list of] float

Coordinates of the isocenter, in voxels. Defaults to the center of the image.

None

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'shim'}

Next class-attribute instance-attribute

Next = AddValueTransform

The transform type returned by unroll, next and final.

Final class-attribute instance-attribute

Final = AddValueTransform

The transform type returned by unroll, next and final.

cc.HertzToPhaseTransform(te: float = 0)
Converts a ΔB0 field (in Hz) into a Phase shift field Δφ (in rad).

cornucopia.qmri.HertzToPhaseTransform

HertzToPhaseTransform(te=0, **kwargs)

Bases: FinalTransform

Converts a ΔB0 field (in Hz) into a Phase shift field Δφ (in rad)

Parameters:

Name Type Description Default
te float

Echo time, in sec.

0
cc.HertzToVoxelShiftTransform(te: float = 0)
Converts a ΔB0 field (in Hz) into a voxel shift field Δv.

cornucopia.qmri.HertzToVoxelShiftTransform

HertzToVoxelShiftTransform(bandwidth=30, **kwargs)

Bases: FinalTransform

Converts a ΔB0 field (in Hz) into a voxel shift field Δv

Parameters:

Name Type Description Default
bandwidth float

Bandwidth per pixel along the slow direction, in Hz/pixel.

This is the phase-encoding direction in an EPI sequence. It can also be the frequency-encoding direction in a non-EPI sequence, although in such cases the bandwidth per pixel is much larger, and displacements are only meaningful in extremely high-resolution scans.

v0.4 Default changed from 140 to 30

30
cc.ApplyB0DistortionTransform(flow: tensor | str | None = None, vdm: tensor | str | None = None, controls: tensor | str | None = None, ...)
Apply a pre-compute B0 distortion field.

cornucopia.qmri.ApplyB0DistortionTransform

ApplyB0DistortionTransform(flow=None, vdm=None, controls=None, axis=-1, order=3, bound='border', nearest_if_label=True, *, dtype=None, device=None, **kwargs)

Bases: FinalTransform

Apply a pre-computed B0 voxel displacement map.

Parameters:

Name Type Description Default
flow (C, D, *spatial) tensor | [list of] (str | int)

Flow field (in voxels), If an index or list of indices, they are used to retrieve the flow from the called arguments. (If not provided, vdm of controls must be provided)

None
vdm (C, *spatial) tensor

Voxel displacement field If an index or list of indices, they are used to retrieve the flow from the called arguments. (If not provided, controls or flow must be provided)

None
controls (C, *shape) tensor

Spline control points If an index or list of indices, they are used to retrieve the flow from the called arguments. (If not provided, vdm or flow must be provided)

None
axis int | sequence[float]

If int, the distortion is applied along this dimension. If sequence of floats, it is a unit vector that encodes the direction of the distortion in the voxel coordinate system.

-1
order 1..7

Order of the splines that encode the smooth deformation.

3
bound (zeros, border, reflection)

Padding mode used for the deformed image.

'zeros'
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

True

make_vdm

make_vdm(shape, controls=None)

Upsample the control points to the final full size

Parameters:

Name Type Description Default
shape list[int]

Target shape

required
controls (C, *shape) tensor

Spline control points

`self.controls`

Returns:

Name Type Description
vdm (C, *fullshape) tensor

Upampled voxel displacement field

make_flow

make_flow(vdm)

Make a flow field from the voxel displacement map

cc.GradientEchoTransform(tr: float = 25e-3, te: float = 7e-3, alpha: float = 20, pd: float | None = None, t1: float | None = None, t2: float | None = None, b1: float | None = 1, mt: float | None = 0)
Spoiled Gradient Echo forward model.

cornucopia.qmri.GradientEchoTransform

GradientEchoTransform(tr=0.025, te=0.007, alpha=20, pd=None, t1=None, t2=None, b1=1, mt=0, **kwargs)

Bases: FinalTransform

Spoiled Gradient Echo forward model

Parameters:

Name Type Description Default
tr float

Repetition time, in sec

0.025
te float

Echo time, in sec

0.007
alpha float

Nominal flip angle, in degree

20
pd float | None

Proton density (PD). If None, the first input channel is PD.

None
t1 float | None

Longitudinal relaxation time (T1), in sec. If None, the second input channel is T1.

None
t2 float | None

Apparent transverse relaxation time (T2), in sec. If None, the third input channel is T2.

None
b1 float | None

Transmit efficiency (B1+). 1 means 100% efficiency. If None, the fourth input channel is B1+.

1
mt float | None

Magnetization transfer saturation (MTsat). If None, the fifth input channel is MTsat.

0

get_parameters

get_parameters(x)

Assign each input channel to the appropriate parameter.

Transforms with fixed parameters (but random coefficients)

cc.B0DistortionTransform(dmax: float = 0.1, unit: {'fov','vox'} = 'fov', shape: int | list[int] = 5, ...)
Compute and apply a B0 distortion field..

cornucopia.qmri.B0DistortionTransform

B0DistortionTransform(dmax=0.1, unit='fov', shape=5, bound='circular', order=3, nearest_if_label=True, axis=-1, *, dtype=None, device=None, shared=True, **kwargs)

Bases: NonFinalTransform

Elastic distortion along a single dimension.

The number of control points is fixed but coefficients are randomly sampled from a uniform distribution.

This is not a realistic B0 distortion model. For a more realistic model, see RealisticB0DistortionTransform.

Parameters:

Name Type Description Default
dmax float

Max displacement

0.1
unit (fov, vox)

Unit of dmax.

'fov'
shape [list of] int

Number of spline control points

5
bound (zeros, border, reflection, circular)

Padding mode used for the deformed image.

'zeros'
order 1..7

Order of the splines that encode the smooth deformation.

3
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

True
axis int | sequence[float]

If int, the distortion is applied along this dimension. If sequence of floats, it is a unit vector that encodes the direction of the distortion in the voxel coordinate system.

-1

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'flow', 'vdm', 'controls'}
  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The flow field
  • 'vdm': The voxel displacement map (VDM)
  • 'controls': The control points of the VDM
shared (channels, tensors, channels + tensors, '')

Apply same transform to all images/channels

Final class-attribute instance-attribute

Final = ApplyB0DistortionTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ApplyB0DistortionTransform

The transform type returned by unroll, next and final.

Transforms with random parameters

cc.RandomSusceptibilityMixtureTransform(...)
A RandomGaussianMixtureTransform tailored to susceptibility maps.

cornucopia.qmri.RandomSusceptibilityMixtureTransform

RandomSusceptibilityMixtureTransform(mu_tissue=Uniform(9, 10), sigma_tissue=0.01, mu_bone=Uniform(12, 13), sigma_bone=0.1, fwhm=2, label_air=0, label_bone=None, dtype=None, *, shared='channels', **kwargs)

Bases: NonFinalTransform

A RandomGaussianMixtureTransform tailored to susceptibility maps.

This transform returns a delta susceptibility map (with respect to air), in ppm.

Parameters:

Name Type Description Default
mu_tissue Sampler | float

Distribution of negative susceptibility offsets (in ppm) of soft tissues with respect to air. Will be negated (air susceptibility is larger than all tissues). If float: upper bound.

Uniform(9, 10)
sigma_tissue Sampler | float

Standard deviation of susceptibility offsets, within class. If float: uper bound.

0.01
mu_bone Sampler | float

Distribution of negative susceptibility offsets (in ppm) of hard tissues with respect to air. Will be negated (air susceptibility is larger than all tissues). If float: upper bound.

Uniform(12, 13)
sigma_bone SamplerOrBound[float]

Standard deviation of susceptibility offsets, within class. If float: upper bound.

0.1
fwhm Sampler | [list of] float

Sampling function for smoothing width. If float: upper bound.

2
label_air [list of] int

Labels corresponding to air.

0
label_bone [list of] int

Labels corresponding to bone and teeth.

None

Next class-attribute instance-attribute

Next = GaussianMixtureTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = GaussianMixtureFinalTransform

The transform type returned by final.

cc.RandomShimTransform(...)
Apply a random shim field to an input field.

cornucopia.qmri.RandomShimTransform

RandomShimTransform(coefficients=5, max_order=2, *, shared=False, **kwargs)

Bases: NonFinalTransform

Sample a random (imperfect) shim.

This function randomly samples the coefficients of a field encoded by spherical harmonics.

Parameters:

Name Type Description Default
coefficients Sampler | int

Sampler for spherical harmonics coefficients (or upper bound)

5
max_order Sampler | int

Sampler for spherical harmonics order (or upper bound)

2

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'shim'}
shared (channels, tensors, channels + tensors, '')

Next class-attribute instance-attribute

Next = ShimTransform

The transform type returned by next.

Final class-attribute instance-attribute

Final = AddValueTransform

The transform type returned by final.

cc.RandomB0DistortionTransform(dmax: Sampler | float = 0.1, shape: Sampler | int = 5, ...)
Apply a random B0 distortion field.

cornucopia.qmri.B0DistortionTransform

B0DistortionTransform(dmax=0.1, unit='fov', shape=5, bound='circular', order=3, nearest_if_label=True, axis=-1, *, dtype=None, device=None, shared=True, **kwargs)

Bases: NonFinalTransform

Elastic distortion along a single dimension.

The number of control points is fixed but coefficients are randomly sampled from a uniform distribution.

This is not a realistic B0 distortion model. For a more realistic model, see RealisticB0DistortionTransform.

Parameters:

Name Type Description Default
dmax float

Max displacement

0.1
unit (fov, vox)

Unit of dmax.

'fov'
shape [list of] int

Number of spline control points

5
bound (zeros, border, reflection, circular)

Padding mode used for the deformed image.

'zeros'
order 1..7

Order of the splines that encode the smooth deformation.

3
nearest_if_label bool

By default, if a tensor has an integer data type, it is deformed using label-specific resampling (each unique label is extracted and resampled using linear interpolation, and an argmax output label map is computed on the fly). If nearest_if_label=True, the entire label map will be resampled at once using nearest-neighbour interpolation.

True
axis int | sequence[float]

If int, the distortion is applied along this dimension. If sequence of floats, it is a unit vector that encodes the direction of the distortion in the voxel coordinate system.

-1

Other Parameters:

Name Type Description
returns [list or dict of] {'input', 'output', 'flow', 'vdm', 'controls'}
  • 'input': The input image
  • 'output': The deformed image
  • 'flow': The flow field
  • 'vdm': The voxel displacement map (VDM)
  • 'controls': The control points of the VDM
shared (channels, tensors, channels + tensors, '')

Apply same transform to all images/channels

Final class-attribute instance-attribute

Final = ApplyB0DistortionTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = ApplyB0DistortionTransform

The transform type returned by unroll, next and final.

cc.RandomGMMGradientEchoTransform(tr: Sampler | float = 50E-3, te: Sampler | float = 50E-3, alpha: Sampler | float = 90, ...)
A RandomGaussianMixtureTransform tailored to quantitative MRI maps, followed by a GRE forward model.

cornucopia.qmri.RandomGMMGradientEchoTransform

RandomGMMGradientEchoTransform(tr=0.05, te=0.05, alpha=90, pd=1, t1=10, t2=100, mt=0.1, b1=RandomMulFieldTransform(vmax=1.5), sigma=0.2, fwhm=2, **kwargs)

Bases: NonFinalTransform

Generate a Spoiled Gradient Echo image from synthetic PD/T1/T2 maps.

Parameters:

Name Type Description Default
tr Sampler | float

Random sampler for repetition time, or upper bound

0.05
te Sampler | float

Random sampler for echo time, or upper bound

0.05
alpha Sampler | float

Random sampler for nominal flip angle, or upper bound

90
pd Sampler | float

Random sampler for proton density, or upper bound

1
t1 Sampler | float

Random sampler for longitudinal relaxation, or upper bound

10
t2 Sampler | float

Random sampler for apparent transverse relaxation, or upper bound

100
mt Sampler | float

Random sampler for magnetization transfer saturation, or upper bound

0.1
b1 Transform

A transformation that samples a smooth multiplicative field

RandomMulFieldTransform(vmax=1.5)
sigma Sampler | float

Random sampler for intra-class standard deviation (in percent), or upper bound

0.2
fwhm Sampler | float

Random sampler for intra-class smoothing (in voxels), or upper bound

2

Final class-attribute instance-attribute

Final = GMMGradientEchoTransform

The transform type returned by unroll, next and final.

Next class-attribute instance-attribute

Next = GMMGradientEchoTransform

The transform type returned by unroll, next and final.

get_parameters

get_parameters(x)

Sample each parameter.

cc.synth: Synthesize images (domain randomization)

cc.IntensityTransform(...)
Common intensity augmentation for MRI and related images.

cornucopia.synth.IntensityTransform

IntensityTransform(bias=7, bias_strength=0.5, gamma=0.6, motion_fwhm=3, resolution=8, snr=10, gfactor=5, order=3, **kwargs)

Bases: SequentialTransform

Common intensity augmentation for MRI and related images

The arguments control the range of the distributions from which the transform parameters are sampled.

It is also possible to directly provide the probability distribution from which to sample the parametes. In this case, it must be a Sampler instance.

Setting any argument to False disables the corresponding transform entirely.

Reference

Billot, B., Greve, D.N., Puonti, O., Thielscher, A., Van Leemput, K., Fischl, B., Dalca, A.V. and Iglesias, J.E., 2023. SynthSeg: Segmentation of brain MRI scans of any contrast and resolution without retraining. Medical image analysis, 86, p.102789.

@article{billot2023synthseg,
  title     = {SynthSeg: Segmentation of brain MRI scans of any contrast and resolution without retraining},
  author    = {Billot, Benjamin and Greve, Douglas N and Puonti, Oula and Thielscher, Axel and Van Leemput, Koen and Fischl, Bruce and Dalca, Adrian V and Iglesias, Juan Eugenio and others},
  journal   = {Medical image analysis},
  volume    = {86},
  pages     = {102789},
  year      = {2023},
  publisher = {Elsevier},
  url       = {https://www.sciencedirect.com/science/article/pii/S1361841523000506}
}

Parameters:

Name Type Description Default
bias Sampler | int | {False}

The sampled value controls the smoothness of the intensity bias field (smaller values yield smoother fields). If an int, sample from RandInt(2, value).

7
bias_strength Sampler | float in (0..1)

The maximum magnitude of the bias field (about 1). If a float, sample from Uniform(0, value). The minimum and maximum values of the bias field will be 1 - bias_strength and 1 + bias_strength.

0.5
gamma Sampler | float | {False}

The Gamma transform squeezes intensities such that the contrast to noise ratio is decreased (positive values lead to less decreased contrast, positive values lead to increased contrast). If a float, sample the gamma exponent from LogNormal(0, value).

0.6
motion_fwhm Sampler | float | {False}

A blur can be perform to model the point spread function or motion-related smearing. The amount of smoothing is encoded by the full-width at half-maximum (FWHM) of the underlying Gaussian kernel. If a float, sample the FWHM from Uniform(0, value).

3
resolution Sampler | float | {False}

Thick-slice or isotropic low-resolution (LR) images are randomly applied. and their (through-slice or iso) resolution is controlled here. It is defined as a proportion of the high-resolution voxel size (i.e., a resolution of 4 mean that the LR voxel size will be four times as large as the input voxel size) If a float, sampled form Uniform(0, value).

8
snr Sampler | float | {False}

The amount of noise added is encoded by the signal-to-noise ratio (SNR) of the noisy image (larger sampled values yield less noisy images). If a float, the value is a lower bound for SNR (no image will have a poorer SNR than this). The noise variance is then sampled from Uniform(0, 1/snr).

10
gfactor Sampler | int | {False}

The g-factor is a smooth field that locally scales the noise variance. The gfactor argument controls the smoothness of the g-factor field. If an int, sample from RandInt(2, value).

5
order 1..7

Spline order of the bias/g-factor fields (1 is much faster)

1..7
cc.SynthFromLabelTransform(...)
Synthesize an MRI from an existing label map.

cornucopia.synth.IntensityTransform

IntensityTransform(bias=7, bias_strength=0.5, gamma=0.6, motion_fwhm=3, resolution=8, snr=10, gfactor=5, order=3, **kwargs)

Bases: SequentialTransform

Common intensity augmentation for MRI and related images

The arguments control the range of the distributions from which the transform parameters are sampled.

It is also possible to directly provide the probability distribution from which to sample the parametes. In this case, it must be a Sampler instance.

Setting any argument to False disables the corresponding transform entirely.

Reference

Billot, B., Greve, D.N., Puonti, O., Thielscher, A., Van Leemput, K., Fischl, B., Dalca, A.V. and Iglesias, J.E., 2023. SynthSeg: Segmentation of brain MRI scans of any contrast and resolution without retraining. Medical image analysis, 86, p.102789.

@article{billot2023synthseg,
  title     = {SynthSeg: Segmentation of brain MRI scans of any contrast and resolution without retraining},
  author    = {Billot, Benjamin and Greve, Douglas N and Puonti, Oula and Thielscher, Axel and Van Leemput, Koen and Fischl, Bruce and Dalca, Adrian V and Iglesias, Juan Eugenio and others},
  journal   = {Medical image analysis},
  volume    = {86},
  pages     = {102789},
  year      = {2023},
  publisher = {Elsevier},
  url       = {https://www.sciencedirect.com/science/article/pii/S1361841523000506}
}

Parameters:

Name Type Description Default
bias Sampler | int | {False}

The sampled value controls the smoothness of the intensity bias field (smaller values yield smoother fields). If an int, sample from RandInt(2, value).

7
bias_strength Sampler | float in (0..1)

The maximum magnitude of the bias field (about 1). If a float, sample from Uniform(0, value). The minimum and maximum values of the bias field will be 1 - bias_strength and 1 + bias_strength.

0.5
gamma Sampler | float | {False}

The Gamma transform squeezes intensities such that the contrast to noise ratio is decreased (positive values lead to less decreased contrast, positive values lead to increased contrast). If a float, sample the gamma exponent from LogNormal(0, value).

0.6
motion_fwhm Sampler | float | {False}

A blur can be perform to model the point spread function or motion-related smearing. The amount of smoothing is encoded by the full-width at half-maximum (FWHM) of the underlying Gaussian kernel. If a float, sample the FWHM from Uniform(0, value).

3
resolution Sampler | float | {False}

Thick-slice or isotropic low-resolution (LR) images are randomly applied. and their (through-slice or iso) resolution is controlled here. It is defined as a proportion of the high-resolution voxel size (i.e., a resolution of 4 mean that the LR voxel size will be four times as large as the input voxel size) If a float, sampled form Uniform(0, value).

8
snr Sampler | float | {False}

The amount of noise added is encoded by the signal-to-noise ratio (SNR) of the noisy image (larger sampled values yield less noisy images). If a float, the value is a lower bound for SNR (no image will have a poorer SNR than this). The noise variance is then sampled from Uniform(0, 1/snr).

10
gfactor Sampler | int | {False}

The g-factor is a smooth field that locally scales the noise variance. The gfactor argument controls the smoothness of the g-factor field. If an int, sample from RandInt(2, value).

5
order 1..7

Spline order of the bias/g-factor fields (1 is much faster)

1..7