imgaug
This python library helps you with augmenting images for your machine learning projects. It converts a set of input images into a new, much larger set of slightly altered images.
Codacy Badge
| Image | Heatmaps | Seg. Maps | Keypoints | Bounding Boxes, Polygons |
|
|---|---|---|---|---|---|
| Original Input | |||||
| Gauss. Noise + Contrast + Sharpen |
|||||
| Affine | |||||
| Crop + Pad |
|||||
| Fliplr + Perspective |
More (strong) example augmentations of one input image:
64 quokkas
Table of Contents
Features
- Many augmentation techniques
- E.g. affine transformations, perspective transformations, contrast changes, gaussian noise, dropout of regions, hue/saturation changes, cropping/padding, blurring, ...
- Optimized for high performance
- Easy to apply augmentations only to some images
- Easy to apply augmentations in random order
- Support for
- Images (full support for uint8, for other dtypes see documentation)
- Heatmaps (float32), Segmentation Maps (int), Masks (bool)
- May be smaller/larger than their corresponding images. No extra lines of code needed for e.g. crop.
- Keypoints/Landmarks (int/float coordinates)
- Bounding Boxes (int/float coordinates)
- Polygons (int/float coordinates)
- Line Strings (int/float coordinates)
- Automatic alignment of sampled random values
- Example: Rotate image and segmentation map on it by the same value sampled from
uniform(-10°, 45°). (0 extra lines of code.) - Probability distributions as parameters
- Example: Rotate images by values sampled from
uniform(-10°, 45°). - Example: Rotate images by values sampled from
ABS(N(0, 20.0))*(1+B(1.0, 1.0))", whereABS(.)is the absolute function,N(.)the gaussian distribution andB(.)the beta distribution. - Many helper functions
- Example: Draw heatmaps, segmentation maps, keypoints, bounding boxes, ...
- Example: Scale segmentation maps, average/max pool of images/maps, pad images to aspect ratios (e.g. to square them)
- Example: Convert keypoints to distance maps, extract pixels within bounding boxes from images, clip polygon to the image plane, ...
- Support for augmentation on multiple CPU cores
Installation
The library supports python 2.7 and 3.4+.
Installation: Anaconda
To install the library in anaconda, perform the following commands:
conda config --add channels conda-forge
conda install imgaug
You can deinstall the library again via conda remove imgaug.
Installation: pip
Then install imgaug either via pypi (can lag behind the github version):
pip install imgaug
or install the latest version directly from github:
pip install git+https://github.com/aleju/imgaug.git
For more details, see the install guide
To deinstall the library, just execute pip uninstall imgaug.
Documentation
Example jupyter notebooks: * Load and Augment an Image * Multicore Augmentation * Augment and work with: Keypoints/Landmarks, Bounding Boxes, Polygons, Line Strings, Heatmaps, Segmentation Maps
More notebooks: imgaug-doc/notebooks.
Example ReadTheDocs pages: * Quick example code on how to use the library * Overview of all Augmenters * API
More RTD documentation: imgaug.readthedocs.io.
All documentation related files of this project are hosted in the repository imgaug-doc.
Recent Changes
- 0.4.0: Added new augmenters, changed backend to batchwise augmentation, support for numpy 1.18 and python 3.8.
- 0.3.0: Reworked segmentation map augmentation, adapted to numpy 1.17+ random number sampling API, several new augmenters.
- 0.2.9: Added polygon augmentation, added line string augmentation, simplified augmentation interface.
- 0.2.8: Improved performance, dtype support and multicore augmentation.
See changelogs/ for more details.
Example Images
The images below show examples for most augmentation techniques.
Values written in the form (a, b) denote a uniform distribution,
i.e. the value is randomly picked from the interval [a, b].
Line strings are supported by (almost) all augmenters, but are not explicitly
visualized here.
Code Examples
Example: Simple Training Setting
A standard machine learning situation. Train on batches of images and augment each batch via crop, horizontal flip ("Fliplr") and gaussian blur:
import numpy as np
import imgaug.augmenters as iaa
def load_batch(batch_idx):
# dummy function, implement this
# Return a numpy array of shape (N, height, width, #channels)
# or a list of (height, width, #channels) arrays (may have different image
# sizes).
# Images should be in RGB for colorspace augmentations.
# (cv2.imread() returns BGR!)
# Images should usually be in uint8 with values from 0-255.
return np.zeros((128, 32, 32, 3), dtype=np.uint8) + (batch_idx % 255)
def train_on_images(images):
# dummy function, implement this
pass
# Pipeline:
# (1) Crop images from each side by 1-16px, do not resize the results
# images back to the input size. Keep them at the cropped size.
# (2) Horizontally flip 50% of the images.
# (3) Blur images using a gaussian kernel with sigma between 0.0 and 3.0.
seq = iaa.Sequential([
iaa.Crop(px=(1, 16), keep_size=False),
iaa.Fliplr(0.5),
iaa.GaussianBlur(sigma=(0, 3.0))
])
for batch_idx in range(100):
images = load_batch(batch_idx)
images_aug = seq(images=images) # done by the library
train_on_images(images_aug)
Example: Very Complex Augmentation Pipeline
Apply a very heavy augmentation pipeline to images (used to create the image at the very top of this readme):
import numpy as np
import imgaug as ia
import imgaug.augmenters as iaa
# random example images
images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)
# Sometimes(0.5, ...) applies the given augmenter in 50% of all cases,
# e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second image.
sometimes = lambda aug: iaa.Sometimes(0.5, aug)
# Define our sequence of augmentation steps that will be applied to every image
# All augmenters with per_channel=0.5 will sample one value _per image_
# in 50% of all cases. In all other cases they will sample new values
# _per channel_.
seq = iaa.Sequential(
[
# apply the following augmenters to most images
iaa.Fliplr(0.5), # horizontally flip 50% of all images
iaa.Flipud(0.2), # vertically flip 20% of all images
# crop images by -5% to 10% of their height/width
sometimes(iaa.CropAndPad(
percent=(-0.05, 0.1),
pad_mode=ia.ALL,
pad_cval=(0, 255)
)),
sometimes(iaa.Affine(
scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, # scale images to 80-120% of their size, individually per axis
translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, # translate by -20 to +20 percent (per axis)
rotate=(-45, 45), # rotate by -45 to +45 degrees
shear=(-16, 16), # shear by -16 to +16 degrees
order=[0, 1], # use nearest neighbour or bilinear interpolation (fast)
cval=(0, 255), # if mode is constant, use a cval between 0 and 255
mode=ia.ALL # use any of scikit-image's warping modes (see 2nd image from the top for examples)
)),
# execute 0 to 5 of the following (less important) augmenters per image
# don't execute all of them, as that would often be way too strong
iaa.SomeOf((0, 5),
[
sometimes(iaa.Superpixels(p_replace=(0, 1.0), n_segments=(20, 200))), # convert images into their superpixel representation
iaa.OneOf([
iaa.GaussianBlur((0, 3.0)), # blur images with a sigma between 0 and 3.0
iaa.AverageBlur(k=(2, 7)), # blur image using local means with kernel sizes between 2 and 7
iaa.MedianBlur(k=(3, 11)), # blur image using local medians with kernel sizes between 2 and 7
]),
iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)), # sharpen images
iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), # emboss images
# search either for all edges or for directed edges,
# blend the result with the original image using a blobby mask
iaa.SimplexNoiseAlpha(iaa.OneOf([
iaa.EdgeDetect(alpha=(0.5, 1.0)),
iaa.DirectedEdgeDetect(alpha=(0.5, 1.0), direction=(0.0, 1.0)),
])),
iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # add gaussian noise to images
iaa.OneOf([
iaa.Dropout((0.01, 0.1), per_channel=0.5), # randomly remove up to 10% of the pixels
iaa.CoarseDropout((0.03, 0.15), size_percent=(0.02, 0.05), per_channel=0.2),
]),
iaa.Invert(0.05, per_channel=True), # invert color channels
iaa.Add((-10, 10), per_channel=0.5), # change brightness of images (by -10 to 10 of original value)
iaa.AddToHueAndSaturation((-20, 20)), # change hue and saturation
# either change the brightness of the whole image (sometimes
# per channel) or change the brightness of subareas
iaa.OneOf([
iaa.Multiply((0.5, 1.5), per_channel=0.5),
iaa.FrequencyNoiseAlpha(
exponent=(-4, 0),
first=iaa.Multiply((0.5, 1.5), per_channel=True),
second=iaa.LinearContrast((0.5, 2.0))
)
]),
iaa.LinearContrast((0.5, 2.0), per_channel=0.5), # improve or worsen the contrast
iaa.Grayscale(alpha=(0.0, 1.0)),
sometimes(iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)), # move pixels locally around (with random strengths)
sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.05))), # sometimes move parts of the image around
sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.1)))
],
random_order=True
)
],
random_order=True
)
images_aug = seq(images=images)
Example: Augment Images and Keypoints
Augment images and keypoints/landmarks on the same images: ```python import numpy as np import imgaug.augmenters as iaa
images = np.zeros((2, 128, 128, 3), dtype=np.uint8) # two example images images[:, 64, 64, :] = 255 points = [ [(10.5, 20.5)], # points on first image [(50.5, 50.5), (60.5, 60.5), (70.5, 70.5)] # points on second image ]
seq = iaa.Sequential([ iaa.AdditiveGaussianNoise(scale=0.05*255), iaa.Affine(translate_px={"x": (1, 5)}) ])
README 内容较长,此处已截断,完整内容请查看 GitHub 仓库。