def YOLO(): """ Data augmentation model for YOLOv3 training """ return iaa.Sequential([ iaa.KeepSizeByResize( iaa.Affine( scale=iap.Normal(1, 0.125), translate_percent=0.1, cval=128, )), iaa.Fliplr(0.5), iaa.Resize({ "height": iap.Normal(1, 0.1), "width": iap.Normal(1, 0.1) }), iaa.Resize({ "longer-side": 416, "shorter-side": "keep-aspect-ratio" }), iaa.PadToFixedSize(416, 416, pad_cval=128), iaa.MultiplyHueAndSaturation(mul_hue=iap.Uniform(0, 2), mul_saturation=iap.Uniform(1 / 1.5, 1.5)), iaa.AssertShape((None, 416, 416, 3)), ])
} }) model = Sequential([ siamese_nets.get_layer('branch_model'), GramMatrix(kernel=siamese_nets.get_layer('head_model')), ]) #%% Init training preprocessing = iaa.Sequential([ iaa.Fliplr(0.5), iaa.Flipud(0.5), iaa.Affine(rotate=(-180, 180)), iaa.CropToFixedSize(224, 224, position='center'), iaa.PadToFixedSize(224, 224, position='center'), iaa.AssertShape((None, 224, 224, 3)), iaa.Lambda(lambda images_list, *_: (getattr( keras_applications, branch_model_name.lower()).preprocess_input( np.stack(images_list), data_format='channels_last'))), ]) batch_size = 64 callbacks = [ TensorBoard(output_folder, write_images=True, histogram_freq=1), ModelCheckpoint( str(output_folder / 'kernel_loss_best_loss_weights.h5'), save_best_only=True, save_weights_only=True, ), ModelCheckpoint( str(output_folder / 'kernel_loss_best_accuracy_weights.h5'), save_best_only=True,
.pipe(RandomAssignment("tray_name")) ) train_set = all_annotations.loc[lambda df: df.random_split == "train"] support_set = train_set.assign(crop_coordinates=lambda df: df[["x1", "y1", "x2", "y2"]].agg(list, axis=1)) val_set = all_annotations.loc[lambda df: df.random_split == "val"] #%% Init training query_preprocessing = iaa.Sequential( [ iaa.Resize({"longer-side": 416, "shorter-side": "keep-aspect-ratio"}), iaa.PadToFixedSize(416, 416), iaa.Fliplr(0.5), iaa.Flipud(0.5), iaa.MultiplyHueAndSaturation(mul_hue=iap.Uniform(0, 2), mul_saturation=iap.Uniform(1 / 1.5, 1.5)), iaa.AssertShape((None, 416, 416, 3)), ] ) support_preprocessing = iaa.Sequential( [ iaa.Fliplr(0.5), iaa.Flipud(0.5), iaa.Affine(rotate=(-180, 180)), iaa.Resize({"longer-side": 128, "shorter-side": "keep-aspect-ratio"}), iaa.PadToFixedSize(128, 128, pad_mode="symmetric"), iaa.MultiplyHueAndSaturation(mul_hue=iap.Uniform(0, 2), mul_saturation=iap.Uniform(1 / 1.5, 1.5)), iaa.AssertShape((None, 128, 128, 3)), ] )
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
def test_determinism(): reseed() images = [ ia.quokka(size=(128, 128)), ia.quokka(size=(64, 64)), ia.imresize_single_image(skimage.data.astronaut(), (128, 256)) ] keypoints = [ ia.KeypointsOnImage([ ia.Keypoint(x=20, y=10), ia.Keypoint(x=5, y=5), ia.Keypoint(x=10, y=43) ], shape=(50, 60, 3)) ] augs = [ iaa.Sequential([iaa.Fliplr(1.0), iaa.Flipud(1.0)]), iaa.SomeOf(1, [iaa.Fliplr(1.0), iaa.Flipud(1.0)]), iaa.OneOf([iaa.Fliplr(1.0), iaa.Flipud(1.0)]), iaa.Sometimes(1.0, iaa.Fliplr(1)), iaa.WithColorspace("HSV", children=iaa.Add((-50, 50))), iaa.WithChannels([0], iaa.Add((-50, 50))), iaa.Noop(name="Noop-nochange"), iaa.Lambda( func_images=lambda images, random_state, parents, hooks: images, func_heatmaps=lambda heatmaps, random_state, parents, hooks: heatmaps, func_keypoints=lambda keypoints_on_images, random_state, parents, hooks: keypoints_on_images, name="Lambda-nochange"), iaa.AssertLambda( func_images=lambda images, random_state, parents, hooks: True, func_heatmaps=lambda heatmaps, random_state, parents, hooks: True, func_keypoints=lambda keypoints_on_images, random_state, parents, hooks: True, name="AssertLambda-nochange"), iaa.AssertShape((None, None, None, 3), check_keypoints=False, name="AssertShape-nochange"), iaa.Scale((0.5, 0.9)), iaa.CropAndPad(px=(-50, 50)), iaa.Pad(px=(1, 50)), iaa.Crop(px=(1, 50)), iaa.Fliplr(1.0), iaa.Flipud(1.0), iaa.Superpixels(p_replace=(0.25, 1.0), n_segments=(16, 128)), iaa.ChangeColorspace(to_colorspace="GRAY"), iaa.Grayscale(alpha=(0.1, 1.0)), iaa.GaussianBlur(1.0), iaa.AverageBlur(5), iaa.MedianBlur(5), iaa.Convolve(np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])), iaa.Sharpen(alpha=(0.1, 1.0), lightness=(0.8, 1.2)), iaa.Emboss(alpha=(0.1, 1.0), strength=(0.8, 1.2)), iaa.EdgeDetect(alpha=(0.1, 1.0)), iaa.DirectedEdgeDetect(alpha=(0.1, 1.0), direction=(0.0, 1.0)), iaa.Add((-50, 50)), iaa.AddElementwise((-50, 50)), iaa.AdditiveGaussianNoise(scale=(0.1, 1.0)), iaa.Multiply((0.6, 1.4)), iaa.MultiplyElementwise((0.6, 1.4)), iaa.Dropout((0.3, 0.5)), iaa.CoarseDropout((0.3, 0.5), size_percent=(0.05, 0.2)), iaa.Invert(0.5), iaa.ContrastNormalization((0.6, 1.4)), iaa.Affine(scale=(0.7, 1.3), translate_percent=(-0.1, 0.1), rotate=(-20, 20), shear=(-20, 20), order=ia.ALL, mode=ia.ALL, cval=(0, 255)), iaa.PiecewiseAffine(scale=(0.1, 0.3)), iaa.ElasticTransformation(alpha=0.5) ] for aug in augs: aug_det = aug.to_deterministic() images_aug1 = aug_det.augment_images(images) images_aug2 = aug_det.augment_images(images) kps_aug1 = aug_det.augment_keypoints(keypoints) kps_aug2 = aug_det.augment_keypoints(keypoints) assert array_equal_lists(images_aug1, images_aug2), \ "Images not identical for %s" % (aug.name,) assert keypoints_equal(kps_aug1, kps_aug2), \ "Keypoints not identical for %s" % (aug.name,)