Transformations

Call a transform on an item with tfm(item). Use map(tfm, items) for a collection of independent samples. The Gallery shows what the spatial transformations look like, and the API reference documents each transform.

Composing transformations

Using transformations is easy. Simply compose them with |>:

tfm = Rotate(10) |> ScaleRatio((0.7,0.1,1.2)) |> FlipX() |> Crop((128, 128))
DataAugmentation.CroppedProjectiveTransform{DataAugmentation.ComposedProjectiveTransform{Tuple{DataAugmentation.RotateND{Distributions.Uniform{Float64}}, ScaleRatio{3}, DataAugmentation.FlipAxis}}, Tuple{Crop{2, DataAugmentation.FromOrigin}}}(DataAugmentation.ComposedProjectiveTransform{Tuple{DataAugmentation.RotateND{Distributions.Uniform{Float64}}, ScaleRatio{3}, DataAugmentation.FlipAxis}}((DataAugmentation.RotateND{Distributions.Uniform{Float64}}(Uniform(-10.0, 10.0), true, nothing), ScaleRatio{3}((0.7, 0.1, 1.2)), DataAugmentation.FlipAxis(:x))), (Crop{2, DataAugmentation.FromOrigin}((128, 128), DataAugmentation.FromOrigin(), (0, 0)),))

Projective transformations are fused into a single, more efficient transformation; the rest are applied one after the other.

Affine transformations

Affine transformations are a kind of projective transformation that can be composed very efficiently. They apply to Images and the keypoint-based items alike, in 2 and 3 dimensions.

  • FlipX(), FlipY() and FlipZ() flip along a named axis according to the item's dimensionality. Use FlipDim(dim) to specify the dimension directly.
  • Reflect(γ) reflects 2D data around its center by an angle chosen uniformly from [-γ, γ] degrees.
  • Rotate(γ) rotates 2D data around its center by an angle chosen uniformly from [-γ, γ] degrees, and 3D data around each of the three axes by angles chosen independently from [-γ, γ]. Use expand = false to keep the input bounds, center to choose a pivot, and fill for pixels outside the image. Rotate(α, β, γ) rotates 3D data with a range per axis, and RotateX, RotateY and RotateZ rotate around a single axis.
  • WarpAffine(σ) randomly moves a corner of the item and its neighbors along each axis, which is three corners of an image. This is similar to a random translation, shear and rotation, and works for any number of dimensions.
  • RandomAffine samples rotation, translation, scale and shear together. RandomPerspective moves the four corners inward, and ElasticTransform applies a smooth displacement field. These 2D warps keep the input bounds and share the same geometry across paired items.

Resizing

  • ScaleRatio(ratios) scales the sides by the given ratios, ScaleFixed(sizes) scales them to the given sizes disregarding the aspect ratio, and ScaleKeepAspect(minlengths) scales so that the sides are at least minlengths, keeping the aspect ratio. Each takes one value per dimension as a tuple, or a number for the same value along every dimension, so ScaleKeepAspect(256) scales the shortest side of an image or a volume to 256. Zoom(scales) zooms in by a factor chosen from the interval scales.
  • Resize(size; max_size) sets the shorter side and can cap the longer one. A size pair sets both dimensions directly. RandomShortestSize chooses a shorter side from a collection, RandomResize samples it from an interval, and ScaleJitter varies the scale around a target canvas size.

Construct an image with Image(data; antialias = true) to prefilter it before affine downsampling. Masks still use their own interpolation settings.

Crops and padding

To get a cropped result, simply compose any projective transformation with a crop:

  • CenterCrop(sz) and RandomCrop(sz) crop a region of size sz from the center or from a random location. They are special cases of Crop(sz, from). The size is a tuple with one size per dimension, or a number for the same size along every dimension: RandomCrop(32) crops a square from an image and a cube from a volume. Use padding to extend the input before choosing the window, and pad_if_needed = true to add room for randomly placing a window larger than the input.
  • CenterResizeCrop(sz) and RandomResizeCrop(sz) first scale the item with ScaleKeepAspect and then crop it from the center or from a random location, so that images of any size end up with the same size sz, a tuple or a number as for crops. The result is moved to the origin with PinOrigin().
  • RandomResizedCrop samples a window by area and aspect ratio, then resizes the window to the target size.
  • RandomIoUCrop takes an image and its bounding boxes together and uses their overlap with candidate windows to choose a crop. It applies that window to the image and any aligned annotations.
  • FiveCrop returns the four corners and center. TenCrop adds the same views of the flipped input.
  • Pad grows the bounds using a constant value, repeating edge pixels, or reflection. RandomZoomOut randomly places the input on a larger canvas using the same padding machinery.
  • ResizePadDivisible(sz, by) scales the item with ScaleKeepAspect and pads it so that its side lengths are divisible by by.

Keypoint bounds

After a crop or another geometric transformation, use ClampKeypoints to move coordinates into the item's index ranges, or SanitizeKeypoints to mark out-of-bounds points with NaN. Sanitizing preserves the index of each landmark, and showitems skips the marked points.

using DataAugmentation, StaticArrays

image = Image(zeros(10, 10))
points = Keypoints([SVector(1f0, 1f0), SVector(5f0, 5f0), SVector(10f0, 10f0)], (10, 10))
tfm = CenterCrop((4, 4)) |> PinOrigin() |> SanitizeKeypoints()
_, cropped_points = tfm((image, points))
itemdata(cropped_points)
3-element Vector{StaticArraysCore.SVector{2, Float32}}:
 [NaN, NaN]
 [2.0, 2.0]
 [NaN, NaN]

Bounding boxes

Pass the image and its BoundingBoxes collection together. After cropping, ClampBoundingBoxes clips partial boxes to the pixel edges of the resulting canvas. SanitizeBoundingBoxes removes boxes with no area and their labels. Sanitizing alone also removes partially out-of-bounds boxes.

using DataAugmentation

image = Image(zeros(8, 10))
boxes = BoundingBoxes([1 9; 2 7; 5 10; 5 8], (8, 10); labels = [:cat, :dog])
tfm = CenterCrop((4, 6)) |> PinOrigin() |> ClampBoundingBoxes() |> SanitizeBoundingBoxes()
_, cropped_boxes = tfm((image, boxes))
itemdata(cropped_boxes), cropped_boxes.labels
([0.5; 0.5; 3.0; 3.0;;], [:cat])

Use masks_to_boxes to turn binary instance masks into boxes and box_iou to compare two collections in the same coordinate system. See the object detection pipeline for an example with an overlap-based crop and labeled boxes.

Color transformations

Color transformations operate on Image items. You can apply them to an image together with its masks or keypoints in the same pipeline.

Policy-based augmentations

Policy-based augmentations draw random operations from a fixed set, such as shearing, translating, rotating, adjusting brightness, solarizing and equalizing, each with a strength from a table. They follow torchvision.transforms.v2, and apply to a 2D Image together with its masks and keypoints, which the geometric operations move along with it.

  • RandAugment(num_ops, magnitude) applies num_ops random operations of the same strength, and TrivialAugmentWide() applies a single operation with a random strength, without anything to tune.
  • AutoAugment(policy) applies one of the pairs of operations that the AutoAugment search found for :imagenet, :cifar10 or :svhn. You can also pass your own pairs.
  • AugMix() blends an image with several chains of random operations. Since the chains warp the image in different ways, it does not take masks or keypoints.
item = Image(testimage("lighthouse"))
tfm = RandAugment(2, 9)
titems = [tfm(item) for _ in 1:8]
showgrid(titems; ncol = 4, npad = 16)
Example block output

Erasing and batch mixing

RandomErasing fills a random rectangle in a 2D image, or a box in a volume, with a constant or with noise. Masks and keypoints passed alongside the image are preserved.

MixUp blends image pairs and their labels. CutMix copies a rectangle, or a box for volumes, from one image into another and weights the labels by the volume each image contributes. Both work on an ImageBatch after collation. The last image axis indexes samples, and each label column represents one sample.

using DataAugmentation, Images

samples = [Image(rand(RGB{Float32}, 24, 32)) for _ in 1:4]
sample_tfm = RandomErasing(value = :random) |> ImageToTensor()
images = stack(itemdata(sample_tfm(image)) for image in samples)

batch = ImageBatch(images, [1, 2, 3, 2]; num_classes = 3)
mix = CutMix()
mixed_images, mixed_labels = itemdata(mix(batch))
size(mixed_images), size(mixed_labels)
((32, 24, 3, 4), (3, 4))

Video

A video is an N-dimensional Image with time as the third dimension, so the spatial transformations apply to it directly. UniformTemporalSubsample(n) keeps n evenly spaced frames, and subsamples masks passed alongside the same way.

using DataAugmentation, Images

video = Image(rand(Gray{Float32}, 32, 32, 16))
tfm = UniformTemporalSubsample(8)
size(itemdata(tfm(video)))
(32, 32, 8)

Stochastic transformations

When augmenting data, it is often useful to apply a transformation only with some probability or choose from a set of transformations. Unlike in other data augmentation libraries like albumentations, in DataAugmentation.jl you can use wrapper transformations for this functionality.

  • Maybe(tfm, p = 0.5) applies a transformation with probability p;
  • OneOf([tfm1, tfm2]) randomly selects a transformation to apply; and
  • RandomOrder(tfm1, tfm2) applies all of them in a random order.

Let's say we have an image classification dataset. For most datasets, horizontally flipping the image does not change the label: a flipped image of a cat still shows a cat. So let's flip every image horizontally half of the time to improve the generalization of the model we might be training.

item = Image(testimage("lighthouse"))
tfm = Maybe(FlipX())
titems = [tfm(item) for _ in 1:8]
showgrid(titems; ncol = 4, npad = 16)
Example block output

Other transformations

Preprocessing covers the transformations that get data ready to be put into a model, such as normalization, whitening with LinearTransformation and one-hot encoding. Buffered wraps any transformation to reuse its output buffers; see Buffering.