API reference

Names that are not exported are listed with the DataAugmentation. prefix and need to be imported or qualified. The sections Extending and Testing cover the names used for defining your own items and transformations.

Jump to the symbol index.

Items

DataAugmentation.Image — Type
Image(image[, bounds]; interpolate=BSpline(Linear()), extrapolate=zero(T), antialias=false)

Item representing an N-dimensional image with element type T. Optionally, the interpolation and extrapolation method can be provided. Interpolation here refers to how the values of projected pixels that fall into the transformed content bounds are calculated. Extrapolation refers to how to assign values that fall outside the projected content bounds. The default is linear interpolation and to fill new regions with zero.

Set antialias = true to apply a box prefilter when an affine projection downsamples the image. The interpolation, extrapolation and antialiasing settings stay with the image through projective transforms.

Info

The Interpolations package provides numerous methods for use with the interpolate and extrapolate keyword arguments. For instance, BSpline(Linear()) and BSpline(Constant()) provide linear and nearest neighbor interpolation, respectively. In addition Flat(), Reflect() and Periodic() boundary conditions are available for extrapolation.

Examples

using DataAugmentation, Images

imagedata = rand(RGB, 100, 100)
item = Image(imagedata)
showitems(item)

If T is not a color, the image will be interpreted as grayscale:

imagedata = rand(Float32, 100, 100)
item = Image(imagedata)
showitems(item)
source
DataAugmentation.ImageBatch — Type
ImageBatch(images, labels)
ImageBatch(images, class_indices; num_classes)

An item for collated images and their classification labels. Use one-based real arrays of size (width, height, batch) for grayscale images or (width, height, channels, batch) for tensors collated after ImageToTensor. Volumes collated after ImageToTensor have size (width, height, depth, channels, batch): from four dimensions on, the last one is the batch, the one before it the channels, and all the dimensions before those are spatial. The label matrix has size (classes, batch) and holds one-hot or soft labels. The second constructor encodes class indices in 1:num_classes as Float32 one-hot columns. itemdata returns (images, labels).

source
DataAugmentation.MaskBinary — Type
MaskBinary(a; interpolate=BSpline(Constant()), extrapolate=Flat())

An N-dimensional binary mask. Optionally, the interpolation and extrapolation method can be provided. Interpolation here refers to how the values of projected pixels that fall into the transformed content bounds are calculated. Extrapolation refers to how to assign values that fall outside the projected content bounds. The default is nearest neighbor interpolation and flat extrapolation of the edges into new regions.

Info

The Interpolations package provides numerous methods for use with the interpolate and extrapolate keyword arguments. For instance, BSpline(Linear()) and BSpline(Constant()) provide linear and nearest neighbor interpolation, respectively. In addition Flat(), Reflect() and Periodic() boundary conditions are available for extrapolation.

Examples

using DataAugmentation

mask = MaskBinary(rand(Bool, 100, 100))
showitems(mask)
source
DataAugmentation.MaskMulti — Type
MaskMulti(a, [classes]; interpolate=BSpline(Constant()), extrapolate=Flat())

An N-dimensional multilabel mask with labels classes. Optionally, the interpolation and extrapolation method can be provided. Interpolation here refers to how the values of projected pixels that fall into the transformed content bounds are calculated. Extrapolation refers to how to assign values that fall outside the projected content bounds. The default is nearest neighbor interpolation and flat extrapolation of the edges into new regions.

Info

The Interpolations package provides numerous methods for use with the interpolate and extrapolate keyword arguments. For instance, BSpline(Linear()) and BSpline(Constant()) provide linear and nearest neighbor interpolation, respectively. In addition Flat(), Reflect() and Periodic() boundary conditions are available for extrapolation.

Examples

using DataAugmentation

mask = MaskMulti(rand(1:3, 100, 100))
showitems(mask)
source
DataAugmentation.Keypoints — Type
Keypoints(points, sz)
Keypoints{N, T, M}(points, bounds)

N-dimensional keypoints represented as SVector{N, T}.

Spatial bounds are given by the polygon bounds::Vector{SVector{N, T}} or sz::NTuple{N, Int}.

Examples

{cell=Keypoints}

using DataAugmentation, StaticArrays
points = [SVector(y, x) for (y, x) in zip(4:5:80, 10:6:90)]
item = Keypoints(points, (100, 100))

{cell=Keypoints}

showitems(item)
source
DataAugmentation.BoundingBox — Type
BoundingBox(points, sz)
BoundingBox{N, T, M}(points, bounds)

Item wrapper around Keypoints.

Examples

{cell=BoundingBox}

using DataAugmentation, StaticArrays
points = [SVector(10., 10.), SVector(80., 60.)]
item = BoundingBox(points, (100, 100))

{cell=BoundingBox}

showitems(item)
source
DataAugmentation.BoundingBoxes — Type
BoundingBoxes(data, bounds; format = :XYXY, labels = nothing)

A collection of axis-aligned boxes on a two-dimensional canvas. Pass a one-based 4 × N matrix of real coordinates with one box per column. Give the canvas as (height, width) or as Bounds with row and column ranges. Optional labels is a one-based vector with one entry per box.

The coordinate order is (x, y), with x along columns and y along rows. Pixel i is centered at coordinate i, so a canvas axis a:b spans the continuous interval [a - 0.5, b + 0.5]. Supported formats are:

  • :XYXY for (xmin, ymin, xmax, ymax)
  • :XYWH for (xmin, ymin, width, height)
  • :CXCYWH for (xcenter, ycenter, width, height)

Use itemdata for the coordinate matrix, boxes.format for its format, and boxes.labels for the labels. Geometric transforms enclose the four projected corners of each valid box and update the canvas. Use ClampBoundingBoxes and SanitizeBoundingBoxes to clip or remove boxes after a crop or warp.

source
DataAugmentation.Polygon — Type
Polygon(points, sz)
Polygon{N, T, M}(points, bounds)

Item wrapper around Keypoints.

Examples

{cell=Polygon}

using DataAugmentation, StaticArrays
points = [SVector(10., 10.), SVector(80., 20.), SVector(90., 70.), SVector(20., 90.)]
item = Polygon(points, (100, 100))

{cell=Polygon}

showitems(item)
source

Applying and composing transformations

DataAugmentation.apply! — Function
apply!(buffer::I, tfm, item::I)

Applies tfm to item, mutating the preallocated buffer.

buffer can be obtained with buffer = makebuffer(tfm, item)

apply!(buffer, tfm::Transform, item::I; randstate) = apply(tfm, item; randstate)

Default to apply(tfm, item) (non-mutating version).

source
DataAugmentation.compose — Function
compose(transforms...)

Compose tranformations. Use |> as an alias.

Defaults to creating a Sequence of transformations, but smarter behavior can be implemented. For example, MapElem(f) |> MapElem(g) == MapElem(g ∘ f).

source

Geometric warps

DataAugmentation.FlipDim — Type
FlipDim(dim)
FlipDim{N}(dim)

Reflect spatial data along the axis of dimension dim. FlipDim(dim) takes the dimensionality from the item and requires it to be at least dim. FlipDim{N}(dim) also checks that 1 <= dim <= N right away.

Examples

tfm = FlipDim(1)
source
DataAugmentation.FlipX — Type
FlipX()

Flip data along the x-axis. In 2D, the layout is (row, col) = (y, x), so this flips dimension 2. For other dimensionalities, it flips dimension 1.

The FlipX{N}() form is kept for compatibility and also uses the item's dimensionality.

source
DataAugmentation.FlipY — Type
FlipY()

Flip data along the y-axis. In 2D, the layout is (row, col) = (y, x), so this flips dimension 1. For three or more dimensions, it flips dimension 2.

The FlipY{N}() form is kept for compatibility and also uses the item's dimensionality.

source
DataAugmentation.FlipZ — Type
FlipZ()

Flip data along the z-axis (dimension 3). The item must have at least three dimensions.

The FlipZ{N}() form is kept for compatibility and also uses the item's dimensionality.

source
DataAugmentation.Reflect — Type
Reflect(γ)
Reflect(distribution)

Reflect 2D spatial data around the center by an angle chosen at uniformly from [-γ, γ], an angle given in degrees.

You can also pass any Distributions.Sampleable from which the angle is selected.

Examples

tfm = Reflect(10)
source
DataAugmentation.Rotate — Type
Rotate(γ; expand = true, center = nothing, fill = nothing)
Rotate(distribution; expand = true, center = nothing, fill = nothing)
Rotate(α, β, γ)
Rotate(α_distribution, β_distribution, γ_distribution)

Rotate spatial data around its center, by angles given in degrees. Rotate(γ) takes the dimensionality from the item. In 2D, it rotates by an angle chosen uniformly from [-γ, γ]. In 3D, it is the same as Rotate(γ, γ, γ): a rotation around each of the three axes, by angles chosen independently from [-γ, γ]. Use Rotate{2}(γ) or Rotate{3}(γ) to accept only 2D or 3D data.

Rotate(α, β, γ) is a 3D rotation by angles chosen uniformly from [-α, α], [-β, β], and [-γ, γ], for X, Y, and Z rotations.

You can also pass any Distributions.Sampleable from which the angle is selected.

expand = false keeps the input bounds. Pass an absolute center = (row, column) (or one coordinate per dimension in 3D) in pixel coordinates to rotate around another point. By default, out-of-bounds samples use the item's extrapolation setting. An explicit fill value applies to this rotation only and to Image items only; masks keep their own extrapolation. Rotations with a fill are not projective transforms and are not fused with neighboring ones.

Examples

tfm = Rotate(10)
tfm(Image(rand(Float32, 16, 16)))
tfm(Image(rand(Float32, 16, 16, 16)))

tfm3d = Rotate(10, 20, 30)
tfm3d(Image(rand(Float32, 16, 16, 16)))
source
DataAugmentation.RotateX — Function
RotateX(γ)
RotateX(distribution)

X-Axis rotation of 3D spatial data around the center by an angle chosen uniformly from [-γ, γ], an angle given in degrees.

You can also pass any Distributions.Sampleable from which the angle is selected.

source
DataAugmentation.RotateY — Function
RotateY(γ)
RotateY(distribution)

Y-Axis rotation of 3D spatial data around the center by an angle chosen uniformly from [-γ, γ], an angle given in degrees.

You can also pass any Distributions.Sampleable from which the angle is selected.

source
DataAugmentation.RotateZ — Function
RotateZ(γ)
RotateZ(distribution)

Z-Axis rotation of 3D spatial data around the center by an angle chosen uniformly from [-γ, γ], an angle given in degrees.

You can also pass any Distributions.Sampleable from which the angle is selected.

source
DataAugmentation.WarpAffine — Type
WarpAffine(σ = 0.1) <: ProjectiveTransform

An affine warp calculated by randomly moving N + 1 corners of an N-dimensional item, which is three corners of an image. Similar to a random translation, shear and rotation. The corners move by up to σ times the geometric mean of the side lengths.

source
DataAugmentation.RandomAffine — Type
RandomAffine(degrees; translate = (0, 0), scale = (1, 1), shear = 0)

Apply a random 2D affine warp on the original canvas. A scalar degrees samples a rotation symmetrically around zero; a pair gives the angle limits directly. translate gives maximum fractions of the height and width. Sample a uniform scale from the two limits in scale. A scalar shear samples horizontal shear symmetrically, a pair sets its limits, and four values give horizontal then vertical shear limits. Angles are in degrees.

source
DataAugmentation.RandomPerspective — Type
RandomPerspective(distortion_scale = 0.5; p = 0.5)

With probability p, warp a 2D canvas by moving its four corners inward. distortion_scale runs from zero to one and controls how far each corner can move along each axis. The output keeps the original canvas bounds.

source
DataAugmentation.ElasticTransform — Type
ElasticTransform(alpha, sigma = 5)
ElasticTransform(; alpha = 25, sigma = 5)

Apply a smooth random elastic deformation to 2D spatial data. alpha scales uniform noise in [-1, 1] that is smoothed with a Gaussian of scale sigma (in pixels); either may be a scalar or a (row, column) pair. The same deformation is used for images, masks, and keypoints.

The sampled field is reduced when necessary to keep its displacement map contractive, which makes the backward map used for image sampling well-defined and numerically invertible. This caps the deformation: for small sigma, increasing alpha beyond some point has no effect. Increase sigma to allow larger, smoother displacements.

source
DataAugmentation.Project — Type
Project(P)

Projective transformation that applies the fixed projection P, a CoordinateTransformations.Transformation, regardless of the item's bounds.

source
DataAugmentation.PinOrigin — Type
PinOrigin()

Projective transformation that translates the data so that the upper left bounding corner is at the origin (0, 0) (or the multidimensional equivalent).

Projective transformations on images return OffsetArrays, but not on keypoints. Hardware like GPUs do not support OffsetArrays, so they will be unwrapped and no longer match up with the keypoints.

Pinning the data to the origin makes sure that the resulting OffsetArray has the same indices as a regular array, starting at one.

source

Resizing

DataAugmentation.ScaleRatio — Type
ScaleRatio(ratios) <: ProjectiveTransform
ScaleRatio(ratio)

Scales the sides by ratios, one per dimension. A number ratio scales every dimension by the same factor, whatever the dimensionality of the item.

source
DataAugmentation.ScaleFixed — Type
ScaleFixed(sizes)
ScaleFixed(size)

Projective transformation that scales sides to sizes, disregarding aspect ratio. A number size is the same size for every dimension, whatever the dimensionality of the item.

See also ScaleKeepAspect.

source
DataAugmentation.ScaleKeepAspect — Type
ScaleKeepAspect(minlengths) <: ProjectiveTransform
ScaleKeepAspect(minlength)

Scales the sides of item to be as least as large as minlengths, keeping the original aspect ratio. A number minlength is the same minimum for every dimension, whatever the dimensionality of the item: the shortest side becomes minlength.

Examples

using DataAugmentation, TestImages
image = testimage("lighthouse")
tfm = ScaleKeepAspect((200, 200))
tfm(Image(image))
source
DataAugmentation.Zoom — Type
Zoom(scales = (1, 1.2)) <: ProjectiveTransform
Zoom(distribution)

Zoom into an item by a factor chosen from the interval scales or distribution.

source
DataAugmentation.Resize — Type
Resize(size; max_size = nothing)

An integer size sets the shorter side of 2D spatial data while preserving aspect ratio. max_size caps the longer side and may override size. Use Resize(nothing; max_size) to set the longer side, or provide a (height, width) tuple to set both sides explicitly.

source
DataAugmentation.ScaleJitter — Type
ScaleJitter(target_size; scale_range = (0.1, 2.0))

Randomly resize 2D spatial data while preserving aspect ratio. Multiply the scale needed to fit inside target_size = (height, width) by a uniform factor from scale_range.

source
DataAugmentation.RandomShortestSize — Type
RandomShortestSize(min_size; max_size = nothing)

Choose a shorter-side target from an integer or a collection of integers. Resize as in Resize, optionally capping the longer side at max_size.

source
DataAugmentation.RandomResize — Type
RandomResize(min_size, max_size)

Resize with aspect ratio preserved. Sample the shorter-side size uniformly from min_size up to but excluding max_size. Equal limits give a fixed size.

source

Crops and padding

DataAugmentation.Crop — Type
Crop(sz[, from]; padding = 0, pad_if_needed = false, fill = nothing, padding_mode = :constant)

Crop a region of size sz from the bounds of an item. from is FromOrigin() (default), FromCenter() or FromRandom(); see also CenterCrop and RandomCrop.

sz is a tuple with one size per dimension. An integer sz is the same size along every dimension, so that Crop(32, FromRandom()) crops a square from an image and a cube from a volume. An integer padding is the same for all dimensions, too; any other form of padding fixes the dimensionality.

With symmetric padding (one integer for all axes or one per axis), the bounds are extended on both sides before cropping. See Pad for asymmetric padding and the available padding modes. By default, padded pixels use the item's extrapolation setting, including when sz exceeds the bounds. With pad_if_needed = true, each side of an undersized axis is padded by the shortfall before choosing the crop. fill applies to Image items only; masks use their own extrapolation. With pad_if_needed, fill or a non-constant padding_mode, the result is a plain transform that is not fused with neighboring projective transforms.

Examples

tfm = Crop((32, 32), FromRandom(); padding = 4) |> PinOrigin()
tfm(Image(rand(RGB, 32, 32)))
source
DataAugmentation.CenterCrop — Function
CenterCrop(sz; padding = 0, kwargs...)

Crop a region of size sz from the center. Same as Crop(sz, FromCenter(); padding), see Crop. An integer sz is the same size along every dimension: a square crop of an image, a cube crop of a volume.

source
DataAugmentation.RandomCrop — Function
RandomCrop(sz; padding = 0, pad_if_needed = false, fill = nothing, padding_mode = :constant)

Crop a region of size sz from a random location. For example, RandomCrop((32, 32); padding = 4) pads a 32×32 image by 4 on each side and crops a random 32×32 window from the result. An integer sz is the same size along every dimension: RandomCrop(32) crops a square from an image and a cube from a volume. See Crop for padding behavior.

source
DataAugmentation.RandomResizedCrop — Type
RandomResizedCrop(size; scale = (0.08, 1.0), ratio = (0.75, 4/3), attempts = 10)

Sample a crop area as a fraction of the input area and sample the width-to-height ratio uniformly in log space. Resize the selected region to size (an integer or a (height, width) tuple). If no sampled crop fits, use a center crop with the closest allowed aspect ratio.

source
DataAugmentation.RandomIoUCrop — Type
RandomIoUCrop(; min_scale = 0.3, max_scale = 1, min_aspect_ratio = 0.5,
                max_aspect_ratio = 2, sampler_options = (0, 0.1, 0.3, 0.5, 0.7, 0.9, 1),
                trials = 40)

Crop a detection sample to a randomly selected 2D window. Apply to a tuple containing the image, its BoundingBoxes collection or individual BoundingBox items, and any aligned masks or keypoints. Individual boxes can also be grouped in a vector. A window is accepted if it contains the center of a box whose intersection over union with the window meets the sampled threshold.

Box corners are continuous coordinates in the pixel-center system, so a window of pixels a:b spans a - 0.5 to b + 0.5. Boxes with centers inside the crop are clipped to these edges. Other boxes are collapsed to zero area so that their positions and labels are preserved. Use SanitizeBoundingBoxes to remove collapsed boxes and their labels from a BoundingBoxes collection. A threshold of 1 keeps the full sample, as does running out of trials or applying the transform to a sample without boxes.

source
DataAugmentation.FiveCrop — Type
FiveCrop(size)

Return five views of 2D spatial data, in order from the top left, top right, bottom left, bottom right, and center. Pass an integer for a square crop or a (height, width) tuple. Each crop keeps its coordinates on the input canvas. For a tuple of items, each item produces its own tuple of views.

source
DataAugmentation.TenCrop — Type
TenCrop(size; vertical_flip = false)

Return the five views from FiveCrop, followed by the same five crops of the horizontally flipped input. Use vertical_flip = true to flip vertically.

source
DataAugmentation.Pad — Type
Pad(padding; fill = nothing, padding_mode = :constant)

Pad every side by an integer, or pass one integer per axis in array order. In 2D, a four-tuple specifies (left, top, right, bottom). For arbitrary dimensions, pairs (before, after) per axis also work.

Modes are :constant, :edge, :reflect (excluding the edge pixel), and :symmetric (including the edge pixel). With :constant, Image items are filled with fill, or with their extrapolation setting if fill = nothing. Masks always use their own extrapolation setting, so fill never injects labels they cannot hold. The input content keeps its coordinates while the bounds grow; use PinOrigin for one-based output coordinates.

source
DataAugmentation.RandomZoomOut — Type
RandomZoomOut(; fill = nothing, side_range = (1.0, 4.0), p = 0.5)

With probability p, place 2D spatial data at a random position within a larger canvas. Sample the canvas scale factor from side_range and fill the new pixels as in Pad.

source

Keypoint bounds

DataAugmentation.ClampKeypoints — Type
ClampKeypoints()

Clamp each coordinate of a Keypoints item to the first and last indices of its dimension. Use after a geometric transformation to move out-of-bounds coordinates onto the boundary. Each dimension with points to clamp must have a nonempty index range.

Accepts a tuple of aligned items, such as (image, keypoints), and targets its Keypoints entries.

source
DataAugmentation.SanitizeKeypoints — Type
SanitizeKeypoints()

Replace each out-of-bounds point in a Keypoints item with a point whose coordinates are all NaN. For a dimension with index range lo:hi, the coordinate is inside if lo <= coordinate < hi + 1.

The result preserves the shape and ordering of the keypoint array and uses floating-point coordinates. Accepts a tuple of aligned items, such as (image, keypoints), and targets its Keypoints entries.

source

Bounding boxes

DataAugmentation.box_convert — Function
box_convert(boxes::BoundingBoxes, format)

Convert the coordinates to :XYXY, :XYWH, or :CXCYWH, preserving the canvas, ordering, and labels. Coordinate arithmetic uses floating point.

source
DataAugmentation.ClampBoundingBoxes — Type
ClampBoundingBoxes()

Clip finite BoundingBoxes coordinates to the pixel edges of the canvas. Preserve the format, box count, and labels. Boxes fully outside the canvas collapse along at least one axis. Follow with SanitizeBoundingBoxes to remove boxes with zero area. Accepts a box collection or a tuple of items such as (image, boxes).

source
DataAugmentation.SanitizeBoundingBoxes — Type
SanitizeBoundingBoxes()

Remove any BoundingBoxes entry with nonfinite coordinates, nonpositive width or height, or any coordinate outside the canvas's pixel edges. Remove the corresponding labels in the same operation. Apply ClampBoundingBoxes first to keep the visible parts of partially out-of-bounds boxes. Accepts a box collection or a tuple of items such as (image, boxes).

source
DataAugmentation.masks_to_boxes — Function
masks_to_boxes(masks::AbstractArray{Bool, 3}; labels = nothing)
masks_to_boxes(mask::MaskBinary{2}; labels = nothing)

Build BoundingBoxes in :XYXY format from a (height, width, count) stack of instance masks or a single binary mask item. Each box encloses the full pixels marked true, so a one-pixel object has width and height 1. An empty mask yields a zero-area box at the canvas's upper-left edge so the box and label ordering is preserved. Spatial axes can be offset.

source
DataAugmentation.box_iou — Function
box_iou(a::BoundingBoxes, b::BoundingBoxes)

Return the pairwise intersection over union of two box collections in the same coordinate system. Entry (i, j) compares box i in a with box j in b. Pairs containing an invalid or degenerate box have IoU 0.

source

Color transformations

DataAugmentation.AdjustBrightness — Type
AdjustBrightness(δ = 0.2; clamp = true)
AdjustBrightness((min, max); clamp = true)
AdjustBrightness(distribution; clamp = true)

Multiply each image color channel by a factor sampled uniformly from [max(0, 1-δ), 1+δ], from the specified interval, or from a Distributions.Sampleable. Pixels are clamped to [0, 1] by default. Alpha, masks, and keypoints are preserved.

Example

using DataAugmentation, TestImages

item = Image(testimage("lighthouse"))
tfm = AdjustBrightness(0.2)
titems = [tfm(item) for _ in 1:8]
showgrid(titems; ncol = 4, npad = 16)
source
DataAugmentation.AdjustContrast — Type
AdjustContrast(δ = 0.2; clamp = true)
AdjustContrast((min, max); clamp = true)
AdjustContrast(distribution; clamp = true)

Transform each color c to c + μ*(1-f), where μ is the mean color of the image. Sample f uniformly from [max(0, 1-δ), 1+δ], from the specified interval, or from a Distributions.Sampleable. Pixels are clamped to [0, 1] by default. Alpha, masks, and keypoints are preserved.

Example

using DataAugmentation, TestImages

item = Image(testimage("lighthouse"))
tfm = AdjustContrast(0.2)
titems = [tfm(item) for _ in 1:8]
showgrid(titems; ncol = 4, npad = 16)
source
DataAugmentation.AdjustSaturation — Type
AdjustSaturation(δ = 0.2)
AdjustSaturation((min, max))
AdjustSaturation(distribution)

Blend each color with its grayscale luminance. A factor of zero gives grayscale and a factor of one preserves the color. The factor is sampled uniformly from [max(0, 1-δ), 1+δ], from the specified interval, or from a Distributions.Sampleable.

source
DataAugmentation.AdjustHue — Type
AdjustHue(δ = 0.1)
AdjustHue((min, max))
AdjustHue(distribution)

Shift the hue in HSV space by a sampled fraction of a turn. Sample uniformly from [-δ, δ], from the specified interval, or from a Distributions.Sampleable. Specify shifts between -0.5 and 0.5 using nonnegative RGB inputs.

source
DataAugmentation.ColorJitter — Type
ColorJitter(; brightness = 0.2, contrast = 0.2, saturation = 0.2, hue = 0.1)

Sample brightness, contrast, saturation, and hue adjustments independently and apply them in a uniformly random order. Each keyword accepts the same parameters as its respective adjustment transform. Set a keyword to 0 or nothing to skip that adjustment.

source
DataAugmentation.Grayscale — Type
Grayscale(num_output_channels = 1)

Convert the image to grayscale. With num_output_channels = 3, repeat the luminance in the three RGB channels. Preserve the channel precision and alpha.

source
DataAugmentation.RandomGrayscale — Type
RandomGrayscale(p = 0.1)

With probability p, turn colors into grayscale while keeping the original element type and alpha. In RGB, the three output channels all contain the luminance.

source
DataAugmentation.ToRGB — Type
ToRGB()

Convert an image to RGB, replicating grayscale values across the three channels. Preserve alpha when present.

source
DataAugmentation.GaussianBlur — Type
GaussianBlur(sigma = 1; kernel_size = 3)
GaussianBlur(sigma, kernel_size)

Apply a separable Gaussian blur to an image with any number of spatial dimensions. sigma is positive or a (min, max) pair of positive values to sample uniformly. kernel_size is an odd positive integer, the same for every dimension, or a tuple of odd positive sizes in array axis order, one per dimension. The filter reflects the image at its edges.

source
DataAugmentation.GaussianNoise — Type
GaussianNoise(sigma = 0.1; mean = 0, clamp = true)

Add independent Gaussian noise with the given mean and standard deviation sigma to each color channel. Supply a (min, max) pair to sample sigma uniformly. Pixels are clamped to [0, 1] by default. The random state holds the sampled sigma and a seed so it can be replayed across images.

source
DataAugmentation.AdjustSharpness — Type
AdjustSharpness(factor = 1)

Blend an image with a weighted smoothing filter over the 3×3 neighborhood of each pixel, or over its 3×3×3 neighborhood in 3D, and so on for other numbers of spatial dimensions. The center has weight 5 and every other pixel of the neighborhood weight 1. factor = 0 gives the smoothed image, factor = 1 preserves the input, and larger values sharpen it. The one-pixel border is preserved.

source
DataAugmentation.AdjustGamma — Type
AdjustGamma(gamma; gain = 1, clamp = true)

Apply gain * x^gamma independently to image channels. Pixels are clamped to [0, 1] by default.

source
DataAugmentation.Posterize — Type
Posterize(bits=4)

Quantize unit-range channels to 8 bits, then keep the bits most significant bits and set the other bits to zero.

source
DataAugmentation.Equalize — Type
Equalize()

Equalize each image channel using a 256-bin histogram over [0, 1]. Channels whose values all fall in one bin are preserved.

source
DataAugmentation.RandomPhotometricDistort — Type
RandomPhotometricDistort(; brightness = (0.875, 1.125), contrast = (0.5, 1.5),
                          saturation = (0.5, 1.5), hue = (-0.05, 0.05), p = 0.5)

Apply brightness, saturation and hue adjustments with factors sampled from the given ranges. Apply contrast randomly before or after the saturation and hue adjustments, then permute the RGB channels. Each of the five operations is selected independently with probability p. Hue is measured in turns.

source
DataAugmentation.RandomChannelPermutation — Type
RandomChannelPermutation()

Uniformly permute the three RGB channels. Other color spaces are converted to RGB for the permutation and converted back afterward. Grayscale and alpha are preserved.

source
DataAugmentation.JPEG — Type
JPEG(quality = 75)
JPEG((min_quality, max_quality))
JPEG(min_quality:max_quality)

Compress and decompress a two-dimensional image in memory using JPEG. Quality is an integer from 1 to 100, or an inclusive range of qualities to sample uniformly. Lower quality produces stronger compression. Pixel intensities are clamped to [0, 1] and quantized to 8 bits for the codec, then converted back to the original element type with alpha preserved.

Load JpegTurbo with using JpegTurbo before applying this transform.

source

Policy-based augmentations

DataAugmentation.RandAugment — Type
RandAugment(num_ops = 2, magnitude = 9; num_magnitude_bins = 31, fill = nothing)

Apply num_ops operations drawn uniformly at random from a fixed set, each with the same strength, as in RandAugment. magnitude selects the strength as an index in 0:num_magnitude_bins-1 into the table of each operation, from the identity to the strongest value.

The operations are Identity, shearing and translating along each axis, rotation, brightness, color (saturation), contrast and sharpness adjustments, posterization, solarization, AutoContrast (Autocontrast) and Equalize. Signed operations are applied in either direction with equal probability. Shears are given as the shear factor, translations as up to 150/331 of the side length, and rotations up to 30 degrees. The tables are those of torchvision.transforms.v2.RandAugment.

The input is an Image with two spatial dimensions, with its masks and keypoints passed alongside. Like the color transformations it uses, it expects pixel values in [0, 1]. The same operations apply to all items: the geometric ones to every item and the others to the image alone. The interpolation and extrapolation of each item are used as given: images interpolate linearly by default, where torchvision uses nearest neighbor, which Image(data; interpolate = BSpline(Constant())) gives. A fill value, a number or color, replaces the extrapolation of the image for the geometric operations.

See also TrivialAugmentWide, AutoAugment.

Example

using DataAugmentation, TestImages

item = Image(testimage("lighthouse"))
tfm = RandAugment(2, 9)
titems = [apply(tfm, item) for _ in 1:8]
showgrid(titems; ncol = 4, npad = 16)
source
DataAugmentation.TrivialAugmentWide — Type
TrivialAugmentWide(; num_magnitude_bins = 31, fill = nothing)

Apply one operation drawn uniformly at random, with a magnitude drawn uniformly at random from its table, as in TrivialAugment (the wide variant).

The operations are those of RandAugment, with wider ranges: shear factors up to 0.99, translations up to 32 pixels, rotations up to 135 degrees, and enhancement factors down to 0.01 and up to 1.99. The tables are those of torchvision.transforms.v2.TrivialAugmentWide. Items, interpolation and fill work as for RandAugment.

Example

using DataAugmentation, TestImages

item = Image(testimage("lighthouse"))
tfm = TrivialAugmentWide()
titems = [apply(tfm, item) for _ in 1:8]
showgrid(titems; ncol = 4, npad = 16)
source
DataAugmentation.AutoAugment — Type
AutoAugment(policy = :imagenet; fill = nothing)
AutoAugment(subpolicies; fill = nothing)

Apply a sub-policy drawn uniformly at random from a policy learned by AutoAugment. A sub-policy is a pair of operations, each applied with its own probability and with a fixed magnitude and a random sign.

policy is :imagenet, :cifar10 or :svhn, the policies of torchvision.transforms.v2.AutoAugment. You can also pass your own subpolicies, a collection of sub-policies, each a collection of operations (name, probability, magnitude). The names are :ShearX, :ShearY, :TranslateX, :TranslateY, :Rotate, :Brightness, :Color, :Contrast, :Sharpness, :Posterize, :Solarize, :AutoContrast, :Equalize and :Invert. The magnitude is an index in 0:9 into the table of the operation, and nothing for the last three. The tables are those of RandAugment, with ten bins.

Items, interpolation and fill work as for RandAugment.

Example

using DataAugmentation, TestImages

item = Image(testimage("lighthouse"))
tfm = AutoAugment(:cifar10)
titems = [apply(tfm, item) for _ in 1:8]
showgrid(titems; ncol = 4, npad = 16)

custom = AutoAugment([((:Rotate, 0.8, 5), (:Equalize, 0.5, nothing))])
source
DataAugmentation.AugMix — Type
AugMix(; severity = 3, mixture_width = 3, chain_depth = -1, alpha = 1,
         all_ops = true, fill = nothing)

Mix an image with augmented versions of itself, as in AugMix. It draws mixture_width chains of random operations, each of chain_depth operations or, for a negative chain_depth, of one to three. The result is a convex combination of the image and the chains, with weights from a Dirichlet distribution and a Beta distribution with parameter alpha.

Operations draw their magnitude from the severity weakest entries of their tables, with severity in 1:10. The operations are shearing and translating along each axis, rotation, posterization, solarization, Autocontrast and Equalize, plus adjustments of brightness, color (saturation), contrast and sharpness with all_ops = true. The tables are those of torchvision.transforms.v2.AugMix: translations up to a third of the side length. The exception is posterization at the two strongest magnitudes, which would keep no bits at all, and keeps one bit here.

AugMix takes an Image with two spatial dimensions and only that. Masks and keypoints are rejected since the chains warp the image differently, so they can't be mixed. The interpolation and extrapolation of the image are used as given. A fill value, a number or color, replaces its extrapolation for the geometric operations. Pixels are returned in the element type of the image.

Example

using DataAugmentation, TestImages

item = Image(testimage("lighthouse"))
tfm = AugMix(severity = 5)
titems = [apply(tfm, item) for _ in 1:8]
showgrid(titems; ncol = 4, npad = 16)
source

Erasing and batch mixing

DataAugmentation.RandomErasing — Type
RandomErasing(; p = 0.5, scale = (0.02, 0.33), ratio = (0.3, 3.3), value = 0)

With probability p, erase a random box in an Image with any number of spatial dimensions, a rectangle in 2D. Sample its volume fraction uniformly from scale ⊆ (0, 1]. Sample the ratio of each side to the last one, except for the last one, log-uniformly and independently from ratio; in 2D, this is the height-to-width ratio. If no box fits after ten attempts, leave the image pixels unchanged.

Fill the box with a real number or color converted to the pixel type. With value = :random, draw each color channel uniformly between zero and one before conversion, preserving alpha. Machine integer pixels use their full range. Masks and keypoints passed alongside the image are unchanged.

source
DataAugmentation.MixUp — Type
MixUp(alpha)
MixUp(; alpha = 1)

Blend each image in an ImageBatch with its partner in a random permutation of the batch. The images and their label columns use the same weight, drawn from Beta(alpha, alpha) with positive finite alpha. Images and labels are returned as floating-point arrays.

source
DataAugmentation.CutMix — Type
CutMix(alpha)
CutMix(; alpha = 1)

Copy a shared random box into each image in an ImageBatch from its partner in a random permutation of the batch. The box spans the spatial dimensions of the images: a rectangle for images, a cuboid for volumes. The target volume fraction is drawn from Beta(alpha, alpha) with positive finite alpha. The label weight uses the fraction of pixels actually replaced after rounding and clipping the box. Images keep their element type and labels are returned as floats.

source

Video

DataAugmentation.UniformTemporalSubsample — Type
UniformTemporalSubsample(num_samples; dim = 3)

Keep num_samples frames of a video, evenly spaced along its temporal dimension dim. Frame i of the result is frame 1 + fld((i - 1) * (T - 1), num_samples - 1) of the input, for T input frames. The first and last frame are always kept, and a single sample is the first frame. If num_samples exceeds T, frames repeat, picking the nearest preceding one.

Videos are N-dimensional items with the temporal dimension next to the spatial ones, so the default dim = 3 fits an Image{3} of size (height, width, time) as well as the (width, height, time, channels) tensor that ImageToTensor makes from it. It applies to ArrayItems, Images, MaskMultis and MaskBinarys, which are subsampled with the same frames when passed together. The bounds of the result are those of its new axes.

Supports apply!.

Examples

using DataAugmentation, Images

video = Image(rand(RGB{N0f8}, 32, 32, 16))
tfm = UniformTemporalSubsample(8)
tfm(video)  # Image{3, RGB{N0f8}} with 8 frames
source

Stochastic transformations

DataAugmentation.OneOf — Type
OneOf(tfms)
OneOf(tfms, ps)

Apply one of tfms selected randomly with probability ps each or uniformly chosen if no ps is given.

source
DataAugmentation.RandomOrder — Type
RandomOrder(tfms)
RandomOrder(tfms...)

Apply all of the transformations tfms, a vector, tuple or list of arguments, in a random order. Each call draws a new permutation, and applies the same one to all items of a tuple. The order changes the shape of the buffers in between, so Buffered does not reuse any for it.

See also OneOf to apply a single randomly selected transformation.

Examples

tfm = RandomOrder(AdjustBrightness(0.2), GaussianBlur(1), FlipX())
source

Buffering

DataAugmentation.Buffered — Type
Buffered(tfm; copy = false)

Wrapper transformation that applies tfm with apply!, reusing buffers that are created the first time the wrapper is applied (one set of buffers per item type).

By default the returned item is the final buffer itself, so the next call can overwrite it. This is a problem for code that keeps several results alive at the same time, like a data loader that collates a batch after loading all its samples (e.g. DataLoader(...; collate = true) from MLUtils.jl). With copy = true the buffers are still reused internally, but the returned item is a fresh copy that the caller owns.

Only one set of buffers is kept, so don't share a Buffered between threads; use BufferedThreadsafe instead.

source
DataAugmentation.BufferedThreadsafe — Type
BufferedThreadsafe(tfm; n = Threads.nthreads())

Like Buffered, but can be applied from multiple threads and tasks at the same time. Each concurrent call checks out its own buffers from a pool that grows on demand (n is the number of buffer sets created upfront) and returns them when done.

Since the buffers go back to the pool, calling the wrapper returns a copy that the caller owns. It is safe to keep several results alive at once. apply!(buf, btfm, item) writes the result into buf.

source

Preprocessing

DataAugmentation.ToEltype — Type
ToEltype(T)

Converts any AbstractArrayItem to an AbstractArrayItem{N, T}.

Supports apply!.

Examples

{cell=ToEltype}

using DataAugmentation

tfm = ToEltype(Float32)
item = ArrayItem(rand(Int, 10))
tfm(item)
source
DataAugmentation.ImageToTensor — Type
ImageToTensor()

Expands an Image{N, T} of size (height, width, ...) to an ArrayItem{N+1} with size (width, height, ..., ch) where ch is the number of color channels of T.

Supports apply!.

Examples

{cell=ImageToTensor}

using DataAugmentation, Images

h, w = 40, 50
image = Image(rand(RGB, h, w))
tfm = ImageToTensor()
tfm(image) # ArrayItem in WHC format of size (50, 40, 3)
source
DataAugmentation.PermuteDims — Type
PermuteDims(perm)

Permute the dimensions of an ArrayItem. perm is a vector or a tuple specifying the permutation, whose length has to match the dimensionality of the ArrayItems data.

Refer to the permutedims documentation for examples of permutation vectors perm.

Supports apply!.

Examples

Preprocessing an image with 3 color channels.

{cell=PermuteDims}

using DataAugmentation, Images
image = Image(rand(RGB, 20, 20))

# Turn image to a WHC (width, height, channel) tensor and permute dimensions 2 and 1
# to convert it to an HWC (height, width, channel) array
tfms = ImageToTensor() |> PermuteDims(2, 1, 3)
tfms(image)
source
DataAugmentation.Normalize — Type
Normalize(means, stds)

Normalizes the last dimension of an AbstractArrayItem{N}.

Supports apply!.

Examples

Preprocessing a 3D image with 3 color channels.

{cell=Normalize}

using DataAugmentation, Images
image = Image(rand(RGB, 20, 20, 20))
tfms = ImageToTensor() |> Normalize((0.1, -0.2, -0.1), (1,1,1.))
tfms(image)
source
DataAugmentation.LinearTransformation — Type
LinearTransformation(matrix; mean = zeros(eltype(matrix), size(matrix, 1)))

Flattens an ArrayItem of length D, subtracts mean, multiplies the result by the D × D matrix and restores the original size, i.e. matrix * (vec(x) - mean). Use it for whitening with a matrix computed offline from a dataset.

The result has the promoted element type of the data, matrix and mean. This is the transformation of torchvision's LinearTransformation for a symmetric matrix, such as the ZCA whitening matrix; torchvision multiplies the row vector from the right, so pass the transpose of a non-symmetric torchvision matrix.

Supports apply!.

Examples

ZCA whitening of 4×4 single-channel samples:

using DataAugmentation, LinearAlgebra, Statistics

samples = randn(Float32, 16, 1000)
μ = vec(mean(samples; dims = 2))
eig = eigen(Symmetric(cov(samples; dims = 2)))
W = eig.vectors * Diagonal(1 ./ sqrt.(eig.values .+ 1f-5)) * eig.vectors'

tfm = LinearTransformation(W; mean = μ)
tfm(ArrayItem(randn(Float32, 4, 4)))
source
DataAugmentation.OneHot — Type
OneHot([T = Float32])

One-hot encodes a MaskMulti with n classes and size sz into an array item of size (sz..., n) with element type T. Supports apply!.

item = MaskMulti(rand(1:4, 100, 100), 1:4)
tfm = OneHot()
tfm(item)
source
DataAugmentation.onehot — Function
onehot([T = Float32], x, n)

One-hot encode the class index x in 1:n as a vector of length n with element type T.

source

Tabular data

DataAugmentation.FillMissing — Type
FillMissing(dict, cols)

Fills the missing values of a row present in TabularItem for the columns specified in cols using dict, which contains the column names as dictionary keys and the value to fill the column with present as dictionary values.

Example

using DataAugmentation

cols = [:col1, :col2, :col3]
row = (; zip(cols, [1, 2, 3])...)
item = TabularItem(row, cols)
fmdict = Dict(:col1 => 100, :col2 => 100)

tfm = FillMissing(fmdict, [:col1, :col2])
tfm(item)
source
DataAugmentation.Categorify — Type
Categorify(dict, cols)

Label encodes the values of a row present in TabularItem for the columns specified in cols using dict, which contains the column names as dictionary keys and the unique values of column present as dictionary values.

if there are any missing values in the values to be transformed, they are replaced by 1.

Example

using DataAugmentation

cols = [:col1, :col2, :col3]
row = (; zip(cols, ["cat", 2, 3])...)
item = TabularItem(row, cols)
catdict = Dict(:col1 => ["dog", "cat"])

tfm = Categorify(catdict, [:col1])
tfm(item)
source
DataAugmentation.NormalizeRow — Type
NormalizeRow(dict, cols)

Normalizes the values of a row present in TabularItem for the columns specified in cols using dict, which contains the column names as dictionary keys and the mean and standard deviation tuple present as dictionary values.

Example

using DataAugmentation

cols = [:col1, :col2, :col3]
row = (; zip(cols, [1, 2, 3])...)
item = TabularItem(row, cols)
normdict = Dict(:col1 => (1, 1), :col2 => (2, 2))

tfm = NormalizeRow(normdict, [:col1, :col2])
tfm(item)
source

Visualization

DataAugmentation.showitems — Function
showitems(items; C = RGBA{N0f8}, showbounds = false, maskalpha = 0.5,
          maskbackground = nothing)

Draw a single spatial item or a collection of items in the given order. Masks drawn after an Image are blended over the canvas with opacity maskalpha, a number between 0 and 1. Set maskbackground to a class label to leave the canvas visible at those pixels. For a binary mask, use false for the background. By default, all mask labels are drawn. A mask drawn on its own is opaque.

source
DataAugmentation.showgrid — Function
showgrid(itemgroups; fillvalue = RGBA{N0f8}(0, 0, 0, 0), maskalpha = 0.5,
         maskbackground = nothing, kwargs...)

Visualize every element of itemgroups (an item or a tuple of items) with showitems, which receives maskalpha and maskbackground. The results are arranged in a grid with MosaicViews.mosaicview, which receives fillvalue and grid options such as ncol and npad.

source

Extending

Items

DataAugmentation.setdata — Function

Provides a convenient way to create a copy of an item, replacing only the wrapped data. This relies on the wrapped data field being named data, though.

source

Transformations

DataAugmentation.getrandstate — Function
getrandstate(transform)

Generate random state for stochastic transformations. Calling tfm(item) is equivalent to tfm(item; randstate = getrandstate(tfm)). The default state is nothing.

source

Return random state of the transform

source
DataAugmentation.makebuffer — Function
makebuffer(tfm, item)

Create a buffer buf that can be used in a call to apply!(buf, tfm, item). Default to buffer = apply(tfm, item).

You only need to implement this if the default apply(tfm, item) isn't enough. See apply(tfm::Sequence, item) for an example of this.

source

Projective transformations

DataAugmentation.ComposedProjectiveTransform — Type
ComposedProjectiveTransform(tfms...)

Wrap multiple projective tfms and apply them efficiently. The projections are fused into a single projection and only points inside the final crop are evaluated.

source
DataAugmentation.getbounds — Function
getbounds(item)

Return the spatial bounds of item. For a 2D-image (Image{2}) the bounds are the 4 corners of the bounding rectangle. In general, for an N-dimensional item, the bounds are a vector of the N^2 corners of the N-dimensional hypercube bounding the data.

source
DataAugmentation.project! — Function
project!(bufitem, P, item, indices)

Project item using projection P and crop to indices if given. Store result in bufitem. Inplace version of project.

Default implementation falls back to project.

source
DataAugmentation.Bounds — Type
Bounds(sz)
Bounds(rs)

Spatial bounds of an N-dimensional item, stored as one index range per dimension. Bounds(sz) for a size tuple sz gives the ranges 1:sz[i]; rs is a tuple of ranges.

source
DataAugmentation.offsetcropbounds — Function
offsetcropbounds(sz, bounds, offsets)

Calculate offset bounds for a crop of size sz.

For every dimension i where sz[i] < length(indices[i]), offsets the crop by offsets[i] times the difference between the two.

source

Testing

DataAugmentation.testapply — Function
testapply(tfm, item)
testapply(tfm, I)

Test apply invariants of tfm on item or item type I.

  1. With a constant randstate parameter, apply should always return the same result.
source
DataAugmentation.testapply! — Function
testapply!(tfm, Items)
testapply!(tfm, Item)
testapply!(tfm, item1, item2)

Test apply! invariants.

  1. With a constant randstate parameter, apply! should always return the same result.
  2. Given a different item than was used to create the buffer, the buffer's data should be modified.
source
DataAugmentation.testitem — Function
testitem(TItem)

Create an instance of an item with type TItem. If it has spatial bounds, should return an instance with bounds with ranges (1:16, 1:16).

source
DataAugmentation.testprojective — Function
testprojective(tfm)

Test invariants of a ProjectiveTransform.

  1. getprojection is defined, and, given a constant randstate parameter, always returns the same result.
  2. It preserves the item type, i.e. apply(tfm, ::I) -> I.
  3. Applying it to multiple items with the same bounds results in the same bounds for all items.
source

Index