Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 32 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,47 @@
[![Coverage](https://codecov.io/gh/FluxML/DataAugmentation.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/FluxML/DataAugmentation.jl)
[![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl)

Efficient, composable data augmentation for machine and deep learning with support for n-dimensional images, keypoints and categorical masks.
Compose data augmentation pipelines for image classification, segmentation, object detection, and 3D volumes in Julia.

## Installation
![A lighthouse photo followed by a flipped, rotated crop and a color-jittered version](assets/readme/transforms.png)

## Quickstart

Install the registered package and the sample images used below.

```julia
using Pkg
Pkg.add("DataAugmentation")
Pkg.add(["DataAugmentation", "TestImages"])
```

## Example
Compose a random rotation and crop with `|>`. Use `itemdata` to get the resulting pixel array.

```julia
using DataAugmentation, TestImages

item = Image(testimage("lighthouse"))
tfm = Maybe(FlipX()) |> RandomResizeCrop((128, 128))
timage = itemdata(tfm(item))
image = Image(testimage("lighthouse"))
tfm = Rotate(15) |> RandomResizeCrop((192, 256))
pixels = itemdata(apply(tfm, image))
```

See the [documentation](https://fluxml.ai/DataAugmentation.jl/stable/) for the available transformations and how to define your own.
## Feature showcase

The showcase uses the development branch. Install it with `Pkg.add(name = "DataAugmentation", rev = "master")`.

### Keep annotations aligned

Pass aligned items as a tuple with `tfm((image, mask, boxes))` to share the random geometry. Here `FlipX` and `RandomIoUCrop` move the segmentation mask and labeled boxes with the image.

![Before and after a shared flip and crop, with masks and bounding boxes aligned to the lighthouse and the house](assets/readme/aligned-annotations.png)

### Mix images and labels

`MixUp` blends paired images. `CutMix` copies a rectangular patch from one image into another. Both return an `ImageBatch` with class weights that reflect the mix.

![A cat and a cup of coffee as source images, a MixUp blend with 55% cat and 45% coffee, and a CutMix sample with 65% cat and 35% coffee](assets/readme/batch-mixing.png)

## Documentation

- Browse crops, warps, color transforms, and policies such as `RandAugment` and `AutoAugment`. [Transformations](https://fluxml.ai/DataAugmentation.jl/dev/transformations/)
- Run complete examples for masks, keypoints, boxes, and volumes. [Pipelines](docs/src/pipelines.md)
- Prepare image tensors, load batches, and train a model. [Using with Flux](docs/src/flux.md)
Binary file added assets/readme/aligned-annotations.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/readme/batch-mixing.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/readme/transforms.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions docs/Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4"
ImageShow = "4e3cecfd-b093-5904-9786-8bbb286a6a31"
Images = "916415d5-f1e6-5110-898d-aaa5f9f070e0"
Interpolations = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59"
MLUtils = "f1d291b0-491e-4a28-83b9-f70985020b54"
MosaicViews = "e94cdb99-869f-56ef-bcf0-1ae2bcbe0389"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
TestImages = "5e47fb64-e119-507b-a336-dd2b206d9990"
Expand All @@ -16,5 +17,6 @@ Documenter = "1.3"
ImageShow = "0.3.8"
Images = "0.26.2"
Interpolations = "0.16.3"
MLUtils = "0.4"
MosaicViews = "0.3.4"
TestImages = "1.9.0"
2 changes: 2 additions & 0 deletions docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ makedocs(;
"Items" => "items.md",
"Transformations" => "transformations.md",
"Gallery" => "gallery.md",
"Pipelines" => "pipelines.md",
"Preprocessing" => "preprocessing.md",
"Using with Flux" => "flux.md",
"Buffering" => "buffering.md",
],
"Concepts" => [
Expand Down
142 changes: 142 additions & 0 deletions docs/src/flux.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# Using with Flux

Use DataAugmentation.jl to transform each sample and the `DataLoader` shared by Flux and [MLUtils.jl](https://github.com/JuliaML/MLUtils.jl) to load, shuffle, and batch samples.

This example builds a per-sample transform and loads augmented batches in the background for a Flux training loop.

## Array layout

Flux's 2D convolutions expect arrays in `(width, height, channels, batch)` order. [`ImageToTensor`](@ref) converts a `(height, width)` array of colors to a `Float32` tensor with shape `(width, height, channels)`. The data loader adds the batch axis when it stacks samples.

## A transformation for each sample

For CIFAR-10, a common pipeline randomly flips the image, pads it by four pixels, and crops a window of the original size. The `padding` keyword of [`RandomCrop`](@ref) extends the canvas, using black pixels by default for images.

```@example flux
using DataAugmentation, Images, MLUtils

means, stds = (0.5, 0.5, 0.5), (0.25, 0.25, 0.25)

train_tfm = Maybe(FlipX()) |> RandomCrop(32; padding = 4) |> PinOrigin() |>
ImageToTensor() |> Normalize(means, stds)
test_tfm = ImageToTensor() |> Normalize(means, stds)

augment(tfm, image) = itemdata(tfm(Image(image)))
```

For a preset CIFAR-10 augmentation policy, compose [`AutoAugment`](@ref)`(:cifar10)` with the preprocessing in `test_tfm`. For evaluation, call `test_tfm` on its own.

The example uses random images and labels. The images stay in memory as 8-bit colors, a quarter of the size of `Float32` colors. [`ImageToTensor`](@ref) converts one sample at a time.

```@example flux
images = [rand(RGB{N0f8}, 32, 32) for _ in 1:64]
labels = rand(1:10, 64)

x = augment(train_tfm, images[1])
size(x), eltype(x)
```

!!! warning "End crops with `PinOrigin`"

A plain crop can leave offset axes tied to the crop location. Batching requires matching axes across samples. Add [`PinOrigin`](@ref)`()` after [`Crop`](@ref), [`CenterCrop`](@ref), or [`RandomCrop`](@ref) to make the axes one-based before preprocessing. [`RandomResizedCrop`](@ref), [`RandomResizeCrop`](@ref), and [`CenterResizeCrop`](@ref) already return one-based axes.

## A data loader

[`mapobs`](https://juliaml.github.io/MLUtils.jl/stable/api/#MLUtils.mapobs) applies a function lazily to each `(image, label)` pair in `(images, labels)`. The function runs each time the loader requests an observation, so every epoch draws fresh transformations.

- `collate = true` loads each observation individually and stacks the image tensors along a new last dimension.
- `parallel = true` loads batches with worker tasks while the model works on the current batch. Start Julia with multiple threads, for example with `julia -t auto`. Batches can arrive out of order.
- `partial = false` drops a short final batch to keep the batch size fixed.

```@example flux
train_data = mapobs(((image, label),) -> (augment(train_tfm, image), label), (images, labels))
train_loader = DataLoader(train_data; batchsize = 16, shuffle = true, collate = true,
partial = false, parallel = true)

x, y = first(train_loader)
size(x), size(y)
```

The test loader iterates over all samples with shuffling disabled.

```@example flux
test_data = mapobs(((image, label),) -> (augment(test_tfm, image), label), (images, labels))
test_loader = DataLoader(test_data; batchsize = 16, collate = true, parallel = true)
```

Without MLUtils, a comprehension and `stack` do the same for a single batch: `stack([augment(train_tfm, image) for image in images[1:16]])`.

!!! warning "Buffered transformations in a data loader"

[`Buffered`](@ref) returns a reusable output buffer by default. Later calls can overwrite samples before the loader collates them. [`BufferedThreadsafe`](@ref) uses a separate set of buffers for each concurrent call and returns a copy. See [Buffering](buffering.md).

## Mixing samples of a batch

[`MixUp`](@ref) and [`CutMix`](@ref) combine pairs of samples and their labels within a batch. Wrap a batch from the loader in an [`ImageBatch`](@ref) with the number of classes to encode labels as one-hot columns. [`OneOf`](@ref) selects a mixing transform for each batch.

```@example flux
mix = OneOf([MixUp(), CutMix()])

x, y = first(train_loader)
xmix, ymix = itemdata(mix(ImageBatch(x, y; num_classes = 10)))
size(xmix), size(ymix)
```

Each column of the mixed label matrix contains class weights for one sample.

## Training

This example uses the `Float32` batches in a Flux training loop. Select the device once and move the model to it. Mix each batch on the CPU before transferring it to the device. `gpu_device()` selects the CPU when a GPU backend is unavailable.

```julia
using Flux

device = gpu_device()

model = device(Chain(
Conv((3, 3), 3 => 16, relu; pad = 1), MaxPool((2, 2)),
Conv((3, 3), 16 => 32, relu; pad = 1), GlobalMeanPool(), Flux.flatten,
Dense(32 => 10),
))
opt_state = Flux.setup(Adam(1e-3), model)

for epoch in 1:10
for (x, y) in train_loader
x, y = itemdata(mix(ImageBatch(x, y; num_classes = 10)))
x, y = device(x), device(y)
loss, grads = Flux.withgradient(model) do m
Flux.logitcrossentropy(m(x), y)
end
Flux.update!(opt_state, model, grads[1])
end
end

accuracy = sum(sum(Flux.onecold(cpu(model(device(x)))) .== y) for (x, y) in test_loader) / numobs(images)
```

## Segmentation

Call the spatial transform on the image and mask together, then prepare each result separately as in [Pipelines](pipelines.md#Images-and-segmentation-masks). By default, padding a mask repeats its edge labels.

```@example flux
masks = [rand(1:3, 32, 32) for _ in 1:64]

seg_tfm = Maybe(FlipX()) |> RandomCrop(32; padding = 4) |> PinOrigin()
mask_prep = OneHot() |> PermuteDims(2, 1, 3)

function augment_pair(image, labels)
timage, tmask = seg_tfm((Image(image), MaskMulti(labels, 1:3)))
return itemdata(test_tfm(timage)), itemdata(mask_prep(tmask))
end

seg_data = mapobs(((image, labels),) -> augment_pair(image, labels), (images, masks))
seg_loader = DataLoader(seg_data; batchsize = 16, shuffle = true, collate = true,
partial = false, parallel = true)

x, y = first(seg_loader)
size(x), size(y)
```

## Object detection

Use the [image and bounding box pipeline](pipelines.md#Images-and-bounding-boxes) in `mapobs` to return an image tensor with the transformed boxes and their labels. Crop sizes and box counts can vary across samples. Use `collate = false` to receive a vector of `(image, target)` pairs, or supply a custom collation function for the detector's batch format.
6 changes: 4 additions & 2 deletions docs/src/index.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# DataAugmentation.jl

Efficient, composable data augmentation for machine and deep learning, with support for n-dimensional images, keypoints and categorical masks.
Efficient, composable data augmentation for machine and deep learning, with support for n-dimensional images, categorical masks, keypoints, and bounding boxes.

An [`Item`](@ref) wraps data, and a [`Transform`](@ref) operates on the item. To resize an [`Image`](@ref), create a [`CenterResizeCrop`](@ref) transform and call it on the item.

Expand Down Expand Up @@ -28,10 +28,12 @@ Pkg.add("DataAugmentation")
- [Items](items.md): the containers for your data.
- [Transformations](transformations.md): composing and randomizing transformations, and an overview of those that are available.
- [Gallery](gallery.md): what the spatial transformations look like.
- [Pipelines](pipelines.md) walks through classification, segmentation, landmarks, object detection, and 3D images.
- [Preprocessing](preprocessing.md): getting data ready to be put into a model.
- [Using with Flux](flux.md): data loading, batching and training with augmented data.
- [Buffering](buffering.md): reusing output buffers for speed.
- **Concepts**: why the library looks the way it does.
- [Design](design.md): stochasticity, composition and buffering.
- [Projective transformations](projective.md): fusing and cropping spatial transformations.
- **Extending**: writing your own [items](iteminterface.md), [transformations](tfminterface.md) and [projective transformations](projinterface.md).
- [API reference](ref.md): every documented name.
- [API reference](ref.md) with an alphabetical [symbol index](@ref reference-index).
Loading
Loading