def data_aug(images): seq = iaa.Sometimes( 0.5, iaa.Identity(), iaa.Sometimes( 0.5, iaa.Sequential([ iaa.Sometimes( 0.5, iaa.OneOf([ iaa.AdditiveGaussianNoise(scale=(0, 0.1 * 255)), iaa.AdditiveLaplaceNoise(scale=(0, 0.1 * 255)), iaa.ReplaceElementwise(0.03, [0, 255]), iaa.GaussianBlur(sigma=(0.0, 3.0)), iaa.BilateralBlur(d=(3, 10), sigma_color=(10, 250), sigma_space=(10, 250)) ])), iaa.OneOf([ iaa.Add((-40, 40)), iaa.AddElementwise((-20, 20)), iaa.pillike.EnhanceBrightness() ]), iaa.OneOf([ iaa.GammaContrast((0.2, 2.0)), iaa.SigmoidContrast(gain=(3, 10), cutoff=(0.4, 0.6)), iaa.LogContrast(gain=(0.6, 1.4)), iaa.AllChannelsCLAHE(), iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.75, 2.0)), ]) ]))) images = seq(images=images) return images
def get_transforms(): sometimes = lambda aug: iaa.Sometimes(0.2, aug) seq1 = iaa.Sequential([ iaa.Fliplr(0.5), iaa.Flipud(0.5), sometimes( iaa.Affine( scale={ "x": (0.8, 1.2), "y": (0.8, 1.2) }, translate_percent={ "x": (-0.2, 0.2), "y": (-0.2, 0.2) }, rotate=(-30, 30), shear=(-10, 10), mode='constant', cval=(0, 255), )), sometimes( iaa.PiecewiseAffine( scale=(0.01, 0.05), nb_cols=8, nb_rows=8, mode='constant', cval=(0, 255), )), ], ) seq2 = iaa.Sequential([ iaa.SomeOf((0, 1), [ sometimes(iaa.MultiplyElementwise((0.8, 1.2))), sometimes(iaa.AddElementwise((-20, 20))), sometimes(iaa.ContrastNormalization((0.8, 1.2))), ]), iaa.SomeOf((0, 1), [ iaa.OneOf([ iaa.GaussianBlur((0, 2.0)), iaa.AverageBlur(k=2), iaa.MedianBlur(k=3), ]), iaa.AdditiveGaussianNoise(0, 10), iaa.SaltAndPepper(0.01), iaa.ReplaceElementwise(0.05, (0, 255)) ]), ], ) return seq1, seq2
def __init__(self): self.aug = iaa.Sequential([ iaa.Scale((224, 224)), iaa.Sometimes(0.30, iaa.GaussianBlur(sigma=(0, 3.0))), iaa.Sometimes(0.25, iaa.Multiply((0.5, 1.5), per_channel=0.5)), iaa.Sometimes(0.20, iaa.Invert(0.25, per_channel=0.5)), iaa.Sometimes(0.25, iaa.ReplaceElementwise( iap.FromLowerResolution(iap.Binomial(0.1), size_px=8), iap.Normal(128, 0.4*128), per_channel=0.5) ), iaa.Sometimes(0.30, iaa.AdditivePoissonNoise(40)), iaa.Fliplr(0.5), iaa.Affine(rotate=(-20, 20), mode='symmetric'), iaa.Sometimes(0.30, iaa.OneOf([iaa.Dropout(p=(0, 0.1)), iaa.CoarseDropout(0.1, size_percent=0.5)])), iaa.AddToHueAndSaturation(value=(-10, 10), per_channel=True) ])
def aug_data(x_data, y_data, percent, aug_percent): rand_vector = np.linspace(0, np.shape(x_data)[0], num=int(percent*np.shape(x_data)[0]/100), endpoint=False, dtype = int) for count in range(0, len(rand_vector)): ppl = Image.fromarray(x_data[rand_vector[count],:,:,:].astype('uint8')) ppl = np.array(ppl) seq1 = iaa.Sequential([ iaa.ReplaceElementwise( iap.FromLowerResolution(iap.Binomial(aug_percent), size_px=4), iap.Normal(128, 0.4*128), per_channel=1) ]) aug_image = seq1(images=ppl) x_data[rand_vector[count],:,:,:] = np.copy(aug_image) return x_data, y_data
def generate_batch_augmented(X, y, batch_size=32, crop_size=130): while True: batch_X, batch_y = next(generate_batch(X, y, batch_size)) seq = iaa.Sequential( [ iaa.Fliplr(0.5), iaa.Flipud(0.5), iaa.Affine( rotate=(-180, 180), # rotate by -45 to +45 degrees order=[3], # use nearest neighbour or bilinear interpolation (fast) ), iaa.CropToFixedSize(crop_size, crop_size), ] ) seq_X = iaa.Sometimes(0.5, [iaa.ReplaceElementwise(0.01, iap.Uniform(0, 2000))]) if batch_X[0].ndim == 2: channels = 1 else: channels = batch_X[0].shape[-1] batch_aug_X = np.empty((batch_size, crop_size, crop_size, channels)) batch_aug_y = np.empty((batch_size, crop_size, crop_size, 1)) for i in range(batch_size): seq_det = ( seq.to_deterministic() ) # call this for each batch again, NOT only once at the start images_aug = seq_det.augment_image(batch_X[i]) forces_aug = seq_det.augment_image(batch_y[i]) images_aug = seq_X.augment_image(images_aug) if images_aug.ndim == 2: batch_aug_X[i] = np.expand_dims(images_aug, axis=-1) else: batch_aug_X[i] = images_aug if forces_aug.ndim == 2: batch_aug_y[i] = np.expand_dims(forces_aug, axis=-1) else: batch_aug_y[i] = forces_aug yield batch_aug_X, batch_aug_y
def __init__(self, base_data_path, train, transform, id_name_path, device, little_train=False, read_mode='jpeg4py', input_size=224, C=2048, test_mode=False): print('data init') self.train = train self.base_data_path = base_data_path self.transform = transform self.fnames = [] self.resize = input_size self.little_train = little_train self.id_name_path = id_name_path self.C = C self.read_mode = read_mode self.device = device self._test = test_mode self.fnames = self.get_data_list(base_data_path) self.num_samples = len(self.fnames) self.get_id_map() self.cls_path_map = self.get_cls_pathlist_map() self.img_augsometimes = lambda aug: iaa.Sometimes(0.5, aug) self.augmentation = iaa.Sequential( [ # augment without change bboxes self.img_augsometimes( iaa.SomeOf( (1, 4), [ iaa.Dropout([0.05, 0.2 ]), # drop 5% or 20% of all pixels iaa.Sharpen((0.1, .8)), # sharpen the image # iaa.GaussianBlur(sigma=(2., 3.5)), iaa.OneOf([ iaa.GaussianBlur(sigma=(2., 3.5)), iaa.AverageBlur(k=(2, 5)), iaa.BilateralBlur(d=(7, 12), sigma_color=(10, 250), sigma_space=(10, 250)), iaa.MedianBlur(k=(3, 7)), ]), iaa.AddElementwise((-50, 50)), iaa.AdditiveGaussianNoise(scale=(0, 0.1 * 255)), iaa.JpegCompression(compression=(80, 95)), iaa.Multiply((0.5, 1.5)), iaa.MultiplyElementwise((0.5, 1.5)), iaa.ReplaceElementwise(0.05, [0, 255]), # iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", # children=iaa.WithChannels(2, iaa.Add((-10, 50)))), iaa.OneOf([ iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels( 1, iaa.Add((-10, 50)))), iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels( 2, iaa.Add((-10, 50)))), ]), iaa.Affine(scale={ "x": (0.8, 1.2), "y": (0.8, 1.2) }, translate_percent={ "x": (-0.2, 0.2), "y": (-0.2, 0.2) }, rotate=(-25, 25), shear=(-8, 8)) ], random_order=True)), iaa.Fliplr(.5), iaa.Flipud(.25), ], random_order=True)
"Elastic_Transformation": lambda alpha_lo, alpha_hi, sigma_lo, sigma_hi: iaa.ElasticTransformation(alpha=(alpha_lo, alpha_hi), sigma=(sigma_lo, sigma_hi)), # Weather augmenters are computationally expensive and will not work effectively on certain data sets # Augmenter to draw clouds in images. "Clouds": iaa.Clouds(), # Augmenter to draw fog in images. "Fog": iaa.Fog(), # Augmenter to add falling snowflakes to images. "Snowflakes": iaa.Snowflakes(), # Replaces percent of all pixels in an image by either x or y "Replace_Element_Wise": lambda percent, x, y: iaa.ReplaceElementwise(percent, [x, y]), # Adds laplace noise (somewhere between gaussian and salt and peeper noise) to an image, sampled once per pixel # from a laplace distribution Laplace(0, s), where s is sampled per image and varies between lo and hi*255 for # percent of all images (sampled once for all channels) and sampled three (RGB) times (channel-wise) # for the rest from the same laplace distribution: "Additive_Laplace_Noise": lambda lo, hi, percent: iaa.AdditiveLaplaceNoise(scale=(lo, hi), per_channel=percent), # Adds poisson noise (similar to gaussian but different distribution) to an image, sampled once per pixel from # a poisson distribution Poisson(s), where s is sampled per image and varies between lo and hi for percent of # all images (sampled once for all channels) and sampled three (RGB) times (channel-wise) # for the rest from the same poisson distribution: "Additive_Poisson_Noise": lambda lo, hi, percent: iaa.AdditivePoissonNoise(lam=(lo, hi), per_channel=percent),
def __init__(self, list_file, train, transform, device, little_train=False, S=7): print('data init') self.train = train self.transform = transform self.fnames = [] self.boxes = [] self.labels = [] self.S = S self.B = 2 self.C = 20 self.device = device self.augmentation = iaa.Sometimes( 0.5, iaa.SomeOf( (1, 6), [ iaa.Dropout([0.05, 0.2]), # drop 5% or 20% of all pixels iaa.Sharpen((0.1, 1.0)), # sharpen the image iaa.GaussianBlur(sigma=(2., 3.5)), iaa.OneOf([ iaa.GaussianBlur(sigma=(2., 3.5)), iaa.AverageBlur(k=(2, 5)), iaa.BilateralBlur(d=(7, 12), sigma_color=(10, 250), sigma_space=(10, 250)), iaa.MedianBlur(k=(3, 7)), ]), # iaa.Fliplr(1.0), # iaa.Flipud(1.0), iaa.AddElementwise((-50, 50)), iaa.AdditiveGaussianNoise(scale=(0, 0.1 * 255)), iaa.JpegCompression(compression=(80, 95)), iaa.Multiply((0.5, 1.5)), iaa.MultiplyElementwise((0.5, 1.5)), iaa.ReplaceElementwise(0.05, [0, 255]), iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels( 2, iaa.Add((-10, 50)))), iaa.OneOf([ iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels( 1, iaa.Add((-10, 50)))), iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels( 2, iaa.Add((-10, 50)))), ]), ], random_order=True)) torch.manual_seed(23) with open(list_file) as f: lines = f.readlines() if little_train: lines = lines[:64] for line in lines: splited = line.strip().split() self.fnames.append(splited[0]) self.num_samples = len(self.fnames)
def create_augmenters(height, width, height_augmentable, width_augmentable, only_augmenters): def lambda_func_images(images, random_state, parents, hooks): return images def lambda_func_heatmaps(heatmaps, random_state, parents, hooks): return heatmaps def lambda_func_keypoints(keypoints, random_state, parents, hooks): return keypoints def assertlambda_func_images(images, random_state, parents, hooks): return True def assertlambda_func_heatmaps(heatmaps, random_state, parents, hooks): return True def assertlambda_func_keypoints(keypoints, random_state, parents, hooks): return True augmenters_meta = [ iaa.Sequential([iaa.Noop(), iaa.Noop()], random_order=False, name="Sequential_2xNoop"), iaa.Sequential([iaa.Noop(), iaa.Noop()], random_order=True, name="Sequential_2xNoop_random_order"), iaa.SomeOf((1, 3), [iaa.Noop(), iaa.Noop(), iaa.Noop()], random_order=False, name="SomeOf_3xNoop"), iaa.SomeOf((1, 3), [iaa.Noop(), iaa.Noop(), iaa.Noop()], random_order=True, name="SomeOf_3xNoop_random_order"), iaa.OneOf([iaa.Noop(), iaa.Noop(), iaa.Noop()], name="OneOf_3xNoop"), iaa.Sometimes(0.5, iaa.Noop(), name="Sometimes_Noop"), iaa.WithChannels([1, 2], iaa.Noop(), name="WithChannels_1_and_2_Noop"), iaa.Noop(name="Noop"), iaa.Lambda(func_images=lambda_func_images, func_heatmaps=lambda_func_heatmaps, func_keypoints=lambda_func_keypoints, name="Lambda"), iaa.AssertLambda(func_images=assertlambda_func_images, func_heatmaps=assertlambda_func_heatmaps, func_keypoints=assertlambda_func_keypoints, name="AssertLambda"), iaa.AssertShape((None, height_augmentable, width_augmentable, None), name="AssertShape"), iaa.ChannelShuffle(0.5, name="ChannelShuffle") ] augmenters_arithmetic = [ iaa.Add((-10, 10), name="Add"), iaa.AddElementwise((-10, 10), name="AddElementwise"), #iaa.AddElementwise((-500, 500), name="AddElementwise"), iaa.AdditiveGaussianNoise(scale=(5, 10), name="AdditiveGaussianNoise"), iaa.AdditiveLaplaceNoise(scale=(5, 10), name="AdditiveLaplaceNoise"), iaa.AdditivePoissonNoise(lam=(1, 5), name="AdditivePoissonNoise"), iaa.Multiply((0.5, 1.5), name="Multiply"), iaa.MultiplyElementwise((0.5, 1.5), name="MultiplyElementwise"), iaa.Dropout((0.01, 0.05), name="Dropout"), iaa.CoarseDropout((0.01, 0.05), size_percent=(0.01, 0.1), name="CoarseDropout"), iaa.ReplaceElementwise((0.01, 0.05), (0, 255), name="ReplaceElementwise"), #iaa.ReplaceElementwise((0.95, 0.99), (0, 255), name="ReplaceElementwise"), iaa.SaltAndPepper((0.01, 0.05), name="SaltAndPepper"), iaa.ImpulseNoise((0.01, 0.05), name="ImpulseNoise"), iaa.CoarseSaltAndPepper((0.01, 0.05), size_percent=(0.01, 0.1), name="CoarseSaltAndPepper"), iaa.Salt((0.01, 0.05), name="Salt"), iaa.CoarseSalt((0.01, 0.05), size_percent=(0.01, 0.1), name="CoarseSalt"), iaa.Pepper((0.01, 0.05), name="Pepper"), iaa.CoarsePepper((0.01, 0.05), size_percent=(0.01, 0.1), name="CoarsePepper"), iaa.Invert(0.1, name="Invert"), # ContrastNormalization iaa.JpegCompression((50, 99), name="JpegCompression") ] augmenters_blend = [ iaa.Alpha((0.01, 0.99), iaa.Noop(), name="Alpha"), iaa.AlphaElementwise((0.01, 0.99), iaa.Noop(), name="AlphaElementwise"), iaa.SimplexNoiseAlpha(iaa.Noop(), name="SimplexNoiseAlpha"), iaa.FrequencyNoiseAlpha((-2.0, 2.0), iaa.Noop(), name="FrequencyNoiseAlpha") ] augmenters_blur = [ iaa.GaussianBlur(sigma=(1.0, 5.0), name="GaussianBlur"), iaa.AverageBlur(k=(3, 11), name="AverageBlur"), iaa.MedianBlur(k=(3, 11), name="MedianBlur"), iaa.BilateralBlur(d=(3, 11), name="BilateralBlur"), iaa.MotionBlur(k=(3, 11), name="MotionBlur") ] augmenters_color = [ # InColorspace (deprecated) iaa.WithColorspace(to_colorspace="HSV", children=iaa.Noop(), name="WithColorspace"), iaa.WithHueAndSaturation(children=iaa.Noop(), name="WithHueAndSaturation"), iaa.MultiplyHueAndSaturation((0.8, 1.2), name="MultiplyHueAndSaturation"), iaa.MultiplyHue((-1.0, 1.0), name="MultiplyHue"), iaa.MultiplySaturation((0.8, 1.2), name="MultiplySaturation"), iaa.AddToHueAndSaturation((-10, 10), name="AddToHueAndSaturation"), iaa.AddToHue((-10, 10), name="AddToHue"), iaa.AddToSaturation((-10, 10), name="AddToSaturation"), iaa.ChangeColorspace(to_colorspace="HSV", name="ChangeColorspace"), iaa.Grayscale((0.01, 0.99), name="Grayscale"), iaa.KMeansColorQuantization((2, 16), name="KMeansColorQuantization"), iaa.UniformColorQuantization((2, 16), name="UniformColorQuantization") ] augmenters_contrast = [ iaa.GammaContrast(gamma=(0.5, 2.0), name="GammaContrast"), iaa.SigmoidContrast(gain=(5, 20), cutoff=(0.25, 0.75), name="SigmoidContrast"), iaa.LogContrast(gain=(0.7, 1.0), name="LogContrast"), iaa.LinearContrast((0.5, 1.5), name="LinearContrast"), iaa.AllChannelsCLAHE(clip_limit=(2, 10), tile_grid_size_px=(3, 11), name="AllChannelsCLAHE"), iaa.CLAHE(clip_limit=(2, 10), tile_grid_size_px=(3, 11), to_colorspace="HSV", name="CLAHE"), iaa.AllChannelsHistogramEqualization( name="AllChannelsHistogramEqualization"), iaa.HistogramEqualization(to_colorspace="HSV", name="HistogramEqualization"), ] augmenters_convolutional = [ iaa.Convolve(np.float32([[0, 0, 0], [0, 1, 0], [0, 0, 0]]), name="Convolve_3x3"), iaa.Sharpen(alpha=(0.01, 0.99), lightness=(0.5, 2), name="Sharpen"), iaa.Emboss(alpha=(0.01, 0.99), strength=(0, 2), name="Emboss"), iaa.EdgeDetect(alpha=(0.01, 0.99), name="EdgeDetect"), iaa.DirectedEdgeDetect(alpha=(0.01, 0.99), name="DirectedEdgeDetect") ] augmenters_edges = [iaa.Canny(alpha=(0.01, 0.99), name="Canny")] augmenters_flip = [ iaa.Fliplr(1.0, name="Fliplr"), iaa.Flipud(1.0, name="Flipud") ] augmenters_geometric = [ iaa.Affine(scale=(0.9, 1.1), translate_percent={ "x": (-0.05, 0.05), "y": (-0.05, 0.05) }, rotate=(-10, 10), shear=(-10, 10), order=0, mode="constant", cval=(0, 255), name="Affine_order_0_constant"), iaa.Affine(scale=(0.9, 1.1), translate_percent={ "x": (-0.05, 0.05), "y": (-0.05, 0.05) }, rotate=(-10, 10), shear=(-10, 10), order=1, mode="constant", cval=(0, 255), name="Affine_order_1_constant"), iaa.Affine(scale=(0.9, 1.1), translate_percent={ "x": (-0.05, 0.05), "y": (-0.05, 0.05) }, rotate=(-10, 10), shear=(-10, 10), order=3, mode="constant", cval=(0, 255), name="Affine_order_3_constant"), iaa.Affine(scale=(0.9, 1.1), translate_percent={ "x": (-0.05, 0.05), "y": (-0.05, 0.05) }, rotate=(-10, 10), shear=(-10, 10), order=1, mode="edge", cval=(0, 255), name="Affine_order_1_edge"), iaa.Affine(scale=(0.9, 1.1), translate_percent={ "x": (-0.05, 0.05), "y": (-0.05, 0.05) }, rotate=(-10, 10), shear=(-10, 10), order=1, mode="constant", cval=(0, 255), backend="skimage", name="Affine_order_1_constant_skimage"), # TODO AffineCv2 iaa.PiecewiseAffine(scale=(0.01, 0.05), nb_rows=4, nb_cols=4, order=1, mode="constant", name="PiecewiseAffine_4x4_order_1_constant"), iaa.PiecewiseAffine(scale=(0.01, 0.05), nb_rows=4, nb_cols=4, order=0, mode="constant", name="PiecewiseAffine_4x4_order_0_constant"), iaa.PiecewiseAffine(scale=(0.01, 0.05), nb_rows=4, nb_cols=4, order=1, mode="edge", name="PiecewiseAffine_4x4_order_1_edge"), iaa.PiecewiseAffine(scale=(0.01, 0.05), nb_rows=8, nb_cols=8, order=1, mode="constant", name="PiecewiseAffine_8x8_order_1_constant"), iaa.PerspectiveTransform(scale=(0.01, 0.05), keep_size=False, name="PerspectiveTransform"), iaa.PerspectiveTransform(scale=(0.01, 0.05), keep_size=True, name="PerspectiveTransform_keep_size"), iaa.ElasticTransformation( alpha=(1, 10), sigma=(0.5, 1.5), order=0, mode="constant", cval=0, name="ElasticTransformation_order_0_constant"), iaa.ElasticTransformation( alpha=(1, 10), sigma=(0.5, 1.5), order=1, mode="constant", cval=0, name="ElasticTransformation_order_1_constant"), iaa.ElasticTransformation( alpha=(1, 10), sigma=(0.5, 1.5), order=1, mode="nearest", cval=0, name="ElasticTransformation_order_1_nearest"), iaa.ElasticTransformation( alpha=(1, 10), sigma=(0.5, 1.5), order=1, mode="reflect", cval=0, name="ElasticTransformation_order_1_reflect"), iaa.Rot90((1, 3), keep_size=False, name="Rot90"), iaa.Rot90((1, 3), keep_size=True, name="Rot90_keep_size") ] augmenters_pooling = [ iaa.AveragePooling(kernel_size=(1, 16), keep_size=False, name="AveragePooling"), iaa.AveragePooling(kernel_size=(1, 16), keep_size=True, name="AveragePooling_keep_size"), iaa.MaxPooling(kernel_size=(1, 16), keep_size=False, name="MaxPooling"), iaa.MaxPooling(kernel_size=(1, 16), keep_size=True, name="MaxPooling_keep_size"), iaa.MinPooling(kernel_size=(1, 16), keep_size=False, name="MinPooling"), iaa.MinPooling(kernel_size=(1, 16), keep_size=True, name="MinPooling_keep_size"), iaa.MedianPooling(kernel_size=(1, 16), keep_size=False, name="MedianPooling"), iaa.MedianPooling(kernel_size=(1, 16), keep_size=True, name="MedianPooling_keep_size") ] augmenters_segmentation = [ iaa.Superpixels(p_replace=(0.05, 1.0), n_segments=(10, 100), max_size=64, interpolation="cubic", name="Superpixels_max_size_64_cubic"), iaa.Superpixels(p_replace=(0.05, 1.0), n_segments=(10, 100), max_size=64, interpolation="linear", name="Superpixels_max_size_64_linear"), iaa.Superpixels(p_replace=(0.05, 1.0), n_segments=(10, 100), max_size=128, interpolation="linear", name="Superpixels_max_size_128_linear"), iaa.Superpixels(p_replace=(0.05, 1.0), n_segments=(10, 100), max_size=224, interpolation="linear", name="Superpixels_max_size_224_linear"), iaa.UniformVoronoi(n_points=(250, 1000), name="UniformVoronoi"), iaa.RegularGridVoronoi(n_rows=(16, 31), n_cols=(16, 31), name="RegularGridVoronoi"), iaa.RelativeRegularGridVoronoi(n_rows_frac=(0.07, 0.14), n_cols_frac=(0.07, 0.14), name="RelativeRegularGridVoronoi"), ] augmenters_size = [ iaa.Resize((0.8, 1.2), interpolation="nearest", name="Resize_nearest"), iaa.Resize((0.8, 1.2), interpolation="linear", name="Resize_linear"), iaa.Resize((0.8, 1.2), interpolation="cubic", name="Resize_cubic"), iaa.CropAndPad(percent=(-0.2, 0.2), pad_mode="constant", pad_cval=(0, 255), keep_size=False, name="CropAndPad"), iaa.CropAndPad(percent=(-0.2, 0.2), pad_mode="edge", pad_cval=(0, 255), keep_size=False, name="CropAndPad_edge"), iaa.CropAndPad(percent=(-0.2, 0.2), pad_mode="constant", pad_cval=(0, 255), name="CropAndPad_keep_size"), iaa.Pad(percent=(0.05, 0.2), pad_mode="constant", pad_cval=(0, 255), keep_size=False, name="Pad"), iaa.Pad(percent=(0.05, 0.2), pad_mode="edge", pad_cval=(0, 255), keep_size=False, name="Pad_edge"), iaa.Pad(percent=(0.05, 0.2), pad_mode="constant", pad_cval=(0, 255), name="Pad_keep_size"), iaa.Crop(percent=(0.05, 0.2), keep_size=False, name="Crop"), iaa.Crop(percent=(0.05, 0.2), name="Crop_keep_size"), iaa.PadToFixedSize(width=width + 10, height=height + 10, pad_mode="constant", pad_cval=(0, 255), name="PadToFixedSize"), iaa.CropToFixedSize(width=width - 10, height=height - 10, name="CropToFixedSize"), iaa.KeepSizeByResize(iaa.CropToFixedSize(height=height - 10, width=width - 10), interpolation="nearest", name="KeepSizeByResize_CropToFixedSize_nearest"), iaa.KeepSizeByResize(iaa.CropToFixedSize(height=height - 10, width=width - 10), interpolation="linear", name="KeepSizeByResize_CropToFixedSize_linear"), iaa.KeepSizeByResize(iaa.CropToFixedSize(height=height - 10, width=width - 10), interpolation="cubic", name="KeepSizeByResize_CropToFixedSize_cubic"), ] augmenters_weather = [ iaa.FastSnowyLandscape(lightness_threshold=(100, 255), lightness_multiplier=(1.0, 4.0), name="FastSnowyLandscape"), iaa.Clouds(name="Clouds"), iaa.Fog(name="Fog"), iaa.CloudLayer(intensity_mean=(196, 255), intensity_freq_exponent=(-2.5, -2.0), intensity_coarse_scale=10, alpha_min=0, alpha_multiplier=(0.25, 0.75), alpha_size_px_max=(2, 8), alpha_freq_exponent=(-2.5, -2.0), sparsity=(0.8, 1.0), density_multiplier=(0.5, 1.0), name="CloudLayer"), iaa.Snowflakes(name="Snowflakes"), iaa.SnowflakesLayer(density=(0.005, 0.075), density_uniformity=(0.3, 0.9), flake_size=(0.2, 0.7), flake_size_uniformity=(0.4, 0.8), angle=(-30, 30), speed=(0.007, 0.03), blur_sigma_fraction=(0.0001, 0.001), name="SnowflakesLayer") ] augmenters = (augmenters_meta + augmenters_arithmetic + augmenters_blend + augmenters_blur + augmenters_color + augmenters_contrast + augmenters_convolutional + augmenters_edges + augmenters_flip + augmenters_geometric + augmenters_pooling + augmenters_segmentation + augmenters_size + augmenters_weather) if only_augmenters is not None: augmenters_reduced = [] for augmenter in augmenters: if any([ re.search(pattern, augmenter.name) for pattern in only_augmenters ]): augmenters_reduced.append(augmenter) augmenters = augmenters_reduced return augmenters
# Augmenter to draw clouds in images. "Clouds": iaa.Clouds(), # Augmenter to draw fog in images. "Fog": iaa.Fog(), # Augmenter to add falling snowflakes to images. "Snowflakes": iaa.Snowflakes(), # Replaces percent of all pixels in an image by either x or y "Replace_Element_Wise": lambda percent, x, y: iaa.ReplaceElementwise(percent, [x, y]), # Adds laplace noise (somewhere between gaussian and salt and peeper noise) to an image, sampled once per pixel # from a laplace distribution Laplace(0, s), where s is sampled per image and varies between lo and hi*255 for # percent of all images (sampled once for all channels) and sampled three (RGB) times (channel-wise) # for the rest from the same laplace distribution: "Additive_Laplace_Noise": lambda lo, hi, percent: iaa.AdditiveLaplaceNoise(scale=(lo, hi), per_channel=percent), # Adds poisson noise (similar to gaussian but different distribution) to an image, sampled once per pixel from # a poisson distribution Poisson(s), where s is sampled per image and varies between lo and hi for percent of # all images (sampled once for all channels) and sampled three (RGB) times (channel-wise) # for the rest from the same poisson distribution: "Additive_Poisson_Noise": lambda lo, hi, percent: iaa.AdditivePoissonNoise(lam=(lo, hi),
def __init__(self, imgdirs_list, annfiles_list, train, transform, device, little_train=False, with_file_path=False, S=7, B=2, C=20, test_mode=False): print('data init') self.imgdirs_list = imgdirs_list self.anns_list = annfiles_list self.train = train self.transform = transform self.fnames = [] self.boxes = [] self.labels = [] self.dataset_list = [] self.resize = 448 self.S = S self.B = B self.C = C self.device = device self._test = test_mode self.with_file_path = with_file_path self.img_augsometimes = lambda aug: iaa.Sometimes(0.25, aug) self.bbox_augsometimes = lambda aug: iaa.Sometimes(0.5, aug) self.augmentation = iaa.Sequential( [ # augment without change bboxes self.img_augsometimes( iaa.SomeOf( (1, 3), [ iaa.Dropout([0.05, 0.2 ]), # drop 5% or 20% of all pixels iaa.Sharpen((0.1, .8)), # sharpen the image # iaa.GaussianBlur(sigma=(2., 3.5)), iaa.OneOf([ iaa.GaussianBlur(sigma=(2., 3.5)), iaa.AverageBlur(k=(2, 5)), iaa.BilateralBlur(d=(7, 12), sigma_color=(10, 250), sigma_space=(10, 250)), iaa.MedianBlur(k=(3, 7)), ]), iaa.AddElementwise((-50, 50)), iaa.AdditiveGaussianNoise(scale=(0, 0.1 * 255)), # iaa.JpegCompression(compression=(80, 95)), iaa.Multiply((0.5, 1.5)), iaa.MultiplyElementwise((0.5, 1.5)), iaa.ReplaceElementwise(0.05, [0, 255]), # iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", # children=iaa.WithChannels(2, iaa.Add((-10, 50)))), iaa.OneOf([ iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels( 1, iaa.Add((-10, 50)))), iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels( 2, iaa.Add((-10, 50)))), ]), ], random_order=True)), iaa.Fliplr(.5), iaa.Flipud(.125), # augment changing bboxes self.bbox_augsometimes( iaa.Affine( # translate_px={"x": 40, "y": 60}, scale={ "x": (0.8, 1.2), "y": (0.8, 1.2) }, translate_percent={ "x": (-0.1, 0.1), "y": (-0.1, 0.1) }, rotate=(-5, 5), )) ], random_order=True) for imgdir, annfile in zip(self.imgdirs_list, self.anns_list): print('handle dataset:\n\t' + imgdir + '\n\t' + annfile) annfile_json = json.load(open(annfile, 'r')) images = annfile_json['images'] annotations = annfile_json['annotations'] ann_dicts = {} for ann in annotations: if ann['image_id'] not in ann_dicts.keys(): ann_dicts[ann['image_id']] = [] ann_dicts[ann['image_id']].append(ann) for img in images: img['file_name'] = os.path.join(imgdir, img['file_name']) if img['id'] in ann_dicts.keys(): anns = ann_dicts[img['id']] else: continue image_ann = {'image_info': img, 'ann': anns} self.dataset_list.append(image_ann) self.num_samples = len(self.dataset_list) print('There are %d pics in datasets.' % (self.num_samples))
def __init__(self,list_file,train,transform, device, little_train=False, with_file_path=False, with_mask=False, S=7, B = 2, C = 20, test_mode=False): print('data init') self.train = train self.transform=transform self.fnames = [] self.boxes = [] self.labels = [] self.resize = 448 self.with_mask = with_mask self.S = S self.B = B self.C = C self.device = device self._test = test_mode self.with_file_path = with_file_path self.img_augsometimes = lambda aug: iaa.Sometimes(0.25, aug) self.bbox_augsometimes = lambda aug: iaa.Sometimes(0.5, aug) self.augmentation = iaa.Sequential( [ # augment without change bboxes self.img_augsometimes( iaa.SomeOf((1, 3), [ iaa.Dropout([0.05, 0.2]), # drop 5% or 20% of all pixels iaa.Sharpen((0.1, .8)), # sharpen the image # iaa.GaussianBlur(sigma=(2., 3.5)), iaa.OneOf([ iaa.GaussianBlur(sigma=(2., 3.5)), iaa.AverageBlur(k=(2, 5)), iaa.BilateralBlur(d=(7, 12), sigma_color=(10, 250), sigma_space=(10, 250)), iaa.MedianBlur(k=(3, 7)), ]), iaa.AddElementwise((-50, 50)), iaa.AdditiveGaussianNoise(scale=(0, 0.1 * 255)), iaa.JpegCompression(compression=(80, 95)), iaa.Multiply((0.5, 1.5)), iaa.MultiplyElementwise((0.5, 1.5)), iaa.ReplaceElementwise(0.05, [0, 255]), # iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", # children=iaa.WithChannels(2, iaa.Add((-10, 50)))), iaa.OneOf([ iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels(1, iaa.Add((-10, 50)))), iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels(2, iaa.Add((-10, 50)))), ]), ], random_order=True) ), # iaa.Fliplr(.5), # iaa.Flipud(.125), # # augment changing bboxes # self.bbox_augsometimes( # iaa.Affine( # # translate_px={"x": 40, "y": 60}, # scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, # translate_percent={"x": (-0.1, 0.1), "y": (-0.1, 0.1)}, # rotate=(-5, 5), # ) # ) ], random_order=True ) # torch.manual_seed(23) with open(list_file) as f: lines = f.readlines() if little_train: lines = lines[:64*8] for line in lines: splited = line.strip().split() self.fnames.append(splited[0]) self.num_samples = len(self.fnames)
transformed_image = transform(image=image) elif augmentation == 'salt_and_papper': transform = iaa.SaltAndPepper(0.1) transformed_image = transform(image=image) elif augmentation == 'coarse_salt_and_papper': transform = iaa.CoarseSaltAndPepper(0.05, size_percent=(0.01, 0.1)) transformed_image = transform(image=image) elif augmentation == 'impulse_noise': transform = iaa.ImpulseNoise(0.1) transformed_image = transform(image=image) elif augmentation == 'replace_elementwise': transform = iaa.ReplaceElementwise(0.1, [0, 255]) transformed_image = transform(image=image) elif augmentation == 'cutout': transform = iaa.Cutout(nb_iterations=5) transformed_image = transform(image=image) elif augmentation == 'solarize': transform = Solarize(always_apply=True) transformed_image = transform(image=image)['image'] elif augmentation == 'invert_img': transform = InvertImg(always_apply=True) transformed_image = transform(image=image)['image'] ## Artistic
iaa.OneOf([ iaa.imgcorruptlike.ShotNoise(severity=(1, 2)), iaa.imgcorruptlike.ImpulseNoise(severity=(1, 2)), iaa.imgcorruptlike.SpeckleNoise(severity=(1, 2)), iaa.imgcorruptlike.Spatter(severity=(1, 3)), iaa.AdditivePoissonNoise((1, 20), per_channel=0.5), iaa.AdditiveLaplaceNoise(scale=(0.005 * 255, 0.03 * 255), per_channel=0.5), iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.03 * 255), per_channel=0.5), iaa.BlendAlphaElementwise((0.0, 1.0), foreground=iaa.Add((-15, 15)), background=iaa.Multiply((0.8, 1.2))), iaa.ReplaceElementwise(0.05, iap.Normal(128, 0.4 * 128), per_channel=0.5), iaa.Dropout(p=(0, 0.05), per_channel=0.5), ])), # Brightness + Color + Contrast iaa.Sometimes( 0.5, iaa.OneOf([ iaa.Add(iap.Normal(iap.Choice([-30, 30]), 10)), iaa.Multiply((0.75, 1.25)), iaa.AddToBrightness((-35, 35)), iaa.MultiplyBrightness((0.85, 1.15)), iaa.MultiplyAndAddToBrightness(mul=(0.85, 1.15), add=(-10, 10)), iaa.BlendAlphaHorizontalLinearGradient(iaa.Add( iap.Normal(iap.Choice([-40, 40]), 10)), start_at=(0, 0.2),
def data_aug(images): seq = iaa.Sometimes( 0.5, iaa.Identity(), iaa.Sometimes( 0.5, iaa.Sequential([ iaa.Fliplr(0.5), iaa.Sometimes( 0.5, iaa.OneOf([ iaa.Add((-40, 40)), iaa.AddElementwise((-40, 40)), iaa.AdditiveGaussianNoise(scale=(0, 0.2 * 255)), iaa.AdditiveLaplaceNoise(scale=(0, 0.2 * 255)), iaa.AdditivePoissonNoise((0, 40)), iaa.MultiplyElementwise((0.5, 1.5)), iaa.ReplaceElementwise(0.1, [0, 255]), iaa.SaltAndPepper(0.1) ])), iaa.OneOf([ iaa.Cutout(nb_iterations=2, size=0.15, cval=0, squared=False), iaa.CoarseDropout((0.0, 0.05), size_percent=(0.02, 0.25)), iaa.Dropout(p=(0, 0.2)), iaa.CoarseSaltAndPepper(0.05, size_percent=(0.01, 0.1)), iaa.Cartoon(), iaa.BlendAlphaVerticalLinearGradient(iaa.TotalDropout(1.0), min_value=0.2, max_value=0.8), iaa.GaussianBlur(sigma=(0.0, 3.0)), iaa.AverageBlur(k=(2, 11)), iaa.MedianBlur(k=(3, 11)), iaa.BilateralBlur(d=(3, 10), sigma_color=(10, 250), sigma_space=(10, 250)), iaa.MotionBlur(k=20), iaa.AllChannelsCLAHE(), iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.75, 2.0)), iaa.Emboss(alpha=(0.0, 1.0), strength=(0.5, 1.5)), iaa.Affine(scale=(0.5, 1.5)), iaa.Affine(translate_px={ "x": (-20, 20), "y": (-20, 20) }), iaa.Affine(shear=(-16, 16)), iaa.pillike.EnhanceSharpness() ]), iaa.OneOf([ iaa.GammaContrast((0.5, 2.0)), iaa.SigmoidContrast(gain=(3, 10), cutoff=(0.4, 0.6)), iaa.LogContrast(gain=(0.6, 1.4)), iaa.LinearContrast((0.4, 1.6)), iaa.pillike.EnhanceBrightness() ]) ]), iaa.Sometimes(0.5, iaa.RandAugment(n=2, m=9), iaa.RandAugment(n=(0, 3), m=(0, 9))))) images = seq(images=images) return images
class AugmentationScheme: # Dictionary containing all possible augmentation functions Augmentations = { # Convert images to HSV, then increase each pixel's Hue (H), Saturation (S) or Value/lightness (V) [0, 1, 2] # value by an amount in between lo and hi: "HSV": lambda channel, lo, hi: iaa.WithColorspace( to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels(channel, iaa.Add((lo, hi)))), # The augmenter first transforms images to HSV color space, then adds random values (lo to hi) # to the H and S channels and afterwards converts back to RGB. # (independently per channel and the same value for all pixels within that channel) "Add_To_Hue_And_Saturation": lambda lo, hi: iaa.AddToHueAndSaturation((lo, hi), per_channel=True), # Increase each pixel’s channel-value (redness/greenness/blueness) [0, 1, 2] by value in between lo and hi: "Increase_Channel": lambda channel, lo, hi: iaa.WithChannels(channel, iaa.Add((lo, hi))), # Rotate each image’s channel [R=0, G=1, B=2] by value in between lo and hi degrees: "Rotate_Channel": lambda channel, lo, hi: iaa.WithChannels(channel, iaa.Affine(rotate=(lo, hi))), # Augmenter that never changes input images (“no operation”). "No_Operation": iaa.Noop(), # Pads images, i.e. adds columns/rows to them. Pads image by value in between lo and hi # percent relative to its original size (only accepts positive values in range[0, 1]): # If s_i is false, The value will be sampled once per image and used for all sides # (i.e. all sides gain/lose the same number of rows/columns) # NOTE: automatically resizes images back to their original size after it has augmented them. "Pad_Percent": lambda lo, hi, s_i: iaa.Pad( percent=(lo, hi), keep_size=True, sample_independently=s_i), # Pads images by a number of pixels between lo and hi # If s_i is false, The value will be sampled once per image and used for all sides # (i.e. all sides gain/lose the same number of rows/columns) "Pad_Pixels": lambda lo, hi, s_i: iaa.Pad( px=(lo, hi), keep_size=True, sample_independently=s_i), # Crops/cuts away pixels at the sides of the image. # Crops images by value in between lo and hi (only accepts positive values in range[0, 1]): # If s_i is false, The value will be sampled once per image and used for all sides # (i.e. all sides gain/lose the same number of rows/columns) # NOTE: automatically resizes images back to their original size after it has augmented them. "Crop_Percent": lambda lo, hi, s_i: iaa.Crop( percent=(lo, hi), keep_size=True, sample_independently=s_i), # Crops images by a number of pixels between lo and hi # If s_i is false, The value will be sampled once per image and used for all sides # (i.e. all sides gain/lose the same number of rows/columns) "Crop_Pixels": lambda lo, hi, s_i: iaa.Crop( px=(lo, hi), keep_size=True, sample_independently=s_i), # Flip/mirror percent (i.e 0.5) of the input images horizontally # The default probability is 0, so to flip all images, percent=1 "Flip_lr": iaa.Fliplr(1), # Flip/mirror percent (i.e 0.5) of the input images vertically # The default probability is 0, so to flip all images, percent=1 "Flip_ud": iaa.Flipud(1), # Completely or partially transform images to their superpixel representation. # Generate s_pix_lo to s_pix_hi superpixels per image. Replace each superpixel with a probability between # prob_lo and prob_hi with range[0, 1] (sampled once per image) by its average pixel color. "Superpixels": lambda prob_lo, prob_hi, s_pix_lo, s_pix_hi: iaa.Superpixels( p_replace=(prob_lo, prob_hi), n_segments=(s_pix_lo, s_pix_hi)), # Change images to grayscale and overlay them with the original image by varying strengths, # effectively removing alpha_lo to alpha_hi of the color: "Grayscale": lambda alpha_lo, alpha_hi: iaa.Grayscale(alpha=(alpha_lo, alpha_hi)), # Blur each image with a gaussian kernel with a sigma between sigma_lo and sigma_hi: "Gaussian_Blur": lambda sigma_lo, sigma_hi: iaa.GaussianBlur(sigma=(sigma_lo, sigma_hi) ), # Blur each image using a mean over neighbourhoods that have random sizes, # which can vary between h_lo and h_hi in height and w_lo and w_hi in width: "Average_Blur": lambda h_lo, h_hi, w_lo, w_hi: iaa.AverageBlur(k=((h_lo, h_hi), (w_lo, w_hi))), # Blur each image using a median over neighbourhoods that have a random size between lo x lo and hi x hi: "Median_Blur": lambda lo, hi: iaa.MedianBlur(k=(lo, hi)), # Sharpen an image, then overlay the results with the original using an alpha between alpha_lo and alpha_hi: "Sharpen": lambda alpha_lo, alpha_hi, lightness_lo, lightness_hi: iaa. Sharpen(alpha=(alpha_lo, alpha_hi), lightness=(lightness_lo, lightness_hi)), # Emboss an image, then overlay the results with the original using an alpha between alpha_lo and alpha_hi: "Emboss": lambda alpha_lo, alpha_hi, strength_lo, strength_hi: iaa.Emboss( alpha=(alpha_lo, alpha_hi), strength=(strength_lo, strength_hi)), # Detect edges in images, turning them into black and white images and # then overlay these with the original images using random alphas between alpha_lo and alpha_hi: "Detect_Edges": lambda alpha_lo, alpha_hi: iaa.EdgeDetect(alpha=(alpha_lo, alpha_hi)), # Detect edges having random directions between dir_lo and dir_hi (i.e (0.0, 1.0) = 0 to 360 degrees) in # images, turning the images into black and white versions and then overlay these with the original images # using random alphas between alpha_lo and alpha_hi: "Directed_edge_Detect": lambda alpha_lo, alpha_hi, dir_lo, dir_hi: iaa.DirectedEdgeDetect( alpha=(alpha_lo, alpha_hi), direction=(dir_lo, dir_hi)), # Add random values between lo and hi to images. In percent of all images the values differ per channel # (3 sampled value). In the rest of the images the value is the same for all channels: "Add": lambda lo, hi, percent: iaa.Add((lo, hi), per_channel=percent), # Adds random values between lo and hi to images, with each value being sampled per pixel. # In percent of all images the values differ per channel (3 sampled value). In the rest of the images # the value is the same for all channels: "Add_Element_Wise": lambda lo, hi, percent: iaa.AddElementwise( (lo, hi), per_channel=percent), # Add gaussian noise (aka white noise) to an image, sampled once per pixel from a normal # distribution N(0, s), where s is sampled per image and varies between lo and hi*255 for percent of all # images (sampled once for all channels) and sampled three (RGB) times (channel-wise) # for the rest from the same normal distribution: "Additive_Gaussian_Noise": lambda lo, hi, percent: iaa.AdditiveGaussianNoise(scale=(lo, hi), per_channel=percent), # Multiply in percent of all images each pixel with random values between lo and hi and multiply # the pixels in the rest of the images channel-wise, # i.e. sample one multiplier independently per channel and pixel: "Multiply": lambda lo, hi, percent: iaa.Multiply((lo, hi), per_channel=percent), # Multiply values of pixels with possibly different values for neighbouring pixels, # making each pixel darker or brighter. Multiply each pixel with a random value between lo and hi: "Multiply_Element_Wise": lambda lo, hi, percent: iaa.MultiplyElementwise( (0.5, 1.5), per_channel=0.5), # Augmenter that sets a certain fraction of pixels in images to zero. # Sample per image a value p from the range lo<=p<=hi and then drop p percent of all pixels in the image # (i.e. convert them to black pixels), but do this independently per channel in percent of all images "Dropout": lambda lo, hi, percent: iaa.Dropout(p=(lo, hi), per_channel=percent), # Augmenter that sets rectangular areas within images to zero. # Drop d_lo to d_hi percent of all pixels by converting them to black pixels, # but do that on a lower-resolution version of the image that has s_lo to s_hi percent of the original size, # Also do this in percent of all images channel-wise, so that only the information of some # channels is set to 0 while others remain untouched: "Coarse_Dropout": lambda d_lo, d_hi, s_lo, s_hi, percent: iaa.CoarseDropout( (d_lo, d_hi), size_percent=(s_hi, s_hi), per_channel=percent), # Augmenter that inverts all values in images, i.e. sets a pixel from value v to 255-v. # For c_percent of all images, invert all pixels in these images channel-wise with probability=i_percent # (per image). In the rest of the images, invert i_percent of all channels: "Invert": lambda i_percent, c_percent: iaa.Invert(i_percent, per_channel=c_percent), # Augmenter that changes the contrast of images. # Normalize contrast by a factor of lo to hi, sampled randomly per image # and for percent of all images also independently per channel: "Contrast_Normalisation": lambda lo, hi, percent: iaa.ContrastNormalization( (lo, hi), per_channel=percent), # Scale images to a value of lo to hi percent of their original size but do this independently per axis: "Scale": lambda x_lo, x_hi, y_lo, y_hi: iaa.Affine(scale={ "x": (x_lo, x_hi), "y": (y_lo, y_hi) }), # Translate images by lo to hi percent on x-axis and y-axis independently: "Translate_Percent": lambda x_lo, x_hi, y_lo, y_hi: iaa.Affine(translate_percent={ "x": (x_lo, x_hi), "y": (y_lo, y_hi) }), # Translate images by lo to hi pixels on x-axis and y-axis independently: "Translate_Pixels": lambda x_lo, x_hi, y_lo, y_hi: iaa.Affine(translate_px={ "x": (x_lo, x_hi), "y": (y_lo, y_hi) }), # Rotate images by lo to hi degrees: "Rotate": lambda lo, hi: iaa.Affine(rotate=(lo, hi)), # Shear images by lo to hi degrees: "Shear": lambda lo, hi: iaa.Affine(shear=(lo, hi)), # Augmenter that places a regular grid of points on an image and randomly moves the neighbourhood of # these point around via affine transformations. This leads to local distortions. # Distort images locally by moving points around, each with a distance v (percent relative to image size), # where v is sampled per point from N(0, z) z is sampled per image from the range lo to hi: "Piecewise_Affine": lambda lo, hi: iaa.PiecewiseAffine(scale=(lo, hi)), # Augmenter to transform images by moving pixels locally around using displacement fields. # Distort images locally by moving individual pixels around following a distortions field with # strength sigma_lo to sigma_hi. The strength of the movement is sampled per pixel from the range # alpha_lo to alpha_hi: "Elastic_Transformation": lambda alpha_lo, alpha_hi, sigma_lo, sigma_hi: iaa. ElasticTransformation(alpha=(alpha_lo, alpha_hi), sigma=(sigma_lo, sigma_hi)), # Weather augmenters are computationally expensive and will not work effectively on certain data sets # Augmenter to draw clouds in images. "Clouds": iaa.Clouds(), # Augmenter to draw fog in images. "Fog": iaa.Fog(), # Augmenter to add falling snowflakes to images. "Snowflakes": iaa.Snowflakes(), # Replaces percent of all pixels in an image by either x or y "Replace_Element_Wise": lambda percent, x, y: iaa.ReplaceElementwise(percent, [x, y]), # Adds laplace noise (somewhere between gaussian and salt and peeper noise) to an image, sampled once per pixel # from a laplace distribution Laplace(0, s), where s is sampled per image and varies between lo and hi*255 for # percent of all images (sampled once for all channels) and sampled three (RGB) times (channel-wise) # for the rest from the same laplace distribution: "Additive_Laplace_Noise": lambda lo, hi, percent: iaa.AdditiveLaplaceNoise(scale=(lo, hi), per_channel=percent), # Adds poisson noise (similar to gaussian but different distribution) to an image, sampled once per pixel from # a poisson distribution Poisson(s), where s is sampled per image and varies between lo and hi for percent of # all images (sampled once for all channels) and sampled three (RGB) times (channel-wise) # for the rest from the same poisson distribution: "Additive_Poisson_Noise": lambda lo, hi, percent: iaa.AdditivePoissonNoise(lam=(lo, hi), per_channel=percent), # Adds salt and pepper noise to an image, i.e. some white-ish and black-ish pixels. # Replaces percent of all pixels with salt and pepper noise "Salt_And_Pepper": lambda percent: iaa.SaltAndPepper(percent), # Adds coarse salt and pepper noise to image, i.e. rectangles that contain noisy white-ish and black-ish pixels # Replaces percent of all pixels with salt/pepper in an image that has lo to hi percent of the input image size, # then upscales the results to the input image size, leading to large rectangular areas being replaced. "Coarse_Salt_And_Pepper": lambda percent, lo, hi: iaa.CoarseSaltAndPepper(percent, size_percent=(lo, hi)), # Adds salt noise to an image, i.e white-ish pixels # Replaces percent of all pixels with salt noise "Salt": lambda percent: iaa.Salt(percent), # Adds coarse salt noise to image, i.e. rectangles that contain noisy white-ish pixels # Replaces percent of all pixels with salt in an image that has lo to hi percent of the input image size, # then upscales the results to the input image size, leading to large rectangular areas being replaced. "Coarse_Salt": lambda percent, lo, hi: iaa.CoarseSalt(percent, size_percent=(lo, hi)), # Adds Pepper noise to an image, i.e Black-ish pixels # Replaces percent of all pixels with Pepper noise "Pepper": lambda percent: iaa.Pepper(percent), # Adds coarse pepper noise to image, i.e. rectangles that contain noisy black-ish pixels # Replaces percent of all pixels with salt in an image that has lo to hi percent of the input image size, # then upscales the results to the input image size, leading to large rectangular areas being replaced. "Coarse_Pepper": lambda percent, lo, hi: iaa.CoarsePepper(percent, size_percent=(lo, hi)), # In an alpha blending, two images are naively mixed. E.g. Let A be the foreground image, B be the background # image and a is the alpha value. Each pixel intensity is then computed as a * A_ij + (1-a) * B_ij. # Images passed in must be a numpy array of type (height, width, channel) "Blend_Alpha": lambda image_fg, image_bg, alpha: iaa.blend_alpha( image_fg, image_bg, alpha), # Blur/Denoise an image using a bilateral filter. # Bilateral filters blur homogeneous and textured areas, while trying to preserve edges. # Blurs all images using a bilateral filter with max distance d_lo to d_hi with ranges for sigma_colour # and sigma space being define by sc_lo/sc_hi and ss_lo/ss_hi "Bilateral_Blur": lambda d_lo, d_hi, sc_lo, sc_hi, ss_lo, ss_hi: iaa.BilateralBlur( d=(d_lo, d_hi), sigma_color=(sc_lo, sc_hi), sigma_space=(ss_lo, ss_hi)), # Augmenter that sharpens images and overlays the result with the original image. # Create a motion blur augmenter with kernel size of (kernel x kernel) and a blur angle of either x or y degrees # (randomly picked per image). "Motion_Blur": lambda kernel, x, y: iaa.MotionBlur(k=kernel, angle=[x, y]), # Augmenter to apply standard histogram equalization to images (similar to CLAHE) "Histogram_Equalization": iaa.HistogramEqualization(), # Augmenter to perform standard histogram equalization on images, applied to all channels of each input image "All_Channels_Histogram_Equalization": iaa.AllChannelsHistogramEqualization(), # Contrast Limited Adaptive Histogram Equalization (CLAHE). This augmenter applies CLAHE to images, a form of # histogram equalization that normalizes within local image patches. # Creates a CLAHE augmenter with clip limit uniformly sampled from [cl_lo..cl_hi], i.e. 1 is rather low contrast # and 50 is rather high contrast. Kernel sizes of SxS, where S is uniformly sampled from [t_lo..t_hi]. # Sampling happens once per image. (Note: more parameters are available for further specification) "CLAHE": lambda cl_lo, cl_hi, t_lo, t_hi: iaa.CLAHE( clip_limit=(cl_lo, cl_hi), tile_grid_size_px=(t_lo, t_hi)), # Contrast Limited Adaptive Histogram Equalization (refer above), applied to all channels of the input images. # CLAHE performs histogram equalization within image patches, i.e. over local neighbourhoods "All_Channels_CLAHE": lambda cl_lo, cl_hi, t_lo, t_hi: iaa.AllChannelsCLAHE( clip_limit=(cl_lo, cl_hi), tile_grid_size_px=(t_lo, t_hi)), # Augmenter that changes the contrast of images using a unique formula (using gamma). # Multiplier for gamma function is between lo and hi,, sampled randomly per image (higher values darken image) # For percent of all images values are sampled independently per channel. "Gamma_Contrast": lambda lo, hi, percent: iaa.GammaContrast( (lo, hi), per_channel=percent), # Augmenter that changes the contrast of images using a unique formula (linear). # Multiplier for linear function is between lo and hi, sampled randomly per image # For percent of all images values are sampled independently per channel. "Linear_Contrast": lambda lo, hi, percent: iaa.LinearContrast( (lo, hi), per_channel=percent), # Augmenter that changes the contrast of images using a unique formula (using log). # Multiplier for log function is between lo and hi, sampled randomly per image. # For percent of all images values are sampled independently per channel. # Values around 1.0 lead to a contrast-adjusted images. Values above 1.0 quickly lead to partially broken # images due to exceeding the datatype’s value range. "Log_Contrast": lambda lo, hi, percent: iaa.LogContrast((lo, hi), per_channel=percent), # Augmenter that changes the contrast of images using a unique formula (sigmoid). # Multiplier for sigmoid function is between lo and hi, sampled randomly per image. c_lo and c_hi decide the # cutoff value that shifts the sigmoid function in horizontal direction (Higher values mean that the switch # from dark to light pixels happens later, i.e. the pixels will remain darker). # For percent of all images values are sampled independently per channel: "Sigmoid_Contrast": lambda lo, hi, c_lo, c_hi, percent: iaa.SigmoidContrast( (lo, hi), (c_lo, c_hi), per_channel=percent), # Augmenter that calls a custom (lambda) function for each batch of input image. # Extracts Canny Edges from images (refer to description in CO) # Good default values for min and max are 100 and 200 'Custom_Canny_Edges': lambda min_val, max_val: iaa.Lambda(func_images=CO.Edges( min_value=min_val, max_value=max_val)), } # AugmentationScheme objects require images and labels. # 'augs' is a list that contains all data augmentations in the scheme def __init__(self): self.augs = [iaa.Flipud(1)] def __call__(self, image): image = np.array(image) aug_scheme = iaa.Sometimes( 0.5, iaa.SomeOf(random.randrange(1, len(self.augs) + 1), self.augs, random_order=True)) aug_img = self.aug_scheme.augment_image(image) # fixes negative strides aug_img = aug_img[..., ::1] - np.zeros_like(aug_img) return aug_img