Skip to content

Instantly share code, notes, and snippets.

@Lexie88rus
Created August 8, 2019 18:42
Show Gist options
  • Save Lexie88rus/b1f3a45f3e0e19c59c1795d7509d42a4 to your computer and use it in GitHub Desktop.
Save Lexie88rus/b1f3a45f3e0e19c59c1795d7509d42a4 to your computer and use it in GitHub Desktop.
Albumentations: PyTorch integration
# Import pytorch utilities from albumentations
from albumentations.pytorch import ToTensor
# Define the augmentation pipeline
augmentation_pipeline = A.Compose(
[
A.HorizontalFlip(p = 0.5), # apply horizontal flip to 50% of images
A.OneOf(
[
# apply one of transforms to 50% of images
A.RandomContrast(), # apply random contrast
A.RandomGamma(), # apply random gamma
A.RandomBrightness(), # apply random brightness
],
p = 0.5
),
A.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
ToTensor() # convert the image to PyTorch tensor
],
p = 1
)
# Load the augmented data
# Define the demo dataset
class DogDataset2(Dataset):
'''
Sample dataset for Albumentations demonstration.
The dataset will consist of just one sample image.
'''
def __init__(self, image, augmentations = None):
self.image = image
self.augmentations = augmentations # save the augmentations
def __len__(self):
return 1 # return 1 as we have only one image
def __getitem__(self, idx):
# return the augmented image
# no need to convert to tensor, because image is converted to tensor already by the pipeline
augmented = self.augmentations(image = self.image)
return augmented['image']
# Initialize the dataset, pass the augmentation pipeline as an argument to init function
train_ds = DogDataset2(image, augmentations = augmentation_pipeline)
# Initilize the dataloader
trainloader = DataLoader(train_ds, batch_size=1, shuffle=True, num_workers=0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment