예제 #1
0
    def _augment_batch(self, images, corners):
        aug = iaa.SomeOf(
            (0, None),
            [
                iaa.KeepSizeByResize(
                    iaa.Affine(
                        translate_px={"x": (10, 30)},
                        rotate=(-5, 5),
                        mode="edge",
                        fit_output=True,
                    )),
                iaa.KeepSizeByResize(
                    iaa.Affine(shear=(-10, 10), mode="edge", fit_output=True)),
                iaa.AddToHueAndSaturation((-50, 50)),
                iaa.AverageBlur(k=(2, 5)),
            ],
            random_order=True,
        )

        # Convert array of corners to list of KeypointsOnImage instances for use with the augmenter.
        keypoints_from_corners = [
            KeypointsOnImage(
                [Keypoint(x=point[0], y=point[1]) for point in img_corners],
                shape=self.dim,
            ) for img_corners in corners
        ]

        images_augm, keypoints_augm = aug.augment(
            images=images, keypoints=keypoints_from_corners)

        # Convert augmented keypoints back to array of size (batch_size, 4, 2).
        corners_augm = np.array(
            [keypoints.to_xy_array() for keypoints in keypoints_augm])

        return images_augm, corners_augm
예제 #2
0
def chapter_augmenters_keepsizebyresize():
    # TODO add example images for heatmaps, segmaps
    fn_start = "size/keepsizebyresize"

    aug = iaa.KeepSizeByResize(iaa.Crop((20, 40), keep_size=False))
    run_and_save_augseq(fn_start + "_crop.jpg",
                        aug,
                        [ia.quokka(size=(120, 120)) for _ in range(4 * 2)],
                        cols=4,
                        rows=2)

    aug = iaa.KeepSizeByResize(iaa.Crop((20, 40), keep_size=False),
                               interpolation="nearest")
    run_and_save_augseq(fn_start + "_crop_nearest.jpg",
                        aug,
                        [ia.quokka(size=(120, 120)) for _ in range(4 * 2)],
                        cols=4,
                        rows=2)

    aug = iaa.KeepSizeByResize(
        iaa.Crop((20, 40), keep_size=False),
        interpolation=["nearest", "cubic"],
        interpolation_heatmaps=iaa.KeepSizeByResize.SAME_AS_IMAGES,
        interpolation_segmaps=iaa.KeepSizeByResize.NO_RESIZE)
    run_and_save_augseq(fn_start + "_various_augmentables.jpg",
                        aug,
                        [ia.quokka(size=(120, 120)) for _ in range(4 * 4)],
                        cols=4,
                        rows=4)
예제 #3
0
    def transform(self, in_data):
        augmenter = iaa.Sequential([
            iaa.LinearContrast(alpha=(0.8, 1.2)),
            iaa.WithColorspace(
                to_colorspace="HSV",
                from_colorspace="RGB",
                children=iaa.Sequential([
                    # SV
                    iaa.WithChannels(
                        (1, 2),
                        iaa.Multiply(mul=(0.8, 1.2), per_channel=True),
                    ),
                    # H
                    iaa.WithChannels(
                        (0, ),
                        iaa.Multiply(mul=(0.95, 1.05), per_channel=True),
                    ),
                ]),
            ),
            iaa.GaussianBlur(sigma=(0, 1.0)),
            iaa.KeepSizeByResize(children=iaa.Resize((0.25, 1.0))),
        ])

        augmenter = augmenter.to_deterministic()
        for index in self._indices:
            in_data[index] = augmenter.augment_image(in_data[index])
예제 #4
0
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)),
    ])
예제 #5
0
def get_fg_augmentation():
    seq = iaa.Sequential([
        iaa.Resize({
            'height': 'keep',
            'width': (0.9, 1.1)
        }),
        iaa.KeepSizeByResize(iaa.Rotate((-15, 15), fit_output=True))
    ])
    return seq
예제 #6
0
def getImageAug():
    seq = iaa.Sequential(
        [
            iaa.SomeOf(
                (0, 2),
                [
                    iaa.Identity(),
                    iaa.AverageBlur(k=((3, 5), (5, 7))),
                    iaa.Rotate((-45, 45)),
                    iaa.Affine(scale=(0.5, 0.95)),
                    iaa.Multiply((0.50, 1.1))
                    #,iaa.BlendAlphaRegularGrid(nb_rows=(4, 6), nb_cols=(1, 4),
                    #                        foreground=iaa.Multiply(0.0))
                    #,iaa.Cartoon()
                    ,
                    iaa.Cutout(
                        nb_iterations=(1, 3), size=0.2, squared=False, cval=0),
                    iaa.Affine(shear=(-48, 48)),
                    iaa.Affine(translate_px={
                        "x": (-42, 42),
                        "y": (-36, 36)
                    }),
                    iaa.KeepSizeByResize(
                        iaa.Resize({
                            "height": (0.70, 0.90),
                            "width": (0.70, 0.90)
                        })),
                    iaa.CropAndPad(percent=(-0.2, 0.2))
                    #,iaa.PiecewiseAffine(scale=(0.01, 0.05))
                    ,
                    iaa.PerspectiveTransform(scale=(0.01, 0.1))
                    #,iaa.WithPolarWarping(iaa.CropAndPad(percent=(-0.1, 0.1)))
                    #,iaa.ElasticTransformation(alpha=(0, 3.0), sigma=0.5)
                ])
            #,iaa.SaveDebugImageEveryNBatches(folder_path, 100)
        ],
        random_order=True)
    return seq
예제 #7
0
 def _augment_rgb(rgb):
     augmenter = iaa.Sequential([
         iaa.LinearContrast(alpha=(0.8, 1.2)),
         iaa.WithColorspace(
             to_colorspace="HSV",
             from_colorspace="RGB",
             children=iaa.Sequential([
                 # SV
                 iaa.WithChannels(
                     (1, 2),
                     iaa.Multiply(mul=(0.8, 1.2), per_channel=True),
                 ),
                 # H
                 iaa.WithChannels(
                     (0, ),
                     iaa.Multiply(mul=(0.95, 1.05), per_channel=True),
                 ),
             ]),
         ),
         iaa.GaussianBlur(sigma=(0, 1.0)),
         iaa.KeepSizeByResize(children=iaa.Resize((0.25, 1.0))),
     ])
     return augmenter.augment_image(rgb)
예제 #8
0
seq = iaa.Sequential([
    iaa.SomeOf((0, 2), [
        iaa.Identity(),
        iaa.AverageBlur(k=((3, 5), (5, 7))),
        iaa.Rotate((-45, 45)),
        iaa.Affine(scale=(0.5, 0.95)),
        iaa.Multiply((0.50, 1.1)),
        iaa.Cutout(nb_iterations=(1, 3), size=0.2, squared=False, cval=0),
        iaa.Affine(shear=(-48, 48)),
        iaa.Affine(translate_px={
            "x": (-42, 42),
            "y": (-36, 36)
        }),
        iaa.KeepSizeByResize(
            iaa.Resize({
                "height": (0.70, 0.90),
                "width": (0.70, 0.90)
            })),
        iaa.CropAndPad(percent=(-0.2, 0.2)),
        iaa.PerspectiveTransform(scale=(0.01, 0.1))
    ])
],
                     random_order=True)


def get_recent_model_dir(model_root_dir):
    import os, glob
    from pathlib import Path
    model_root_dir = "models"
    paths = sorted(Path(model_root_dir).iterdir(), key=os.path.getmtime)[::-1]
    for p in paths:
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
예제 #10
0
    def augmentation_of_image(self, test_image, output_path):
        self.test_image = test_image
        self.output_path = output_path
        #define the Augmenters

        #properties: A range of values signifies that one of these numbers is randmoly chosen for every augmentation for every batch

        # Apply affine transformations to each image.
        rotate = iaa.Affine(rotate=(-90, 90))
        scale = iaa.Affine(scale={
            "x": (0.5, 0.9),
            "y": (0.5, 0.9)
        })
        translation = iaa.Affine(translate_percent={
            "x": (-0.15, 0.15),
            "y": (-0.15, 0.15)
        })
        shear = iaa.Affine(shear=(-2, 2))
        #plagio parallhlogrammo wihthin a range (-8,8)
        zoom = iaa.PerspectiveTransform(
            scale=(0.01, 0.15),
            keep_size=True)  # do not change the output size of the image
        h_flip = iaa.Fliplr(1.0)
        # flip horizontally all images (100%)
        v_flip = iaa.Flipud(1.0)
        #flip vertically all images
        padding = iaa.KeepSizeByResize(
            iaa.CropAndPad(percent=(0.05, 0.25))
        )  #positive values correspond to padding 5%-25% of the image,but keeping the origial output size of the new image

        #More augmentations
        blur = iaa.GaussianBlur(
            sigma=(0, 1.22)
        )  # blur images with a sigma 0-2,a number ofthis range is randomly chosen everytime.Low values suggested for this application
        contrast = iaa.contrast.LinearContrast((0.75, 1.5))
        #change the contrast by a factor of 0.75 and 1.5 sampled randomly per image
        contrast_channels = iaa.LinearContrast(
            (0.75, 1.5), per_channel=True
        )  #and for 50% of all images also independently per channel:
        sharpen = iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5))
        #sharpen with an alpha from 0(no sharpening) - 1(full sharpening) and change the lightness form 0.75 to 1.5
        gauss_noise = iaa.AdditiveGaussianNoise(
            scale=0.111 * 255, per_channel=True
        )  #some random gaussian noise might occur in cell images,especially when image quality is poor
        laplace_noise = iaa.AdditiveLaplaceNoise(
            scale=(0, 0.111 * 255)
        )  #we choose to be in a small range, as it is logical for training the cell images

        #Brightness
        brightness = iaa.Multiply(
            (0.35, 1.65
             ))  #change brightness between 35% or 165% of the original image
        brightness_channels = iaa.Multiply(
            (0.5, 1.5), per_channel=0.75
        )  # change birghtness for 25% of images.For the remaining 75%, change it, but also channel-wise.

        #CHANNELS (RGB)=(Red,Green,Blue)
        red = iaa.WithChannels(0, iaa.Add(
            (10,
             100)))  #increase each Red-pixels value within the range 10-100
        red_rot = iaa.WithChannels(0, iaa.Affine(
            rotate=(0, 45)))  #rotate each image's red channel by 0-45 degrees
        green = iaa.WithChannels(1, iaa.Add(
            (10,
             100)))  #increase each Green-pixels value within the range 10-100
        green_rot = iaa.WithChannels(1, iaa.Affine(
            rotate=(0,
                    45)))  #rotate each image's green channel by 0-45 degrees
        blue = iaa.WithChannels(2, iaa.Add(
            (10,
             100)))  #increase each Blue-pixels value within the range 10-100
        blue_rot = iaa.WithChannels(2, iaa.Affine(
            rotate=(0, 45)))  #rotate each image's blue channel by 0-45 degrees

        #colors
        channel_shuffle = iaa.ChannelShuffle(1.0)
        #shuffle all images of the batch
        grayscale = iaa.Grayscale(1.0)
        hue_n_saturation = iaa.MultiplyHueAndSaturation(
            (0.5, 1.5), per_channel=True
        )  #change hue and saturation with this range of values for different values
        add_hue_saturation = iaa.AddToHueAndSaturation(
            (-50, 50),
            per_channel=True)  #add more hue and saturation to its pixels
        #Quantize colors using k-Means clustering
        kmeans_color = iaa.KMeansColorQuantization(
            n_colors=(4, 16)
        )  #quantizes to k means 4 to 16 colors (randomly chosen). Quantizes colors up to 16 colors

        #Alpha Blending
        blend = iaa.AlphaElementwise((0, 1.0), iaa.Grayscale((0, 1.0)))
        #blend depending on which value is greater

        #Contrast augmentors
        clahe = iaa.CLAHE(tile_grid_size_px=((3, 21), [
            0, 2, 3, 4, 5, 6, 7
        ]))  #create a clahe contrast augmentor H=(3,21) and W=(0,7)
        histogram = iaa.HistogramEqualization(
        )  #performs histogram equalization

        #Augmentation list of metadata augmentors
        OneofRed = iaa.OneOf([red])
        OneofGreen = iaa.OneOf([green])
        OneofBlue = iaa.OneOf([blue])
        contrast_n_shit = iaa.OneOf(
            [contrast, brightness, brightness_channels])
        SomeAug = iaa.SomeOf(
            2, [rotate, scale, translation, shear, h_flip, v_flip],
            random_order=True)
        SomeClahe = iaa.SomeOf(
            2, [
                clahe,
                iaa.CLAHE(clip_limit=(1, 10)),
                iaa.CLAHE(tile_grid_size_px=(3, 21)),
                iaa.GammaContrast((0.5, 2.0)),
                iaa.AllChannelsCLAHE(),
                iaa.AllChannelsCLAHE(clip_limit=(1, 10), per_channel=True)
            ],
            random_order=True)  #Random selection from clahe augmentors
        edgedetection = iaa.OneOf([
            iaa.EdgeDetect(alpha=(0, 0.7)),
            iaa.DirectedEdgeDetect(alpha=(0, 0.7), direction=(0.0, 1.0))
        ])
        # Search in some images either for all edges or for directed edges.These edges are then marked in a black and white image and overlayed with the original image using an alpha of 0 to 0.7.
        canny_filter = iaa.OneOf([
            iaa.Canny(),
            iaa.Canny(alpha=(0.5, 1.0), sobel_kernel_size=[3, 7])
        ])
        #choose one of the 2 canny filter options
        OneofNoise = iaa.OneOf([blur, gauss_noise, laplace_noise])
        Color_1 = iaa.OneOf([
            channel_shuffle, grayscale, hue_n_saturation, add_hue_saturation,
            kmeans_color
        ])
        Color_2 = iaa.OneOf([
            channel_shuffle, grayscale, hue_n_saturation, add_hue_saturation,
            kmeans_color
        ])
        Flip = iaa.OneOf([histogram, v_flip, h_flip])

        #Define the augmentors used in the DA
        Augmentors = [
            SomeAug, SomeClahe, SomeClahe, edgedetection, sharpen,
            canny_filter, OneofRed, OneofGreen, OneofBlue, OneofNoise, Color_1,
            Color_2, Flip, contrast_n_shit
        ]

        for i in range(0, 14):
            img = cv2.imread(test_image)  #read you image
            images = np.array(
                [img for _ in range(14)], dtype=np.uint8
            )  # 12 is the size of the array that will hold 8 different images
            images_aug = Augmentors[i].augment_images(
                images
            )  #alternate between the different augmentors for a test image
            cv2.imwrite(
                os.path.join(output_path,
                             test_image + "new" + str(i) + '.jpg'),
                images_aug[i])  #write all changed images
        iaa.ContrastNormalization((0.9, 1.1)),
        # Add gaussian noise.
        # For 50% of all images, we sample the noise once per pixel.
        # For the other 50% of all images, we sample the noise per pixel AND
        # channel. This can change the color (not only brightness) of the
        # pixels.
        iaa.AdditiveGaussianNoise(
            loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5),
        # Make some images brighter and some darker.
        # In 20% of all cases, we sample the multiplier once per channel,
        # which can end up changing the color of the images.
        iaa.Multiply((0.9, 1.1), per_channel=0.2),
        # Apply affine transformations to each image.
        # Scale/zoom them, translate/move them, rotate them and shear them.
        iaa.KeepSizeByResize(
            iaa.Affine(scale={
                "x": (0.8, 1.2),
                "y": (0.8, 1.2)
            },
                       rotate=(-10, 10),
                       shear=(-8, 8),
                       mode="symmetric"))
        #translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)},
    ],
    random_order=True)  # apply augmenters in random order

for j in range(4):
    images_aug = seq.augment_images(imgs)
    for i in range(images_aug.shape[0]):
        imageio.imwrite('G:\\final_dataset\\paper\\{}_{}.png'.format(j, i),
                        images_aug[i])
seq_1 = iaa.Sequential(
        [
        # apply only 2 of the following
        iaa.SomeOf(3, [
            sometimes(iaa.Fliplr(0.99)),
            sometimes(iaa.Flipud(0.99)),
            sometimes(iaa.Affine(scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, order=1, backend="cv2")),
            sometimes(iaa.Affine(translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, order=1, backend="cv2")),
            sometimes(iaa.Affine(rotate=(-90, 90), order=1, backend="cv2")),
            sometimes(iaa.Affine(shear=(-25, 25), order=1, backend="cv2")),
            sometimes(iaa.ElasticTransformation(alpha=50.0, sigma=5.0)),
            # radomly crop some part of image to add more BG class in data
            sometimes(iaa.CropToFixedSize(width=512, height=512, position='uniform')),
            iaa.OneOf([
            sometimes(iaa.KeepSizeByResize(
                                 iaa.Crop(percent=(0.05, 0.25), keep_size=False),
                                 interpolation='linear')),
            sometimes(iaa.KeepSizeByResize(
                                iaa.CropAndPad(percent=(0.05, 0.25), pad_mode=["constant", "edge"], pad_cval=(0, 255)),
                                interpolation="linear"))
            ]),
            ], random_order=True),
        ], random_order=True)
''' Noisy Data Aug'''
seq_2 = iaa.Sequential(
        [
        iaa.OneOf(
            [   
            # Blur each image using a median over neihbourhoods that have a random size between 3x3 and 7x7
            sometimes(iaa.MedianBlur(k=(3, 7))),
            # blur images using gaussian kernels with random value (sigma) from the interval [a, b]
예제 #13
0

        # iaa.Crop(px=(0, 70)),
        # iaa.Affine(rotate=(-25, 25)),
        # iaa.Affine(translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)})

        # ],random_order=True),

        ], random_order=True)
    ''' SSD Upscale Crop'''
    # randomly choose positions in image
    positions = ['center','left-top', 'left-center', 'left-bottom', 'center-top',
                 'center-bottom', 'right-top', 'right-center', 'right-bottom']
    SSD = iaa.Sequential([

        iaa.KeepSizeByResize(iaa.CropToFixedSize(width=470, height=370, position=positions[0]), interpolation="linear")

        ], random_order=True)
    #%

    #for i in range(10):
    image_aug, bbs_aug = SSD.augment(image=img, bounding_boxes=bbs)
    #   disregard bounding boxes which have fallen out of image pane   
    bbs_aug = bbs_aug.remove_out_of_image()
    #   clip bounding boxes which are partially outside of image pane
    bbs_aug = bbs_aug.clip_out_of_image()

    #ia.imshow(bbs_aug.draw_on_image(image_aug, size=5))

    '''
    Now updata the dictionary wiht new augmented values