Пример #1
0
def chapter_augmenters_blendalphasimplexnoise():
    fn_start = "blend/blendalphasimplexnoise"

    aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0))
    run_and_save_augseq(fn_start + ".jpg",
                        aug,
                        [ia.quokka(size=(128, 128)) for _ in range(4 * 2)],
                        cols=4,
                        rows=2)

    aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), upscale_method="nearest")
    run_and_save_augseq(fn_start + "_nearest.jpg",
                        aug,
                        [ia.quokka(size=(128, 128)) for _ in range(4 * 2)],
                        cols=4,
                        rows=2)

    aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), upscale_method="linear")
    run_and_save_augseq(fn_start + "_linear.jpg",
                        aug,
                        [ia.quokka(size=(128, 128)) for _ in range(4 * 2)],
                        cols=4,
                        rows=2)

    aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0),
                                sigmoid_thresh=iap.Normal(10.0, 5.0))
    run_and_save_augseq(fn_start + "_sigmoid_thresh_normal.jpg",
                        aug,
                        [ia.quokka(size=(128, 128)) for _ in range(4 * 2)],
                        cols=4,
                        rows=2)
Пример #2
0
def chapter_alpha_masks_introduction():
    # -----------------------------------------
    # example introduction
    # -----------------------------------------
    import imgaug as ia
    from imgaug import augmenters as iaa

    ia.seed(2)

    # Example batch of images.
    # The array has shape (8, 128, 128, 3) and dtype uint8.
    images = np.array([ia.quokka(size=(128, 128)) for _ in range(8)],
                      dtype=np.uint8)

    seqs = [
        iaa.Alpha((0.0, 1.0), first=iaa.MedianBlur(11), per_channel=True),
        iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(1.0), per_channel=False),
        iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(1.0),
                              second=iaa.ContrastNormalization((0.5, 2.0)),
                              per_channel=0.5),
        iaa.FrequencyNoiseAlpha(first=iaa.Affine(rotate=(-10, 10),
                                                 translate_px={
                                                     "x": (-4, 4),
                                                     "y": (-4, 4)
                                                 }),
                                second=iaa.AddToHueAndSaturation((-40, 40)),
                                per_channel=0.5),
        iaa.SimplexNoiseAlpha(
            first=iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(1.0),
                                        second=iaa.ContrastNormalization(
                                            (0.5, 2.0)),
                                        per_channel=True),
            second=iaa.FrequencyNoiseAlpha(exponent=(-2.5, -1.0),
                                           first=iaa.Affine(rotate=(-10, 10),
                                                            translate_px={
                                                                "x": (-4, 4),
                                                                "y": (-4, 4)
                                                            }),
                                           second=iaa.AddToHueAndSaturation(
                                               (-40, 40)),
                                           per_channel=True),
            per_channel=True,
            aggregation_method="max",
            sigmoid=False)
    ]

    cells = []
    for seq in seqs:
        images_aug = seq.augment_images(images)
        cells.extend(images_aug)

    # ------------

    save("alpha", "introduction.jpg", grid(cells, cols=8, rows=5))
Пример #3
0
def main():
    nb_rows = 8
    nb_cols = 8
    h, w = (128, 128)
    sample_size = 128

    noise_gens = [
        iap.SimplexNoise(),
        iap.FrequencyNoise(exponent=-4, size_px_max=sample_size, upscale_method="cubic"),
        iap.FrequencyNoise(exponent=-2, size_px_max=sample_size, upscale_method="cubic"),
        iap.FrequencyNoise(exponent=0, size_px_max=sample_size, upscale_method="cubic"),
        iap.FrequencyNoise(exponent=2, size_px_max=sample_size, upscale_method="cubic"),
        iap.FrequencyNoise(exponent=4, size_px_max=sample_size, upscale_method="cubic"),
        iap.FrequencyNoise(exponent=(-4, 4), size_px_max=(4, sample_size), upscale_method=["nearest", "linear", "cubic"]),
        iap.IterativeNoiseAggregator(
            other_param=iap.FrequencyNoise(exponent=(-4, 4), size_px_max=(4, sample_size), upscale_method=["nearest", "linear", "cubic"]),
            iterations=(1, 3),
            aggregation_method=["max", "avg"]
        ),
        iap.IterativeNoiseAggregator(
            other_param=iap.Sigmoid(
                iap.FrequencyNoise(exponent=(-4, 4), size_px_max=(4, sample_size), upscale_method=["nearest", "linear", "cubic"]),
                threshold=(-10, 10),
                activated=0.33,
                mul=20,
                add=-10
            ),
            iterations=(1, 3),
            aggregation_method=["max", "avg"]
        )
    ]

    samples = [[] for _ in range(len(noise_gens))]
    for _ in range(nb_rows * nb_cols):
        for i, noise_gen in enumerate(noise_gens):
            samples[i].append(noise_gen.draw_samples((h, w)))

    rows = [np.hstack(row) for row in samples]
    grid = np.vstack(rows)
    misc.imshow((grid*255).astype(np.uint8))

    images = [ia.quokka_square(size=(128, 128)) for _ in range(16)]
    seqs = [
        iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(1.0)),
        iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(1.0), per_channel=True),
        iaa.FrequencyNoiseAlpha(first=iaa.EdgeDetect(1.0)),
        iaa.FrequencyNoiseAlpha(first=iaa.EdgeDetect(1.0), per_channel=True)
    ]
    images_aug = []

    for seq in seqs:
        images_aug.append(np.hstack(seq.augment_images(images)))
    images_aug = np.vstack(images_aug)
    misc.imshow(images_aug)
Пример #4
0
def get_augmentation_sequence():
    sometimes = lambda aug: iaa.Sometimes(0.5, aug)
    seq = iaa.Sequential([
        sometimes(iaa.Fliplr(0.5)),
        iaa.Sometimes(0.1, iaa.Add((-70, 70))),
        sometimes(
            iaa.Affine(scale={
                "x": (0.8, 1.2),
                "y": (0.8, 1.2)
            }  # scale images to 80-120% of their size, individually per axis
                       )),
        sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.01))),
        iaa.Sometimes(
            0.1,
            iaa.SimplexNoiseAlpha(iaa.OneOf(
                [iaa.Add((150, 255)),
                 iaa.Add((-100, 100))]),
                                  sigmoid_thresh=5)),
        iaa.Sometimes(
            0.1,
            iaa.OneOf([
                iaa.CoarseDropout((0.01, 0.15), size_percent=(0.02, 0.08)),
                iaa.CoarseSaltAndPepper(p=0.2, size_percent=0.01),
                iaa.CoarseSalt(p=0.2, size_percent=0.02)
            ])),
        iaa.Sometimes(0.25, slice_thickness_augmenter)
    ])
    return seq
Пример #5
0
def augment_sequential():
    return iaa.Sequential([
        iaa.SomeOf(
            (0, 3),
            [  # 每次使用0~3个Augmenter来处理图片
                iaa.DirectedEdgeDetect(alpha=(0.0, 0.3),
                                       direction=(0.0, 1.0)),  # 边缘检测,只检测某些方向的
                iaa.OneOf([  # 每次以下Augmenters中选择一个来变换
                    iaa.GaussianBlur((0, 1.0)),
                    iaa.AverageBlur(k=(2, 3)),
                ]),
                iaa.Sharpen(alpha=(0, 0.5), lightness=(0.75, 1.0)),  # 锐化
                iaa.SimplexNoiseAlpha(
                    iaa.OneOf([
                        iaa.EdgeDetect(alpha=(0.0, 0.5)),
                        iaa.DirectedEdgeDetect(alpha=(0.0, 0.5),
                                               direction=(0.5, 1.0)),
                    ])),
                iaa.AdditiveGaussianNoise(
                    loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5),
                iaa.OneOf([
                    iaa.Dropout((0.01, 0.3), per_channel=0.5),  # 随机丢弃像素
                    iaa.CoarseDropout((0.03, 0.15),
                                      size_percent=(0.02, 0.1),
                                      per_channel=0.2),  # 随机丢弃某位置某通道像素
                ]),
                iaa.Add((-50, 50), per_channel=0.5),  # 像素值成比例增加/减小(特指亮度)
                iaa.AddToHueAndSaturation((-50, 50)),  # 增加色相、饱和度
                iaa.LinearContrast((0.8, 1.2), per_channel=0.5),
                iaa.Grayscale(alpha=(0.0, 1.0)),
            ])
    ])
    def add_simplex_noise(self, prob=0.5, multiplicator=0.7):
        if self._sequential_augmentation is None:
            self._sequential_augmentation = iaa.Sequential()

        self._sequential_augmentation.add(iaa.Sometimes(prob,
                                                        iaa.SimplexNoiseAlpha(iaa.Multiply(multiplicator),
                                                                              upscale_method='linear')))
 def augmentation2(image, mask):
     sometimes = lambda aug: iaa.Sometimes(0.5, aug)
     seq = iaa.Sequential(
         [
             sometimes(
                 iaa.CropAndPad(percent=(-0.05, 0.1),
                                pad_mode=ia.ALL,
                                pad_cval=(0, 255))),
             iaa.SomeOf(
                 (0, 5),
                 [
                     sometimes(
                         iaa.Superpixels(p_replace=(0, 1.0),
                                         n_segments=(20, 200))),
                     # convert images into their superpixel representation
                     iaa.OneOf([
                         iaa.GaussianBlur(
                             (0, 3.0)
                         ),  # blur images with a sigma between 0 and 3.0
                         iaa.AverageBlur(k=(2, 7)),
                         # blur image using local means with kernel sizes between 2 and 7
                         iaa.MedianBlur(k=(3, 11)),
                     ]),
                     iaa.Sharpen(alpha=(0, 1.0),
                                 lightness=(0.75, 1.5)),  # sharpen images
                     iaa.Emboss(alpha=(0, 1.0),
                                strength=(0, 2.0)),  # emboss images
                     iaa.SimplexNoiseAlpha(
                         iaa.OneOf([
                             iaa.EdgeDetect(alpha=(0.5, 1.0)),
                             iaa.DirectedEdgeDetect(alpha=(0.5, 1.0),
                                                    direction=(0.0, 1.0)),
                         ])),
                     iaa.AdditiveGaussianNoise(
                         loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5),
                     # add gaussian noise to images
                     iaa.OneOf([
                         iaa.Dropout(
                             (0.01, 0.1), per_channel=0.5
                         ),  # randomly remove up to 10% of the pixels
                         iaa.CoarseDropout((0.03, 0.15),
                                           size_percent=(0.02, 0.05),
                                           per_channel=0.2),
                     ]),
                     iaa.Invert(0.05,
                                per_channel=True),  # invert color channels
                     iaa.Add((-10, 10), per_channel=0.5),
                     iaa.AddToHueAndSaturation(
                         (-20, 20)),  # change hue and saturation
                     iaa.OneOf([
                         iaa.Multiply((0.5, 1.5), per_channel=0.5),
                     ]),
                     iaa.Grayscale(alpha=(0.0, 1.0)),
                 ],
                 random_order=True)
         ],
         random_order=True)
     image_heavy, mask_heavy = seq(images=image, segmentation_maps=mask)
     return image_heavy, mask_heavy
def generateAugSeq():
    sometimes = lambda aug: iaa.Sometimes(0.5, aug)

    return iaa.Sequential([
        sometimes(
            iaa.CropAndPad(
                percent=(-0.05, 0.1), pad_mode=ia.ALL, pad_cval=(0, 255))),
        sometimes(
            iaa.Affine(scale={
                "x": (0.8, 1.2),
                "y": (0.8, 1.2)
            },
                       translate_percent={
                           "x": (-0.2, 0.2),
                           "y": (-0.2, 0.2)
                       },
                       order=[0, 1],
                       cval=(0, 255),
                       mode=ia.ALL)),
        iaa.SomeOf((0, 5), [
            sometimes(iaa.Superpixels(p_replace=(0, 1.0),
                                      n_segments=(20, 200))),
            iaa.OneOf([
                iaa.GaussianBlur((0, 3.0)),
                iaa.AverageBlur(k=(2, 7)),
                iaa.MedianBlur(k=(3, 11)),
            ]),
            iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)),
            iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)),
            iaa.SimplexNoiseAlpha(
                iaa.OneOf([
                    iaa.EdgeDetect(alpha=(0.5, 1.0)),
                    iaa.DirectedEdgeDetect(alpha=(0.5, 1.0),
                                           direction=(0.0, 1.0)),
                ])),
            iaa.AdditiveGaussianNoise(
                loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5),
            iaa.OneOf([
                iaa.Dropout((0.01, 0.1), per_channel=0.5),
                iaa.CoarseDropout(
                    (0.03, 0.15), size_percent=(0.02, 0.05), per_channel=0.2),
            ]),
            iaa.Invert(0.05, per_channel=True),
            iaa.Add((-10, 10), per_channel=0.5),
            iaa.AddToHueAndSaturation((-20, 20)),
            iaa.OneOf([
                iaa.Multiply((0.5, 1.5), per_channel=0.5),
                iaa.FrequencyNoiseAlpha(exponent=(-4, 0),
                                        first=iaa.Multiply(
                                            (0.5, 1.5), per_channel=True),
                                        second=iaa.ContrastNormalization(
                                            (0.5, 2.0)))
            ]),
            iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5),
            iaa.Grayscale(alpha=(0.0, 1.0)),
        ],
                   random_order=True)
    ],
                          random_order=True)
Пример #9
0
def method2(): ##simplex noise alpha
    ia.seed(1)
    seq = iaa.Sequential([
        iaa.SimplexNoiseAlpha(
            first=iaa.Multiply(iaa.Choice([0.5, 1.5]), per_channel=False)
        )
    ])
    return seq
Пример #10
0
 def logic(self, image):
     for param in self.augmentation_params:
         self.augmentation_data.append([
             str(param.augmentation_value),
             iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(
                 1.0)).to_deterministic().augment_image(image),
             param.detection_tag
         ])
Пример #11
0
 def __init__(self):
     self.simplex_noise = iaa.Sometimes(
         .9,
         iaa.SimplexNoiseAlpha(first=iaa.Sometimes(
             .7, iaa.MedianBlur(k=iaa.Choice([0, 5]))),
                               second=iaa.Sometimes(
                                   .7,
                                   iaa.Multiply(iaa.Choice([0.5, 1.5]),
                                                per_channel=False)),
                               upscale_method="linear"))
def get_augmentations():
    # Sometimes(0.5, ...) applies the given augmenter in 50% of all cases,
    # e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second image.
    sometimes = lambda aug: iaa.Sometimes(0.5, aug)

    # Define our sequence of augmentation steps that will be applied to every image
    # All augmenters with per_channel=0.5 will sample one value _per image_
    # in 50% of all cases. In all other cases they will sample new values
    # _per channel_.
    seq = iaa.Sequential([
            # execute 0 to 5 of the following (less important) augmenters per image
            # don't execute all of them, as that would often be way too strong
            iaa.SomeOf((0, 5),
                [
                    iaa.OneOf([
                        iaa.GaussianBlur((0, 3.0)), # blur images with a sigma between 0 and 3.0
                        iaa.AverageBlur(k=(2, 7)), # blur image using local means with kernel sizes between 2 and 7
                        iaa.MedianBlur(k=(3, 11)), # blur image using local medians with kernel sizes between 2 and 7
                    ]),
                    iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)), # sharpen images
                    iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), # emboss images
                    # search either for all edges or for directed edges,
                    # blend the result with the original image using a blobby mask
                    iaa.SimplexNoiseAlpha(iaa.OneOf([
                        iaa.EdgeDetect(alpha=(0.5, 1.0)),
                        iaa.DirectedEdgeDetect(alpha=(0.5, 1.0), direction=(0.0, 1.0)),
                    ])),
                    iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # add gaussian noise to images
                    iaa.OneOf([
                        iaa.Dropout((0.01, 0.1), per_channel=0.5), # randomly remove up to 10% of the pixels
                        iaa.CoarseDropout((0.03, 0.15), size_percent=(0.02, 0.05), per_channel=0.2),
                    ]),
                    iaa.Add((-10, 10), per_channel=0.5), # change brightness of images (by -10 to 10 of original value)
                    iaa.AddToHueAndSaturation((-20, 20)), # change hue and saturation
                    # either change the brightness of the whole image (sometimes
                    # per channel) or change the brightness of subareas
                    iaa.OneOf([
                        iaa.Multiply((0.5, 1.5), per_channel=0.5),
                        iaa.FrequencyNoiseAlpha(
                            exponent=(-4, 0),
                            first=iaa.Multiply((0.5, 1.5), per_channel=True),
                            second=iaa.ContrastNormalization((0.5, 2.0))
                        )
                    ]),
                    iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5), # improve or worsen the contrast
                    sometimes(iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)), # move pixels locally around (with random strengths)
                ],
                random_order=True
            )
        ],
        random_order=True
    )
    return seq
Пример #13
0
 def __init__(self,with_mask=True):
     self.with_mask = with_mask
     self.seq = iaa.Sequential(
         [
         iaa.SomeOf((0, 5),
             [
                 sometimes(iaa.Superpixels(p_replace=(0, 0.5), n_segments=(100, 200))), # convert images into their superpixel representation
                 iaa.OneOf([
                     iaa.GaussianBlur((0, 3.0)), # blur images with a sigma between 0 and 3.0
                     iaa.AverageBlur(k=(2, 7)), # blur image using local means with kernel sizes between 2 and 7
                     iaa.MedianBlur(k=(3, 11)), # blur image using local medians with kernel sizes between 2 and 7
                 ]),
                 iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)), # sharpen images
                 iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), # emboss images
                 # search either for all edges or for directed edges,
                 # blend the result with the original image using a blobby mask
                 iaa.SimplexNoiseAlpha(iaa.OneOf([
                     iaa.EdgeDetect(alpha=(0.5, 1.0)),
                     iaa.DirectedEdgeDetect(alpha=(0.5, 1.0), direction=(0.0, 1.0)),
                 ])),
                 iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # add gaussian noise to images
                 #iaa.OneOf([
                 #    iaa.Dropout((0.01, 0.1), per_channel=0.5), # randomly remove up to 10% of the pixels
                 #    iaa.CoarseDropout((0.03, 0.15), size_percent=(0.02, 0.05), per_channel=0.2),
                 #]),
                 iaa.Invert(0.05, per_channel=True), # invert color channels
                 iaa.Add((-5, 5), per_channel=0.5), # change brightness of images
                 iaa.AddToHueAndSaturation((-20, 20)), # change hue and saturation
                 # either change the brightness of the whole image (sometimes
                 # per channel) or change the brightness of subareas
                 iaa.OneOf([
                     iaa.Multiply((0.5, 1.5), per_channel=0.5),
                     iaa.FrequencyNoiseAlpha(
                         exponent=(-4, 0),
                         first=iaa.Multiply((0.5, 1.5), per_channel=True),
                         second=iaa.LinearContrast((0.5, 2.0))
                     )
                 ]),
                 iaa.LinearContrast((0.5, 2.0), per_channel=0.5), # improve or worsen the contrast
                 iaa.Grayscale(alpha=(0.0, 1.0))
             ],
             random_order=True
         )
     ],
     random_order=True
 )
Пример #14
0
def get_augmentation_sequence():
    sometimes = lambda aug: iaa.Sometimes(0.5, aug)

    slice_thickness_augmenter = iaa.Lambda(
        func_images=slice_thickness_func_images,
        func_keypoints=slice_thickness_func_keypoints)

    seq = iaa.Sequential([
        sometimes(iaa.Fliplr(0.5)),
        iaa.Sometimes(0.1, iaa.Add((-70, 70))),
        sometimes(
            iaa.Affine(scale={
                "x": (0.8, 1.2),
                "y": (0.8, 1.2)
            }  # scale images to 80-120% of their size, individually per axis
                       )),
        # sometimes(iaa.Multiply((0.5, 1.5))),
        # sometimes(iaa.ContrastNormalization((0.5, 2.0))),
        #     sometimes(iaa.Affine(
        #     translate_percent={"x": (-0.02, 0.02), "y": (-0.02, 0.02)}, # translate by -20 to +20 percent (per axis)
        #     rotate=(-2, 2), # rotate by -45 to +45 degrees
        #     shear=(-2, 2), # shear by -16 to +16 degrees
        #     order=[0, 1], # use nearest neighbour or bilinear interpolation (fast)
        #     cval=(0, 255), # if mode is constant, use a cval between 0 and 255
        #     mode='constant' # use any of scikit-image's warping modes (see 2nd image from the top for examples)
        # )),
        #     sometimes(iaa.CoarseDropout((0.03, 0.15), size_percent=(0.02, 0.05))),
        sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.01))),
        iaa.Sometimes(
            0.1,
            iaa.SimplexNoiseAlpha(iaa.OneOf(
                [iaa.Add((150, 255)),
                 iaa.Add((-100, 100))]),
                                  sigmoid_thresh=5)),
        iaa.Sometimes(
            0.1,
            iaa.OneOf([
                iaa.CoarseDropout((0.01, 0.15), size_percent=(0.02, 0.08)),
                iaa.CoarseSaltAndPepper(p=0.2, size_percent=0.01),
                iaa.CoarseSalt(p=0.2, size_percent=0.02)
            ])),
        iaa.Sometimes(0.25, slice_thickness_augmenter)
    ])
    return seq
def augment_sequential():
    return iaa.Sequential([
        iaa.SomeOf((1, 3), [
            iaa.Fliplr(0.5),

            iaa.DirectedEdgeDetect(alpha=(0.0, 0.3), direction=(0.0, 1.0)),

            iaa.OneOf([
                iaa.GaussianBlur((0, 1.0)),
                iaa.AverageBlur(k=(2, 3)),
            ]),

            iaa.Sharpen(alpha=(0, 0.5), lightness=(0.75, 1.0)),

            iaa.SimplexNoiseAlpha(iaa.OneOf([
                iaa.EdgeDetect(alpha=(0.0, 0.5)),
                iaa.DirectedEdgeDetect(alpha=(0.0, 0.5), direction=(0.5, 1.0)),
            ])),

            iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5),

            iaa.OneOf([
                iaa.Dropout((0.01, 0.3), per_channel=0.5),
                iaa.CoarseDropout((0.03, 0.15), size_percent=(0.02, 0.1), per_channel=0.2),
            ]),

            iaa.Add((-50, 50), per_channel=0.5),

            iaa.AddToHueAndSaturation((-50, 50)),

            iaa.LinearContrast((0.8, 1.2), per_channel=0.5),

            iaa.Grayscale(alpha=(0.0, 1.0)),

            iaa.ElasticTransformation(alpha=(0.5, 1.5), sigma=0.25),

            iaa.LinearContrast((0.5, 1.5), per_channel=0.5),
        ])
    ])
    def __init__(self, images,
                       config,
                       jitter=True,
                       norm=None):
        self.generator = None

        self.images = [] # pairs of (img, mask)
        self.config = config

        self.jitter  = jitter
        self.norm    = norm

        self.images = copy.deepcopy(images)

        sometimes = lambda aug: iaa.Sometimes(0.5, aug)
        self.seq_color = iaa.Sequential(
            [
                iaa.SomeOf((0, 3),
                    [
                        iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.2)),
                        iaa.Emboss(alpha=(0, 0.3), strength=(0, 2.0)),
                        iaa.SimplexNoiseAlpha(iaa.OneOf([
                            iaa.EdgeDetect(alpha=(0.5, 1.0)),
                            iaa.DirectedEdgeDetect(alpha=(0.5, 1.0), direction=(0.0, 1.0)),
                        ])),
                        iaa.OneOf([
                            iaa.Dropout((0.01, 0.1), per_channel=0.5), # randomly remove up to 10% of the pixels
                            iaa.CoarseDropout((0.03, 0.15), size_percent=(0.02, 0.05), per_channel=0.2),
                        ]),
                        iaa.Invert(0.05, per_channel=True),
                        iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5), 
                        iaa.Grayscale(alpha=(0.0, 1.0))
                    ], random_order=True
                )
            ], random_order=True
        )
Пример #17
0
def do_augmentation(D):
    """ D : Nx(n+p+1)xHxWx3. Return N1x(n+p+1)xHxWx3 """

    n_samples = D.shape[0]
    n_images_per_sample = D.shape[1]

    im_rows = D.shape[2]
    im_cols = D.shape[3]
    im_chnl = D.shape[4]

    E = D.reshape(n_samples * n_images_per_sample, im_rows, im_cols, im_chnl)

    sometimes = lambda aug: iaa.Sometimes(0.5, aug)

    # Very basic
    if True:
        seq = iaa.Sequential([
            sometimes(iaa.Crop(px=(
                0, 50
            ))),  # crop images from each side by 0 to 16px (randomly chosen)
            # iaa.Fliplr(0.5), # horizontally flip 50% of the images
            iaa.GaussianBlur(sigma=(0, 3.0)
                             ),  # blur images with a sigma of 0 to 3.0
            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=(-25, 25),
                           shear=(-8, 8)))
        ])
        seq_vbasic = seq

    # Sometimes(0.5, ...) applies the given augmenter in 50% of all cases,
    # e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second image.

    # Typical
    if True:
        seq = iaa.Sequential(
            [
                iaa.Fliplr(0.5),  # horizontal flips
                iaa.Crop(percent=(0, 0.1)),  # random crops
                # Small gaussian blur with random sigma between 0 and 0.5.
                # But we only blur about 50% of all images.
                iaa.Sometimes(0.5, iaa.GaussianBlur(sigma=(0, 0.5))),
                # Strengthen or weaken the contrast in each image.
                iaa.ContrastNormalization((0.75, 1.5)),
                # 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.8, 1.2), per_channel=0.2),
                # Apply affine transformations to each image.
                # Scale/zoom them, translate/move them, rotate them and shear them.
                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)  # apply augmenters in random order
        # seq = sometimes( seq )
        seq_typical = seq

    # Heavy
    if True:
        # Define our sequence of augmentation steps that will be applied to every image
        # All augmenters with per_channel=0.5 will sample one value _per image_
        # in 50% of all cases. In all other cases they will sample new values
        # _per channel_.
        seq = iaa.Sequential(
            [
                # apply the following augmenters to most images
                iaa.Fliplr(0.2),  # horizontally flip 20% of all images
                iaa.Flipud(0.2),  # vertically flip 20% of all images
                # crop images by -5% to 10% of their height/width
                sometimes(
                    iaa.CropAndPad(percent=(-0.05, 0.1),
                                   pad_mode=ia.ALL,
                                   pad_cval=(0, 255))),
                sometimes(
                    iaa.Affine(
                        scale={
                            "x": (0.8, 1.2),
                            "y": (0.8, 1.2)
                        },  # scale images to 80-120% of their size, individually per axis
                        translate_percent={
                            "x": (-0.2, 0.2),
                            "y": (-0.2, 0.2)
                        },  # translate by -20 to +20 percent (per axis)
                        rotate=(-45, 45),  # rotate by -45 to +45 degrees
                        shear=(-16, 16),  # shear by -16 to +16 degrees
                        order=[
                            0,
                            1
                        ],  # use nearest neighbour or bilinear interpolation (fast)
                        cval=(
                            0, 255
                        ),  # if mode is constant, use a cval between 0 and 255
                        mode=ia.
                        ALL  # use any of scikit-image's warping modes (see 2nd image from the top for examples)
                    )),
                # execute 0 to 5 of the following (less important) augmenters per image
                # don't execute all of them, as that would often be way too strong
                iaa.SomeOf(
                    (0, 5),
                    [
                        sometimes(
                            iaa.Superpixels(p_replace=(0, 1.0),
                                            n_segments=(20, 200))
                        ),  # convert images into their superpixel representation
                        iaa.OneOf([
                            iaa.GaussianBlur(
                                (0, 3.0)
                            ),  # blur images with a sigma between 0 and 3.0
                            iaa.AverageBlur(
                                k=(2, 7)
                            ),  # blur image using local means with kernel sizes between 2 and 7
                            #iaa.MedianBlur(k=(3, 11)), # blur image using local medians with kernel sizes between 2 and 7
                        ]),
                        iaa.Sharpen(alpha=(0, 1.0),
                                    lightness=(0.75, 1.5)),  # sharpen images
                        iaa.Emboss(alpha=(0, 1.0),
                                   strength=(0, 2.0)),  # emboss images
                        # search either for all edges or for directed edges,
                        # blend the result with the original image using a blobby mask
                        iaa.SimplexNoiseAlpha(
                            iaa.OneOf([
                                iaa.EdgeDetect(alpha=(0.5, 1.0)),
                                iaa.DirectedEdgeDetect(alpha=(0.5, 1.0),
                                                       direction=(0.0, 1.0)),
                            ])),
                        iaa.AdditiveGaussianNoise(
                            loc=0, scale=(0.0, 0.05 * 255),
                            per_channel=0.5),  # add gaussian noise to images
                        iaa.OneOf([
                            iaa.Dropout(
                                (0.01, 0.1), per_channel=0.5
                            ),  # randomly remove up to 10% of the pixels
                            iaa.CoarseDropout((0.03, 0.15),
                                              size_percent=(0.02, 0.05),
                                              per_channel=0.2),
                        ]),
                        iaa.Invert(0.05,
                                   per_channel=True),  # invert color channels
                        iaa.Add(
                            (-10, 10), per_channel=0.5
                        ),  # change brightness of images (by -10 to 10 of original value)
                        iaa.AddToHueAndSaturation(
                            (-20, 20)),  # change hue and saturation
                        # either change the brightness of the whole image (sometimes
                        # per channel) or change the brightness of subareas
                        iaa.OneOf([
                            iaa.Multiply((0.5, 1.5), per_channel=0.5),
                            iaa.FrequencyNoiseAlpha(
                                exponent=(-4, 0),
                                first=iaa.Multiply(
                                    (0.5, 1.5), per_channel=True),
                                second=iaa.ContrastNormalization((0.5, 2.0)))
                        ]),
                        iaa.ContrastNormalization(
                            (0.5, 2.0),
                            per_channel=0.5),  # improve or worsen the contrast
                        iaa.Grayscale(alpha=(0.0, 1.0)),
                        sometimes(
                            iaa.ElasticTransformation(alpha=(0.5, 3.5),
                                                      sigma=0.25)
                        ),  # move pixels locally around (with random strengths)
                        sometimes(
                            iaa.PiecewiseAffine(scale=(0.01, 0.05))
                        ),  # sometimes move parts of the image around
                        sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.1)))
                    ],
                    random_order=True)
            ],
            random_order=True)
        seq_heavy = seq

    print 'Add data'
    L = [E]
    print 'seq_vbasic'
    L.append(seq_vbasic.augment_images(E))
    print 'seq_typical'
    L.append(seq_typical.augment_images(E))
    print 'seq_typical'
    L.append(seq_typical.augment_images(E))
    print 'seq_heavy'
    L.append(seq_heavy.augment_images(E))

    G = [
        l.reshape(n_samples, n_images_per_sample, im_rows, im_cols, im_chnl)
        for l in L
    ]
    G = np.concatenate(G)
    print 'Input.shape ', D.shape, '\tOutput.shape ', G.shape
    return G

    # for j in range(n_times):
    #     images_aug = seq.augment_images(E)
    #     # L.append( images_aug.reshape( n_samples, n_images_per_sample, im_rows,im_cols,im_chnl  ) )
    #     L.append( images_aug )

    # code.interact( local=locals() )
    return L
Пример #18
0
def test_dtype_preservation():
    reseed()

    size = (4, 16, 16, 3)
    images = [
        np.random.uniform(0, 255, size).astype(np.uint8),
        np.random.uniform(0, 65535, size).astype(np.uint16),
        np.random.uniform(0, 4294967295, size).astype(np.uint32),
        np.random.uniform(-128, 127, size).astype(np.int16),
        np.random.uniform(-32768, 32767, size).astype(np.int32),
        np.random.uniform(0.0, 1.0, size).astype(np.float32),
        np.random.uniform(-1000.0, 1000.0, size).astype(np.float16),
        np.random.uniform(-1000.0, 1000.0, size).astype(np.float32),
        np.random.uniform(-1000.0, 1000.0, size).astype(np.float64)
    ]

    default_dtypes = set([arr.dtype for arr in images])

    # Some dtypes are here removed per augmenter, because the respective
    # augmenter does not support them. This test currently only checks whether
    # dtypes are preserved from in- to output for all dtypes that are supported
    # per augmenter.
    # dtypes are here removed via list comprehension instead of
    # `default_dtypes - set([dtype])`, because the latter one simply never
    # removed the dtype(s) for some reason

    def _not_dts(dts):
        return [dt for dt in default_dtypes if dt not in dts]

    augs = [
        (iaa.Add((-5, 5),
                 name="Add"), _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.AddElementwise((-5, 5), name="AddElementwise"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.AdditiveGaussianNoise(0.01 * 255, name="AdditiveGaussianNoise"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.Multiply((0.95, 1.05), name="Multiply"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.Dropout(0.01, name="Dropout"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.CoarseDropout(0.01, size_px=6, name="CoarseDropout"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.Invert(0.01, per_channel=True, name="Invert"), default_dtypes),
        (iaa.GaussianBlur(sigma=(0.95, 1.05),
                          name="GaussianBlur"), _not_dts([np.float16])),
        (iaa.AverageBlur((3, 5), name="AverageBlur"),
         _not_dts([np.uint32, np.int32, np.float16])),
        (iaa.MedianBlur((3, 5), name="MedianBlur"),
         _not_dts([np.uint32, np.int32, np.float16, np.float64])),
        (iaa.BilateralBlur((3, 5), name="BilateralBlur"),
         _not_dts([
             np.uint16, np.uint32, np.int16, np.int32, np.float16, np.float64
         ])),
        (iaa.Sharpen((0.0, 0.1), lightness=(1.0, 1.2), name="Sharpen"),
         _not_dts([np.uint32, np.int32, np.float16, np.uint32])),
        (iaa.Emboss(alpha=(0.0, 0.1), strength=(0.5, 1.5), name="Emboss"),
         _not_dts([np.uint32, np.int32, np.float16, np.uint32])),
        (iaa.EdgeDetect(alpha=(0.0, 0.1), name="EdgeDetect"),
         _not_dts([np.uint32, np.int32, np.float16, np.uint32])),
        (iaa.DirectedEdgeDetect(alpha=(0.0, 0.1),
                                direction=0,
                                name="DirectedEdgeDetect"),
         _not_dts([np.uint32, np.int32, np.float16, np.uint32])),
        (iaa.Fliplr(0.5, name="Fliplr"), default_dtypes),
        (iaa.Flipud(0.5, name="Flipud"), default_dtypes),
        (iaa.Affine(translate_px=(-5, 5), name="Affine-translate-px"),
         _not_dts([np.uint32, np.int32])),
        (iaa.Affine(translate_percent=(-0.05, 0.05),
                    name="Affine-translate-percent"),
         _not_dts([np.uint32, np.int32])),
        (iaa.Affine(rotate=(-20, 20),
                    name="Affine-rotate"), _not_dts([np.uint32, np.int32])),
        (iaa.Affine(shear=(-20, 20),
                    name="Affine-shear"), _not_dts([np.uint32, np.int32])),
        (iaa.Affine(scale=(0.9, 1.1),
                    name="Affine-scale"), _not_dts([np.uint32, np.int32])),
        (iaa.PiecewiseAffine(scale=(0.001, 0.005),
                             name="PiecewiseAffine"), default_dtypes),
        (iaa.ElasticTransformation(alpha=(0.1, 0.2),
                                   sigma=(0.1, 0.2),
                                   name="ElasticTransformation"),
         _not_dts([np.float16])),
        (iaa.Sequential([iaa.Identity(), iaa.Identity()],
                        name="SequentialNoop"), default_dtypes),
        (iaa.SomeOf(1, [iaa.Identity(), iaa.Identity()],
                    name="SomeOfNoop"), default_dtypes),
        (iaa.OneOf([iaa.Identity(), iaa.Identity()],
                   name="OneOfNoop"), default_dtypes),
        (iaa.Sometimes(0.5, iaa.Identity(),
                       name="SometimesNoop"), default_dtypes),
        (iaa.Sequential([iaa.Add(
            (-5, 5)), iaa.AddElementwise((-5, 5))],
                        name="Sequential"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.SomeOf(1, [iaa.Add(
            (-5, 5)), iaa.AddElementwise((-5, 5))],
                    name="SomeOf"), _not_dts([np.uint32, np.int32,
                                              np.float64])),
        (iaa.OneOf([iaa.Add(
            (-5, 5)), iaa.AddElementwise((-5, 5))],
                   name="OneOf"), _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.Sometimes(0.5, iaa.Add((-5, 5)), name="Sometimes"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.Identity(name="Identity"), default_dtypes),
        (iaa.Alpha((0.0, 0.1), iaa.Identity(),
                   name="AlphaIdentity"), default_dtypes),
        (iaa.AlphaElementwise(
            (0.0, 0.1), iaa.Identity(),
            name="AlphaElementwiseIdentity"), default_dtypes),
        (iaa.SimplexNoiseAlpha(iaa.Identity(),
                               name="SimplexNoiseAlphaIdentity"),
         default_dtypes),
        (iaa.FrequencyNoiseAlpha(exponent=(-2, 2),
                                 first=iaa.Identity(),
                                 name="SimplexNoiseAlphaIdentity"),
         default_dtypes),
        (iaa.Alpha((0.0, 0.1), iaa.Add(10),
                   name="Alpha"), _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.AlphaElementwise((0.0, 0.1), iaa.Add(10),
                              name="AlphaElementwise"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.SimplexNoiseAlpha(iaa.Add(10), name="SimplexNoiseAlpha"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.FrequencyNoiseAlpha(exponent=(-2, 2),
                                 first=iaa.Add(10),
                                 name="SimplexNoiseAlpha"),
         _not_dts([np.uint32, np.int32, np.float64])),
        (iaa.Superpixels(p_replace=0.01, n_segments=64),
         _not_dts([np.float16, np.float32, np.float64])),
        (iaa.Resize({
            "height": 4,
            "width": 4
        }, name="Resize"),
         _not_dts([
             np.uint16, np.uint32, np.int16, np.int32, np.float32, np.float16,
             np.float64
         ])),
        (iaa.CropAndPad(px=(-10, 10), name="CropAndPad"),
         _not_dts([
             np.uint16, np.uint32, np.int16, np.int32, np.float32, np.float16,
             np.float64
         ])),
        (iaa.Pad(px=(0, 10), name="Pad"),
         _not_dts([
             np.uint16, np.uint32, np.int16, np.int32, np.float32, np.float16,
             np.float64
         ])),
        (iaa.Crop(px=(0, 10), name="Crop"),
         _not_dts([
             np.uint16, np.uint32, np.int16, np.int32, np.float32, np.float16,
             np.float64
         ]))
    ]

    for (aug, allowed_dtypes) in augs:
        for images_i in images:
            if images_i.dtype in allowed_dtypes:
                images_aug = aug.augment_images(images_i)
                assert images_aug.dtype == images_i.dtype
Пример #19
0
def test_unusual_channel_numbers():
    reseed()

    images = [(0, create_random_images((4, 16, 16))),
              (1, create_random_images((4, 16, 16, 1))),
              (2, create_random_images((4, 16, 16, 2))),
              (4, create_random_images((4, 16, 16, 4))),
              (5, create_random_images((4, 16, 16, 5))),
              (10, create_random_images((4, 16, 16, 10))),
              (20, create_random_images((4, 16, 16, 20)))]

    augs = [
        iaa.Add((-5, 5), name="Add"),
        iaa.AddElementwise((-5, 5), name="AddElementwise"),
        iaa.AdditiveGaussianNoise(0.01 * 255, name="AdditiveGaussianNoise"),
        iaa.Multiply((0.95, 1.05), name="Multiply"),
        iaa.Dropout(0.01, name="Dropout"),
        iaa.CoarseDropout(0.01, size_px=6, name="CoarseDropout"),
        iaa.Invert(0.01, per_channel=True, name="Invert"),
        iaa.GaussianBlur(sigma=(0.95, 1.05), name="GaussianBlur"),
        iaa.AverageBlur((3, 5), name="AverageBlur"),
        iaa.MedianBlur((3, 5), name="MedianBlur"),
        iaa.Sharpen((0.0, 0.1), lightness=(1.0, 1.2), name="Sharpen"),
        iaa.Emboss(alpha=(0.0, 0.1), strength=(0.5, 1.5), name="Emboss"),
        iaa.EdgeDetect(alpha=(0.0, 0.1), name="EdgeDetect"),
        iaa.DirectedEdgeDetect(alpha=(0.0, 0.1),
                               direction=0,
                               name="DirectedEdgeDetect"),
        iaa.Fliplr(0.5, name="Fliplr"),
        iaa.Flipud(0.5, name="Flipud"),
        iaa.Affine(translate_px=(-5, 5), name="Affine-translate-px"),
        iaa.Affine(translate_percent=(-0.05, 0.05),
                   name="Affine-translate-percent"),
        iaa.Affine(rotate=(-20, 20), name="Affine-rotate"),
        iaa.Affine(shear=(-20, 20), name="Affine-shear"),
        iaa.Affine(scale=(0.9, 1.1), name="Affine-scale"),
        iaa.PiecewiseAffine(scale=(0.001, 0.005), name="PiecewiseAffine"),
        iaa.PerspectiveTransform(scale=(0.01, 0.10),
                                 name="PerspectiveTransform"),
        iaa.ElasticTransformation(alpha=(0.1, 0.2),
                                  sigma=(0.1, 0.2),
                                  name="ElasticTransformation"),
        iaa.Sequential([iaa.Add((-5, 5)),
                        iaa.AddElementwise((-5, 5))]),
        iaa.SomeOf(1, [iaa.Add(
            (-5, 5)), iaa.AddElementwise((-5, 5))]),
        iaa.OneOf([iaa.Add((-5, 5)),
                   iaa.AddElementwise((-5, 5))]),
        iaa.Sometimes(0.5, iaa.Add((-5, 5)), name="Sometimes"),
        iaa.Identity(name="Noop"),
        iaa.Alpha((0.0, 0.1), iaa.Add(10), name="Alpha"),
        iaa.AlphaElementwise((0.0, 0.1), iaa.Add(10), name="AlphaElementwise"),
        iaa.SimplexNoiseAlpha(iaa.Add(10), name="SimplexNoiseAlpha"),
        iaa.FrequencyNoiseAlpha(exponent=(-2, 2),
                                first=iaa.Add(10),
                                name="SimplexNoiseAlpha"),
        iaa.Superpixels(p_replace=0.01, n_segments=64),
        iaa.Resize({
            "height": 4,
            "width": 4
        }, name="Resize"),
        iaa.CropAndPad(px=(-10, 10), name="CropAndPad"),
        iaa.Pad(px=(0, 10), name="Pad"),
        iaa.Crop(px=(0, 10), name="Crop")
    ]

    for aug in augs:
        for (nb_channels, images_c) in images:
            if aug.name != "Resize":
                images_aug = aug.augment_images(images_c)
                assert images_aug.shape == images_c.shape
                image_aug = aug.augment_image(images_c[0])
                assert image_aug.shape == images_c[0].shape
            else:
                images_aug = aug.augment_images(images_c)
                image_aug = aug.augment_image(images_c[0])
                if images_c.ndim == 3:
                    assert images_aug.shape == (4, 4, 4)
                    assert image_aug.shape == (4, 4)
                else:
                    assert images_aug.shape == (4, 4, 4, images_c.shape[3])
                    assert image_aug.shape == (4, 4, images_c.shape[3])
Пример #20
0
def test_keypoint_augmentation():
    reseed()

    keypoints = []
    for y in sm.xrange(40 // 5):
        for x in sm.xrange(60 // 5):
            keypoints.append(ia.Keypoint(y=y * 5, x=x * 5))

    keypoints_oi = ia.KeypointsOnImage(keypoints, shape=(40, 60, 3))
    keypoints_oi_empty = ia.KeypointsOnImage([], shape=(40, 60, 3))

    augs = [
        iaa.Add((-5, 5), name="Add"),
        iaa.AddElementwise((-5, 5), name="AddElementwise"),
        iaa.AdditiveGaussianNoise(0.01 * 255, name="AdditiveGaussianNoise"),
        iaa.Multiply((0.95, 1.05), name="Multiply"),
        iaa.Dropout(0.01, name="Dropout"),
        iaa.CoarseDropout(0.01, size_px=6, name="CoarseDropout"),
        iaa.Invert(0.01, per_channel=True, name="Invert"),
        iaa.GaussianBlur(sigma=(0.95, 1.05), name="GaussianBlur"),
        iaa.AverageBlur((3, 5), name="AverageBlur"),
        iaa.MedianBlur((3, 5), name="MedianBlur"),
        iaa.Sharpen((0.0, 0.1), lightness=(1.0, 1.2), name="Sharpen"),
        iaa.Emboss(alpha=(0.0, 0.1), strength=(0.5, 1.5), name="Emboss"),
        iaa.EdgeDetect(alpha=(0.0, 0.1), name="EdgeDetect"),
        iaa.DirectedEdgeDetect(alpha=(0.0, 0.1),
                               direction=0,
                               name="DirectedEdgeDetect"),
        iaa.Fliplr(0.5, name="Fliplr"),
        iaa.Flipud(0.5, name="Flipud"),
        iaa.Affine(translate_px=(-5, 5), name="Affine-translate-px"),
        iaa.Affine(translate_percent=(-0.05, 0.05),
                   name="Affine-translate-percent"),
        iaa.Affine(rotate=(-20, 20), name="Affine-rotate"),
        iaa.Affine(shear=(-20, 20), name="Affine-shear"),
        iaa.Affine(scale=(0.9, 1.1), name="Affine-scale"),
        iaa.PiecewiseAffine(scale=(0.001, 0.005), name="PiecewiseAffine"),
        iaa.ElasticTransformation(alpha=(0.1, 0.2),
                                  sigma=(0.1, 0.2),
                                  name="ElasticTransformation"),
        iaa.Alpha((0.0, 0.1), iaa.Add(10), name="Alpha"),
        iaa.AlphaElementwise((0.0, 0.1), iaa.Add(10), name="AlphaElementwise"),
        iaa.SimplexNoiseAlpha(iaa.Add(10), name="SimplexNoiseAlpha"),
        iaa.FrequencyNoiseAlpha(exponent=(-2, 2),
                                first=iaa.Add(10),
                                name="SimplexNoiseAlpha"),
        iaa.Superpixels(p_replace=0.01, n_segments=64),
        iaa.Resize(0.5, name="Resize"),
        iaa.CropAndPad(px=(-10, 10), name="CropAndPad"),
        iaa.Pad(px=(0, 10), name="Pad"),
        iaa.Crop(px=(0, 10), name="Crop")
    ]

    for aug in augs:
        dss = []
        for i in sm.xrange(10):
            aug_det = aug.to_deterministic()

            kp_fully_empty_aug = aug_det.augment_keypoints([])
            assert kp_fully_empty_aug == []

            kp_first_empty_aug = aug_det.augment_keypoints(keypoints_oi_empty)
            assert len(kp_first_empty_aug.keypoints) == 0

            kp_image = keypoints_oi.to_keypoint_image(size=5)
            kp_image_aug = aug_det.augment_image(kp_image)
            kp_image_aug_rev = ia.KeypointsOnImage.from_keypoint_image(
                kp_image_aug,
                if_not_found_coords={
                    "x": -9999,
                    "y": -9999
                },
                nb_channels=1)
            kp_aug = aug_det.augment_keypoints([keypoints_oi])[0]
            ds = []
            assert len(kp_image_aug_rev.keypoints) == len(kp_aug.keypoints), (
                "Lost keypoints for '%s' (%d vs expected %d)" %
                (aug.name, len(
                    kp_aug.keypoints), len(kp_image_aug_rev.keypoints)))

            gen = zip(kp_aug.keypoints, kp_image_aug_rev.keypoints)
            for kp_pred, kp_pred_img in gen:
                kp_pred_lost = (kp_pred.x == -9999 and kp_pred.y == -9999)
                kp_pred_img_lost = (kp_pred_img.x == -9999
                                    and kp_pred_img.y == -9999)

                if not kp_pred_lost and not kp_pred_img_lost:
                    d = np.sqrt((kp_pred.x - kp_pred_img.x)**2 +
                                (kp_pred.y - kp_pred_img.y)**2)
                    ds.append(d)
            dss.extend(ds)
            if len(ds) == 0:
                print("[INFO] No valid keypoints found for '%s' "
                      "in test_keypoint_augmentation()" % (str(aug), ))
        assert np.average(dss) < 5.0, \
            "Average distance too high (%.2f, with ds: %s)" \
            % (np.average(dss), str(dss))
Пример #21
0
def black_and_white_aug():
    alpha_seconds = iaa.OneOf([
        iaa.Affine(rotate=(-3, 3)),
        iaa.Affine(translate_percent={
            "x": (0.95, 1.05),
            "y": (0.95, 1.05)
        }),
        iaa.Affine(scale={
            "x": (0.95, 1.05),
            "y": (0.95, 1.05)
        }),
        iaa.Affine(shear=(-2, 2)),
        iaa.CoarseDropout(p=0.1, size_percent=(0.08, 0.02)),
    ])

    first_set = iaa.OneOf([
        iaa.Multiply(iap.Choice([0.5, 1.5]), per_channel=True),
        iaa.EdgeDetect((0.1, 1)),
    ])

    second_set = iaa.OneOf([
        iaa.AddToHueAndSaturation((-40, 40)),
        iaa.ContrastNormalization((0.5, 2.0), per_channel=True)
    ])

    color_aug = iaa.Sequential(
        [
            # Original Image Domain ==================================================

            # Geometric Rigid
            iaa.Fliplr(0.5),
            iaa.OneOf([
                iaa.Noop(),
                iaa.Affine(rotate=90),
                iaa.Affine(rotate=180),
                iaa.Affine(rotate=270),
            ]),
            iaa.OneOf([
                iaa.Noop(),
                iaa.Crop(percent=(0, 0.1)),  # Random Crops
                iaa.PerspectiveTransform(scale=(0.05, 0.15)),
            ]),

            # Affine
            sometimes(
                iaa.PiecewiseAffine(
                    scale=(0.01, 0.07), nb_rows=(3, 6), nb_cols=(3, 6))),
            fewtimes(
                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=(-45, 45),
                           shear=(-16, 16),
                           order=[0, 1],
                           cval=0)),

            # Transformations outside Image domain ==============================================

            # COLOR, CONTRAST, HUE
            iaa.Invert(0.5, name='Invert'),
            fewtimes(iaa.Add((-10, 10), per_channel=0.5, name='Add')),
            fewtimes(
                iaa.AddToHueAndSaturation(
                    (-40, 40), per_channel=0.5, name='AddToHueAndSaturation')),

            # Intensity / contrast
            fewtimes(
                iaa.ContrastNormalization(
                    (0.8, 1.1), name='ContrastNormalization')),

            # Add to hue and saturation
            fewtimes(
                iaa.Multiply(
                    (0.5, 1.5), per_channel=0.5, name='HueAndSaturation')),

            # Noise ===========================================================================
            fewtimes(
                iaa.AdditiveGaussianNoise(loc=0,
                                          scale=(0.0, 0.15 * 255),
                                          per_channel=0.5,
                                          name='AdditiveGaussianNoise')),
            fewtimes(
                iaa.Alpha(factor=(0.5, 1),
                          first=iaa.ContrastNormalization(
                              (0.5, 2.0), per_channel=True),
                          second=alpha_seconds,
                          per_channel=0.5,
                          name='AlphaNoise'), ),
            fewtimes(
                iaa.SimplexNoiseAlpha(first=first_set,
                                      second=second_set,
                                      per_channel=0.5,
                                      aggregation_method="max",
                                      sigmoid=False,
                                      upscale_method='cubic',
                                      size_px_max=(2, 12),
                                      name='SimplexNoiseAlpha'), ),
            fewtimes(
                iaa.FrequencyNoiseAlpha(first=first_set,
                                        second=second_set,
                                        per_channel=0.5,
                                        aggregation_method="max",
                                        sigmoid=False,
                                        upscale_method='cubic',
                                        size_px_max=(2, 12),
                                        name='FrequencyNoiseAlpha'), ),

            # Blur
            fewtimes(
                iaa.OneOf([
                    iaa.GaussianBlur((0, 3.0)),
                    iaa.AverageBlur(k=(2, 7)),
                    iaa.MedianBlur(k=(3, 11)),
                    iaa.BilateralBlur(d=(3, 10),
                                      sigma_color=(10, 250),
                                      sigma_space=(10, 250))
                ],
                          name='Blur')),

            # Regularization ======================================================================
            unlikely(
                iaa.OneOf([
                    iaa.Dropout((0.01, 0.1), per_channel=0.5, name='Dropout'),
                    iaa.CoarseDropout((0.03, 0.15),
                                      size_percent=(0.02, 0.05),
                                      per_channel=0.5,
                                      name='CoarseDropout'),
                ], )),
        ],
        random_order=True)

    seq = iaa.Sequential(
        [
            iaa.Sequential(
                [
                    # Texture
                    rarely(
                        iaa.Superpixels(p_replace=(0.3, 1.0),
                                        n_segments=(500, 1000),
                                        name='Superpixels')),
                    rarely(
                        iaa.Sharpen(alpha=(0, 0.5),
                                    lightness=(0.75, 1.0),
                                    name='Sharpen')),
                    rarely(
                        iaa.Emboss(
                            alpha=(0, 1.0), strength=(0, 1.0), name='Emboss')),
                    rarely(
                        iaa.OneOf([
                            iaa.EdgeDetect(alpha=(0, 0.5)),
                            iaa.DirectedEdgeDetect(alpha=(0, 0.5),
                                                   direction=(0.0, 1.0)),
                        ],
                                  name='EdgeDetect')),
                    rarely(
                        iaa.ElasticTransformation(
                            alpha=(0.5, 3.5),
                            sigma=0.25,
                            name='ElasticTransformation')),
                ],
                random_order=True),
            color_aug,
            iaa.Grayscale(alpha=1.0, name='Grayscale')
        ],
        random_order=False)

    def activator_masks(images, augmenter, parents, default):
        if 'Unnamed' not in augmenter.name:
            return False
        else:
            return default

    hooks_masks = ia.HooksImages(activator=activator_masks)
    return seq, hooks_masks
 # execute 0 to 5 of the following (less important) augmenters per image
 # don't execute all of them, as that would often be way too strong
 iaa.SomeOf((0, 5),
     [
         sometimes(iaa.Superpixels(p_replace=(0, 1.0), n_segments=(20, 200))), # convert images into their superpixel representation
         iaa.OneOf([
             iaa.GaussianBlur((0, 1.0)), # blur images with a sigma between 0 and 3.0
             iaa.AverageBlur(k=(3, 5)), # blur image using local means with kernel sizes between 2 and 7
             iaa.MedianBlur(k=(3, 5)), # blur image using local medians with kernel sizes between 2 and 7
         ]),
         iaa.Sharpen(alpha=(0, 1.0), lightness=(0.9, 1.1)), # sharpen images
         iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), # emboss images
         # search either for all edges or for directed edges,
         # blend the result with the original image using a blobby mask
         iaa.SimplexNoiseAlpha(iaa.OneOf([
             iaa.EdgeDetect(alpha=(0.5, 1.0)),
             iaa.DirectedEdgeDetect(alpha=(0.5, 1.0), direction=(0.0, 1.0)),
         ])),
         iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.01*255), per_channel=0.5), # add gaussian noise to images
         iaa.OneOf([
             iaa.Dropout((0.01, 0.05), per_channel=0.5), # randomly remove up to 10% of the pixels
             iaa.CoarseDropout((0.01, 0.03), size_percent=(0.01, 0.02), per_channel=0.2),
         ]),
         iaa.Invert(0.01, per_channel=True), # invert color channels
         iaa.Add((-2, 2), per_channel=0.5), # change brightness of images (by -10 to 10 of original value)
         iaa.AddToHueAndSaturation((-1, 1)), # change hue and saturation
         # either change the brightness of the whole image (sometimes
         # per channel) or change the brightness of subareas
         iaa.OneOf([
             iaa.Multiply((0.9, 1.1), per_channel=0.5),
             iaa.FrequencyNoiseAlpha(
                 exponent=(-1, 0),
Пример #23
0
def draw_single_sequential_images():
    ia.seed(44)

    #image = misc.imresize(ndimage.imread("quokka.jpg")[0:643, 0:643], (128, 128))
    image = ia.quokka_square(size=(128, 128))

    sometimes = lambda aug: iaa.Sometimes(0.5, aug)
    seq = iaa.Sequential(
        [
            # apply the following augmenters to most images
            iaa.Fliplr(0.5), # horizontally flip 50% of all images
            iaa.Flipud(0.2), # vertically flip 20% of all images
            # crop images by -5% to 10% of their height/width
            sometimes(iaa.CropAndPad(
                percent=(-0.05, 0.1),
                pad_mode=ia.ALL,
                pad_cval=(0, 255)
            )),
            sometimes(iaa.Affine(
                scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, # scale images to 80-120% of their size, individually per axis
                translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, # translate by -20 to +20 percent (per axis)
                rotate=(-45, 45), # rotate by -45 to +45 degrees
                shear=(-16, 16), # shear by -16 to +16 degrees
                order=[0, 1], # use nearest neighbour or bilinear interpolation (fast)
                cval=(0, 255), # if mode is constant, use a cval between 0 and 255
                mode=ia.ALL # use any of scikit-image's warping modes (see 2nd image from the top for examples)
            )),
            # execute 0 to 5 of the following (less important) augmenters per image
            # don't execute all of them, as that would often be way too strong
            iaa.SomeOf((0, 5),
                [
                    sometimes(iaa.Superpixels(p_replace=(0, 1.0), n_segments=(20, 200))), # convert images into their superpixel representation
                    iaa.OneOf([
                        iaa.GaussianBlur((0, 3.0)), # blur images with a sigma between 0 and 3.0
                        iaa.AverageBlur(k=(2, 7)), # blur image using local means with kernel sizes between 2 and 7
                        iaa.MedianBlur(k=(3, 11)), # blur image using local medians with kernel sizes between 2 and 7
                    ]),
                    iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)), # sharpen images
                    iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), # emboss images
                    # search either for all edges or for directed edges,
                    # blend the result with the original image using a blobby mask
                    iaa.SimplexNoiseAlpha(iaa.OneOf([
                        iaa.EdgeDetect(alpha=(0.5, 1.0)),
                        iaa.DirectedEdgeDetect(alpha=(0.5, 1.0), direction=(0.0, 1.0)),
                    ])),
                    iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # add gaussian noise to images
                    iaa.OneOf([
                        iaa.Dropout((0.01, 0.1), per_channel=0.5), # randomly remove up to 10% of the pixels
                        iaa.CoarseDropout((0.03, 0.15), size_percent=(0.02, 0.05), per_channel=0.2),
                    ]),
                    iaa.Invert(0.05, per_channel=True), # invert color channels
                    iaa.Add((-10, 10), per_channel=0.5), # change brightness of images (by -10 to 10 of original value)
                    iaa.AddToHueAndSaturation((-20, 20)), # change hue and saturation
                    # either change the brightness of the whole image (sometimes
                    # per channel) or change the brightness of subareas
                    iaa.OneOf([
                        iaa.Multiply((0.5, 1.5), per_channel=0.5),
                        iaa.FrequencyNoiseAlpha(
                            exponent=(-4, 0),
                            first=iaa.Multiply((0.5, 1.5), per_channel=True),
                            second=iaa.ContrastNormalization((0.5, 2.0))
                        )
                    ]),
                    iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5), # improve or worsen the contrast
                    iaa.Grayscale(alpha=(0.0, 1.0)),
                    sometimes(iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)), # move pixels locally around (with random strengths)
                    sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.05))), # sometimes move parts of the image around
                    sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.1)))
                ],
                random_order=True
            )
        ],
        random_order=True
    )

    grid = seq.draw_grid(image, cols=8, rows=8)
    misc.imsave("examples_grid.jpg", grid)
  def __init__(self):
    sometimes = lambda aug: iaa.Sometimes(0.2, aug)
    self.aug = iaa.Sequential(
				[
				sometimes(iaa.Affine(
					scale={"x": (0.9, 1.1), "y": (0.9, 1.1)},
					# scale images to 80-120% of their size, individually per axis
					translate_percent={"x": (-0.1, 0.1), "y": (-0.1, 0.1)},
					# translate by -20 to +20 percent (per axis)
					#rotate=(-5, 5),  # rotate by -45 to +45 degrees
					#shear=(-5, 5),  # shear by -16 to +16 degrees
					order=[0, 1],
					# use nearest neighbour or bilinear interpolation (fast)
					cval=(0, 255),  # if mode is constant, use a cval between 0 and 255
					mode=ia.ALL
					# use any of scikit-image's warping modes (see 2nd image from the top for examples)
				)),
				# execute 0 to 5 of the following (less important) augmenters per image
				# don't execute all of them, as that would often be way too strong
				iaa.SomeOf((0, 5),
				           [sometimes(iaa.Superpixels(p_replace=(0, 1.0),
						                                     n_segments=(20, 200))),
					           # convert images into their superpixel representation
					           iaa.OneOf([
							           iaa.GaussianBlur((0, 1.0)),
							           # blur images with a sigma between 0 and 3.0
							           iaa.AverageBlur(k=(3, 5)),
							           # blur image using local means with kernel sizes between 2 and 7
							           iaa.MedianBlur(k=(3, 5)),
							           # blur image using local medians with kernel sizes between 2 and 7
					           ]),
					           iaa.Sharpen(alpha=(0, 1.0), lightness=(0.9, 1.1)),
					           # sharpen images
					           iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)),
					           # emboss images
					           # search either for all edges or for directed edges,
					           # blend the result with the original image using a blobby mask
					           iaa.SimplexNoiseAlpha(iaa.OneOf([
							           iaa.EdgeDetect(alpha=(0.5, 1.0)),
							           iaa.DirectedEdgeDetect(alpha=(0.5, 1.0),
							                                  direction=(0.0, 1.0)),
					           ])),
					           iaa.AdditiveGaussianNoise(loc=0,
					                                     scale=(0.0, 0.01 * 255),
					                                     per_channel=0.5),
					           # add gaussian noise to images
					           iaa.OneOf([
							           iaa.Dropout((0.01, 0.05), per_channel=0.5),
							           # randomly remove up to 10% of the pixels
							           iaa.CoarseDropout((0.01, 0.03),
							                             size_percent=(0.01, 0.02),
							                             per_channel=0.2),
					           ]),
					           iaa.Invert(0.01, per_channel=True),
					           # invert color channels
					           iaa.Add((-2, 2), per_channel=0.5),
					           # change brightness of images (by -10 to 10 of original value)
					           iaa.AddToHueAndSaturation((-1, 1)),
					           # change hue and saturation
					           # either change the brightness of the whole image (sometimes
					           # per channel) or change the brightness of subareas
					           iaa.OneOf([
							           iaa.Multiply((0.9, 1.1), per_channel=0.5),
							           iaa.FrequencyNoiseAlpha(
									           exponent=(-1, 0),
									           first=iaa.Multiply((0.9, 1.1),
									                              per_channel=True),
									           second=iaa.ContrastNormalization(
											           (0.9, 1.1))
							           )
					           ]),
					           sometimes(iaa.ElasticTransformation(alpha=(0.5, 3.5),
					                                               sigma=0.25)),
					           # move pixels locally around (with random strengths)
					           sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.05))),
					           # sometimes move parts of the image around
					           sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.1)))
				           ],
				           random_order=True
				           )
				],
				random_order=True
    )
Пример #25
0
def draw_per_augmenter_images():
    print("[draw_per_augmenter_images] Loading image...")
    #image = misc.imresize(ndimage.imread("quokka.jpg")[0:643, 0:643], (128, 128))
    image = ia.quokka_square(size=(128, 128))

    keypoints = [ia.Keypoint(x=34, y=15), ia.Keypoint(x=85, y=13), ia.Keypoint(x=63, y=73)] # left ear, right ear, mouth
    keypoints = [ia.KeypointsOnImage(keypoints, shape=image.shape)]

    print("[draw_per_augmenter_images] Initializing...")
    rows_augmenters = [
        (0, "Noop", [("", iaa.Noop()) for _ in sm.xrange(5)]),
        (0, "Crop\n(top, right,\nbottom, left)", [(str(vals), iaa.Crop(px=vals)) for vals in [(2, 0, 0, 0), (0, 8, 8, 0), (4, 0, 16, 4), (8, 0, 0, 32), (32, 64, 0, 0)]]),
        (0, "Pad\n(top, right,\nbottom, left)", [(str(vals), iaa.Pad(px=vals)) for vals in [(2, 0, 0, 0), (0, 8, 8, 0), (4, 0, 16, 4), (8, 0, 0, 32), (32, 64, 0, 0)]]),
        (0, "Fliplr", [(str(p), iaa.Fliplr(p)) for p in [0, 0, 1, 1, 1]]),
        (0, "Flipud", [(str(p), iaa.Flipud(p)) for p in [0, 0, 1, 1, 1]]),
        (0, "Superpixels\np_replace=1", [("n_segments=%d" % (n_segments,), iaa.Superpixels(p_replace=1.0, n_segments=n_segments)) for n_segments in [25, 50, 75, 100, 125]]),
        (0, "Superpixels\nn_segments=100", [("p_replace=%.2f" % (p_replace,), iaa.Superpixels(p_replace=p_replace, n_segments=100)) for p_replace in [0, 0.25, 0.5, 0.75, 1.0]]),
        (0, "Invert", [("p=%d" % (p,), iaa.Invert(p=p)) for p in [0, 0, 1, 1, 1]]),
        (0, "Invert\n(per_channel)", [("p=%.2f" % (p,), iaa.Invert(p=p, per_channel=True)) for p in [0.5, 0.5, 0.5, 0.5, 0.5]]),
        (0, "Add", [("value=%d" % (val,), iaa.Add(val)) for val in [-45, -25, 0, 25, 45]]),
        (0, "Add\n(per channel)", [("value=(%d, %d)" % (vals[0], vals[1],), iaa.Add(vals, per_channel=True)) for vals in [(-55, -35), (-35, -15), (-10, 10), (15, 35), (35, 55)]]),
        (0, "AddToHueAndSaturation", [("value=%d" % (val,), iaa.AddToHueAndSaturation(val)) for val in [-45, -25, 0, 25, 45]]),
        (0, "Multiply", [("value=%.2f" % (val,), iaa.Multiply(val)) for val in [0.25, 0.5, 1.0, 1.25, 1.5]]),
        (1, "Multiply\n(per channel)", [("value=(%.2f, %.2f)" % (vals[0], vals[1],), iaa.Multiply(vals, per_channel=True)) for vals in [(0.15, 0.35), (0.4, 0.6), (0.9, 1.1), (1.15, 1.35), (1.4, 1.6)]]),
        (0, "GaussianBlur", [("sigma=%.2f" % (sigma,), iaa.GaussianBlur(sigma=sigma)) for sigma in [0.25, 0.50, 1.0, 2.0, 4.0]]),
        (0, "AverageBlur", [("k=%d" % (k,), iaa.AverageBlur(k=k)) for k in [1, 3, 5, 7, 9]]),
        (0, "MedianBlur", [("k=%d" % (k,), iaa.MedianBlur(k=k)) for k in [1, 3, 5, 7, 9]]),
        (0, "BilateralBlur\nsigma_color=250,\nsigma_space=250", [("d=%d" % (d,), iaa.BilateralBlur(d=d, sigma_color=250, sigma_space=250)) for d in [1, 3, 5, 7, 9]]),
        (0, "Sharpen\n(alpha=1)", [("lightness=%.2f" % (lightness,), iaa.Sharpen(alpha=1, lightness=lightness)) for lightness in [0, 0.5, 1.0, 1.5, 2.0]]),
        (0, "Emboss\n(alpha=1)", [("strength=%.2f" % (strength,), iaa.Emboss(alpha=1, strength=strength)) for strength in [0, 0.5, 1.0, 1.5, 2.0]]),
        (0, "EdgeDetect", [("alpha=%.2f" % (alpha,), iaa.EdgeDetect(alpha=alpha)) for alpha in [0.0, 0.25, 0.5, 0.75, 1.0]]),
        (0, "DirectedEdgeDetect\n(alpha=1)", [("direction=%.2f" % (direction,), iaa.DirectedEdgeDetect(alpha=1, direction=direction)) for direction in [0.0, 1*(360/5)/360, 2*(360/5)/360, 3*(360/5)/360, 4*(360/5)/360]]),
        (0, "AdditiveGaussianNoise", [("scale=%.2f*255" % (scale,), iaa.AdditiveGaussianNoise(scale=scale * 255)) for scale in [0.025, 0.05, 0.1, 0.2, 0.3]]),
        (0, "AdditiveGaussianNoise\n(per channel)", [("scale=%.2f*255" % (scale,), iaa.AdditiveGaussianNoise(scale=scale * 255, per_channel=True)) for scale in [0.025, 0.05, 0.1, 0.2, 0.3]]),
        (0, "Dropout", [("p=%.2f" % (p,), iaa.Dropout(p=p)) for p in [0.025, 0.05, 0.1, 0.2, 0.4]]),
        (0, "Dropout\n(per channel)", [("p=%.2f" % (p,), iaa.Dropout(p=p, per_channel=True)) for p in [0.025, 0.05, 0.1, 0.2, 0.4]]),
        (3, "CoarseDropout\n(p=0.2)", [("size_percent=%.2f" % (size_percent,), iaa.CoarseDropout(p=0.2, size_percent=size_percent, min_size=2)) for size_percent in [0.3, 0.2, 0.1, 0.05, 0.02]]),
        (0, "CoarseDropout\n(p=0.2, per channel)", [("size_percent=%.2f" % (size_percent,), iaa.CoarseDropout(p=0.2, size_percent=size_percent, per_channel=True, min_size=2)) for size_percent in [0.3, 0.2, 0.1, 0.05, 0.02]]),
        (0, "SaltAndPepper", [("p=%.2f" % (p,), iaa.SaltAndPepper(p=p)) for p in [0.025, 0.05, 0.1, 0.2, 0.4]]),
        (0, "Salt", [("p=%.2f" % (p,), iaa.Salt(p=p)) for p in [0.025, 0.05, 0.1, 0.2, 0.4]]),
        (0, "Pepper", [("p=%.2f" % (p,), iaa.Pepper(p=p)) for p in [0.025, 0.05, 0.1, 0.2, 0.4]]),
        (0, "CoarseSaltAndPepper\n(p=0.2)", [("size_percent=%.2f" % (size_percent,), iaa.CoarseSaltAndPepper(p=0.2, size_percent=size_percent, min_size=2)) for size_percent in [0.3, 0.2, 0.1, 0.05, 0.02]]),
        (0, "CoarseSalt\n(p=0.2)", [("size_percent=%.2f" % (size_percent,), iaa.CoarseSalt(p=0.2, size_percent=size_percent, min_size=2)) for size_percent in [0.3, 0.2, 0.1, 0.05, 0.02]]),
        (0, "CoarsePepper\n(p=0.2)", [("size_percent=%.2f" % (size_percent,), iaa.CoarsePepper(p=0.2, size_percent=size_percent, min_size=2)) for size_percent in [0.3, 0.2, 0.1, 0.05, 0.02]]),
        (0, "ContrastNormalization", [("alpha=%.1f" % (alpha,), iaa.ContrastNormalization(alpha=alpha)) for alpha in [0.5, 0.75, 1.0, 1.25, 1.50]]),
        (0, "ContrastNormalization\n(per channel)", [("alpha=(%.2f, %.2f)" % (alphas[0], alphas[1],), iaa.ContrastNormalization(alpha=alphas, per_channel=True)) for alphas in [(0.4, 0.6), (0.65, 0.85), (0.9, 1.1), (1.15, 1.35), (1.4, 1.6)]]),
        (0, "Grayscale", [("alpha=%.1f" % (alpha,), iaa.Grayscale(alpha=alpha)) for alpha in [0.0, 0.25, 0.5, 0.75, 1.0]]),
        (6, "PerspectiveTransform", [("scale=%.3f" % (scale,), iaa.PerspectiveTransform(scale=scale)) for scale in [0.025, 0.05, 0.075, 0.10, 0.125]]),
        (0, "PiecewiseAffine", [("scale=%.3f" % (scale,), iaa.PiecewiseAffine(scale=scale)) for scale in [0.015, 0.03, 0.045, 0.06, 0.075]]),
        (0, "Affine: Scale", [("%.1fx" % (scale,), iaa.Affine(scale=scale)) for scale in [0.1, 0.5, 1.0, 1.5, 1.9]]),
        (0, "Affine: Translate", [("x=%d y=%d" % (x, y), iaa.Affine(translate_px={"x": x, "y": y})) for x, y in [(-32, -16), (-16, -32), (-16, -8), (16, 8), (16, 32)]]),
        (0, "Affine: Rotate", [("%d deg" % (rotate,), iaa.Affine(rotate=rotate)) for rotate in [-90, -45, 0, 45, 90]]),
        (0, "Affine: Shear", [("%d deg" % (shear,), iaa.Affine(shear=shear)) for shear in [-45, -25, 0, 25, 45]]),
        (0, "Affine: Modes", [(mode, iaa.Affine(translate_px=-32, mode=mode)) for mode in ["constant", "edge", "symmetric", "reflect", "wrap"]]),
        (0, "Affine: cval", [("%d" % (int(cval*255),), iaa.Affine(translate_px=-32, cval=int(cval*255), mode="constant")) for cval in [0.0, 0.25, 0.5, 0.75, 1.0]]),
        (
            2, "Affine: all", [
                (
                    "",
                    iaa.Affine(
                        scale={"x": (0.5, 1.5), "y": (0.5, 1.5)},
                        translate_px={"x": (-32, 32), "y": (-32, 32)},
                        rotate=(-45, 45),
                        shear=(-32, 32),
                        mode=ia.ALL,
                        cval=(0.0, 1.0)
                    )
                )
                for _ in sm.xrange(5)
            ]
        ),
        (1, "ElasticTransformation\n(sigma=0.2)", [("alpha=%.1f" % (alpha,), iaa.ElasticTransformation(alpha=alpha, sigma=0.2)) for alpha in [0.1, 0.5, 1.0, 3.0, 9.0]]),
        (0, "Alpha\nwith EdgeDetect(1.0)", [("factor=%.1f" % (factor,), iaa.Alpha(factor=factor, first=iaa.EdgeDetect(1.0))) for factor in [0.0, 0.25, 0.5, 0.75, 1.0]]),
        (4, "Alpha\nwith EdgeDetect(1.0)\n(per channel)", [("factor=(%.2f, %.2f)" % (factor[0], factor[1]), iaa.Alpha(factor=factor, first=iaa.EdgeDetect(1.0), per_channel=0.5)) for factor in [(0.0, 0.2), (0.15, 0.35), (0.4, 0.6), (0.65, 0.85), (0.8, 1.0)]]),
        (15, "SimplexNoiseAlpha\nwith EdgeDetect(1.0)", [("", iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(1.0))) for alpha in [0.0, 0.25, 0.5, 0.75, 1.0]]),
        (9, "FrequencyNoiseAlpha\nwith EdgeDetect(1.0)", [("exponent=%.1f" % (exponent,), iaa.FrequencyNoiseAlpha(exponent=exponent, first=iaa.EdgeDetect(1.0), size_px_max=16, upscale_method="linear", sigmoid=False)) for exponent in [-4, -2, 0, 2, 4]])
    ]

    print("[draw_per_augmenter_images] Augmenting...")
    rows = []
    for (row_seed, row_name, augmenters) in rows_augmenters:
        ia.seed(row_seed)
        #for img_title, augmenter in augmenters:
        #    #aug.reseed(1000)
        #    pass

        row_images = []
        row_keypoints = []
        row_titles = []
        for img_title, augmenter in augmenters:
            aug_det = augmenter.to_deterministic()
            row_images.append(aug_det.augment_image(image))
            row_keypoints.append(aug_det.augment_keypoints(keypoints)[0])
            row_titles.append(img_title)
        rows.append((row_name, row_images, row_keypoints, row_titles))

    # matplotlib drawin routine
    """
    print("[draw_per_augmenter_images] Plotting...")
    width = 8
    height = int(1.5 * len(rows_augmenters))
    fig = plt.figure(figsize=(width, height))
    grid_rows = len(rows)
    grid_cols = 1 + 5
    gs = gridspec.GridSpec(grid_rows, grid_cols, width_ratios=[2, 1, 1, 1, 1, 1])
    axes = []
    for i in sm.xrange(grid_rows):
        axes.append([plt.subplot(gs[i, col_idx]) for col_idx in sm.xrange(grid_cols)])
    fig.tight_layout()
    #fig.subplots_adjust(bottom=0.2 / grid_rows, hspace=0.22)
    #fig.subplots_adjust(wspace=0.005, hspace=0.425, bottom=0.02)
    fig.subplots_adjust(wspace=0.005, hspace=0.005, bottom=0.02)

    for row_idx, (row_name, row_images, row_keypoints, row_titles) in enumerate(rows):
        axes_row = axes[row_idx]

        for col_idx in sm.xrange(grid_cols):
            ax = axes_row[col_idx]

            ax.cla()
            ax.axis("off")
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

            if col_idx == 0:
                ax.text(0, 0.5, row_name, color="black")
            else:
                cell_image = row_images[col_idx-1]
                cell_keypoints = row_keypoints[col_idx-1]
                cell_image_kp = cell_keypoints.draw_on_image(cell_image, size=5)
                ax.imshow(cell_image_kp)
                x = 0
                y = 145
                #ax.text(x, y, row_titles[col_idx-1], color="black", backgroundcolor="white", fontsize=6)
                ax.text(x, y, row_titles[col_idx-1], color="black", fontsize=7)


    fig.savefig("examples.jpg", bbox_inches="tight")
    #plt.show()
    """

    # simpler and faster drawing routine
    """
    output_image = ExamplesImage(128, 128, 128+64, 32)
    for (row_name, row_images, row_keypoints, row_titles) in rows:
        row_images_kps = []
        for image, keypoints in zip(row_images, row_keypoints):
            row_images_kps.append(keypoints.draw_on_image(image, size=5))
        output_image.add_row(row_name, row_images_kps, row_titles)
    misc.imsave("examples.jpg", output_image.draw())
    """

    # routine to draw many single files
    seen = defaultdict(lambda: 0)
    markups = []
    for (row_name, row_images, row_keypoints, row_titles) in rows:
        output_image = ExamplesImage(128, 128, 128+64, 32)
        row_images_kps = []
        for image, keypoints in zip(row_images, row_keypoints):
            row_images_kps.append(keypoints.draw_on_image(image, size=5))
        output_image.add_row(row_name, row_images_kps, row_titles)
        if "\n" in row_name:
            row_name_clean = row_name[0:row_name.find("\n")+1]
        else:
            row_name_clean = row_name
        row_name_clean = re.sub(r"[^a-z0-9]+", "_", row_name_clean.lower())
        row_name_clean = row_name_clean.strip("_")
        if seen[row_name_clean] > 0:
            row_name_clean = "%s_%d" % (row_name_clean, seen[row_name_clean] + 1)
        fp = os.path.join(IMAGES_DIR, "examples_%s.jpg" % (row_name_clean,))
        #misc.imsave(fp, output_image.draw())
        save(fp, output_image.draw())
        seen[row_name_clean] += 1

        markup_descr = row_name.replace('"', '') \
                               .replace("\n", " ") \
                               .replace("(", "") \
                               .replace(")", "")
        markup = '![%s](%s?raw=true "%s")' % (markup_descr, fp, markup_descr)
        markups.append(markup)

    for markup in markups:
        print(markup)
Пример #26
0
def main():
    parser = argparse.ArgumentParser(description="Check augmenters visually.")
    parser.add_argument(
        "--only",
        default=None,
        help=
        "If this is set, then only the results of an augmenter with this name will be shown. "
        "Optionally, comma-separated list.",
        required=False)
    args = parser.parse_args()

    images = [
        ia.quokka_square(size=(128, 128)),
        ia.imresize_single_image(data.astronaut(), (128, 128))
    ]

    keypoints = [
        ia.KeypointsOnImage([
            ia.Keypoint(x=50, y=40),
            ia.Keypoint(x=70, y=38),
            ia.Keypoint(x=62, y=52)
        ],
                            shape=images[0].shape),
        ia.KeypointsOnImage([
            ia.Keypoint(x=55, y=32),
            ia.Keypoint(x=42, y=95),
            ia.Keypoint(x=75, y=89)
        ],
                            shape=images[1].shape)
    ]

    bounding_boxes = [
        ia.BoundingBoxesOnImage([
            ia.BoundingBox(x1=10, y1=10, x2=20, y2=20),
            ia.BoundingBox(x1=40, y1=50, x2=70, y2=60)
        ],
                                shape=images[0].shape),
        ia.BoundingBoxesOnImage([
            ia.BoundingBox(x1=10, y1=10, x2=20, y2=20),
            ia.BoundingBox(x1=40, y1=50, x2=70, y2=60)
        ],
                                shape=images[1].shape)
    ]

    augmenters = [
        iaa.Sequential([
            iaa.CoarseDropout(p=0.5, size_percent=0.05),
            iaa.AdditiveGaussianNoise(scale=0.1 * 255),
            iaa.Crop(percent=0.1)
        ],
                       name="Sequential"),
        iaa.SomeOf(2,
                   children=[
                       iaa.CoarseDropout(p=0.5, size_percent=0.05),
                       iaa.AdditiveGaussianNoise(scale=0.1 * 255),
                       iaa.Crop(percent=0.1)
                   ],
                   name="SomeOf"),
        iaa.OneOf(children=[
            iaa.CoarseDropout(p=0.5, size_percent=0.05),
            iaa.AdditiveGaussianNoise(scale=0.1 * 255),
            iaa.Crop(percent=0.1)
        ],
                  name="OneOf"),
        iaa.Sometimes(0.5,
                      iaa.AdditiveGaussianNoise(scale=0.1 * 255),
                      name="Sometimes"),
        iaa.WithColorspace("HSV",
                           children=[iaa.Add(20)],
                           name="WithColorspace"),
        iaa.WithChannels([0], children=[iaa.Add(20)], name="WithChannels"),
        iaa.AddToHueAndSaturation((-20, 20),
                                  per_channel=True,
                                  name="AddToHueAndSaturation"),
        iaa.Noop(name="Noop"),
        iaa.Resize({
            "width": 64,
            "height": 64
        }, name="Resize"),
        iaa.CropAndPad(px=(-8, 8), name="CropAndPad-px"),
        iaa.Pad(px=(0, 8), name="Pad-px"),
        iaa.Crop(px=(0, 8), name="Crop-px"),
        iaa.Crop(percent=(0, 0.1), name="Crop-percent"),
        iaa.Fliplr(0.5, name="Fliplr"),
        iaa.Flipud(0.5, name="Flipud"),
        iaa.Superpixels(p_replace=0.75, n_segments=50, name="Superpixels"),
        iaa.Grayscale(0.5, name="Grayscale0.5"),
        iaa.Grayscale(1.0, name="Grayscale1.0"),
        iaa.GaussianBlur((0, 3.0), name="GaussianBlur"),
        iaa.AverageBlur(k=(3, 11), name="AverageBlur"),
        iaa.MedianBlur(k=(3, 11), name="MedianBlur"),
        iaa.BilateralBlur(d=10, name="BilateralBlur"),
        iaa.Sharpen(alpha=(0.1, 1.0), lightness=(0, 2.0), name="Sharpen"),
        iaa.Emboss(alpha=(0.1, 1.0), strength=(0, 2.0), name="Emboss"),
        iaa.EdgeDetect(alpha=(0.1, 1.0), name="EdgeDetect"),
        iaa.DirectedEdgeDetect(alpha=(0.1, 1.0),
                               direction=(0, 1.0),
                               name="DirectedEdgeDetect"),
        iaa.Add((-50, 50), name="Add"),
        iaa.Add((-50, 50), per_channel=True, name="AddPerChannel"),
        iaa.AddElementwise((-50, 50), name="AddElementwise"),
        iaa.AdditiveGaussianNoise(loc=0,
                                  scale=(0.0, 0.1 * 255),
                                  name="AdditiveGaussianNoise"),
        iaa.Multiply((0.5, 1.5), name="Multiply"),
        iaa.Multiply((0.5, 1.5), per_channel=True, name="MultiplyPerChannel"),
        iaa.MultiplyElementwise((0.5, 1.5), name="MultiplyElementwise"),
        iaa.Dropout((0.0, 0.1), name="Dropout"),
        iaa.CoarseDropout(p=0.05,
                          size_percent=(0.05, 0.5),
                          name="CoarseDropout"),
        iaa.Invert(p=0.5, name="Invert"),
        iaa.Invert(p=0.5, per_channel=True, name="InvertPerChannel"),
        iaa.ContrastNormalization(alpha=(0.5, 2.0),
                                  name="ContrastNormalization"),
        iaa.SaltAndPepper(p=0.05, name="SaltAndPepper"),
        iaa.Salt(p=0.05, name="Salt"),
        iaa.Pepper(p=0.05, name="Pepper"),
        iaa.CoarseSaltAndPepper(p=0.05,
                                size_percent=(0.01, 0.1),
                                name="CoarseSaltAndPepper"),
        iaa.CoarseSalt(p=0.05, size_percent=(0.01, 0.1), name="CoarseSalt"),
        iaa.CoarsePepper(p=0.05, size_percent=(0.01, 0.1),
                         name="CoarsePepper"),
        iaa.Affine(scale={
            "x": (0.8, 1.2),
            "y": (0.8, 1.2)
        },
                   translate_px={
                       "x": (-16, 16),
                       "y": (-16, 16)
                   },
                   rotate=(-45, 45),
                   shear=(-16, 16),
                   order=ia.ALL,
                   cval=(0, 255),
                   mode=ia.ALL,
                   name="Affine"),
        iaa.PiecewiseAffine(scale=0.03,
                            nb_rows=(2, 6),
                            nb_cols=(2, 6),
                            name="PiecewiseAffine"),
        iaa.PerspectiveTransform(scale=0.1, name="PerspectiveTransform"),
        iaa.ElasticTransformation(alpha=(0.5, 8.0),
                                  sigma=1.0,
                                  name="ElasticTransformation"),
        iaa.Alpha(factor=(0.0, 1.0),
                  first=iaa.Add(100),
                  second=iaa.Dropout(0.5),
                  per_channel=False,
                  name="Alpha"),
        iaa.Alpha(factor=(0.0, 1.0),
                  first=iaa.Add(100),
                  second=iaa.Dropout(0.5),
                  per_channel=True,
                  name="AlphaPerChannel"),
        iaa.Alpha(factor=(0.0, 1.0),
                  first=iaa.Affine(rotate=(-45, 45)),
                  per_channel=True,
                  name="AlphaAffine"),
        iaa.AlphaElementwise(factor=(0.0, 1.0),
                             first=iaa.Add(50),
                             second=iaa.ContrastNormalization(2.0),
                             per_channel=False,
                             name="AlphaElementwise"),
        iaa.AlphaElementwise(factor=(0.0, 1.0),
                             first=iaa.Add(50),
                             second=iaa.ContrastNormalization(2.0),
                             per_channel=True,
                             name="AlphaElementwisePerChannel"),
        iaa.AlphaElementwise(factor=(0.0, 1.0),
                             first=iaa.Affine(rotate=(-45, 45)),
                             per_channel=True,
                             name="AlphaElementwiseAffine"),
        iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(1.0),
                              per_channel=False,
                              name="SimplexNoiseAlpha"),
        iaa.FrequencyNoiseAlpha(first=iaa.EdgeDetect(1.0),
                                per_channel=False,
                                name="FrequencyNoiseAlpha")
    ]

    augmenters.append(
        iaa.Sequential([iaa.Sometimes(0.2, aug.copy()) for aug in augmenters],
                       name="Sequential"))
    augmenters.append(
        iaa.Sometimes(0.5, [aug.copy() for aug in augmenters],
                      name="Sometimes"))

    for augmenter in augmenters:
        if args.only is None or augmenter.name in [
                v.strip() for v in args.only.split(",")
        ]:
            print("Augmenter: %s" % (augmenter.name, ))
            grid = []
            for image, kps, bbs in zip(images, keypoints, bounding_boxes):
                aug_det = augmenter.to_deterministic()
                imgs_aug = aug_det.augment_images(
                    np.tile(image[np.newaxis, ...], (16, 1, 1, 1)))
                kps_aug = aug_det.augment_keypoints([kps] * 16)
                bbs_aug = aug_det.augment_bounding_boxes([bbs] * 16)
                imgs_aug_drawn = [
                    kps_aug_one.draw_on_image(img_aug)
                    for img_aug, kps_aug_one in zip(imgs_aug, kps_aug)
                ]
                imgs_aug_drawn = [
                    bbs_aug_one.draw_on_image(img_aug)
                    for img_aug, bbs_aug_one in zip(imgs_aug_drawn, bbs_aug)
                ]
                grid.append(np.hstack(imgs_aug_drawn))
            ia.imshow(np.vstack(grid))
Пример #27
0
def data_aug(data_path):
	'''
	augment data
	increase data number
	generate 10 extra pictures from 1 picture 
	This function defines 13 different augment methods
	Everytime would choose 2 randomly and use the combination of these 2 methods to process all the images under the input data_path
	the processed data would still be under the original data directory
	'''
	list = list_all_files(data_path)#os.listdir(data_path) 
	for i in range(0,len(list)):
                #path = os.path.join(data_path,list[i])
		path =  list[i]

                #if os.path.isfile(path):
		try:
			img = cv2.imread(path)
			print("read path succeed: ",path)
			#print("image shape is: ", img.shape)
		except:
			print("Image read error. Please check the path again!")

		else:
                        #11 different kinds of pre-processing operators
                        #
			q1 = iaa.Alpha((0.0, 1.0),first=iaa.MedianBlur(9),per_channel=True)
			#alpha noise
			q2 = iaa.SimplexNoiseAlpha(first=iaa.EdgeDetect(0.5),per_channel=False)
			#noise in the frequency domain
			q3 = iaa.FrequencyNoiseAlpha(first=iaa.Affine(rotate=(-10, 10),translate_px={"x": (-4, 4), "y": (-4, 4)}),second=iaa.AddToHueAndSaturation((-40, 40)),per_channel=0.5)
			#set 5% of all the pixels black
			q4 = iaa.Dropout(p=0.05, per_channel=False, name=None, deterministic=False, random_state=None)
			#adjust contrast to make the image darker
			q5 = iaa.ContrastNormalization(alpha=1.5, per_channel=False, name=None, deterministic=False, random_state=None)
			#adjust contrast to make the image brighter
			q6 = iaa.ContrastNormalization(alpha=0.5, per_channel=False, name=None, deterministic=False, random_state=None)
			#16 pixels left
			q7 = iaa.Affine(translate_px={"x": -16})
			#sharpen
			q8 = iaa.Sharpen(alpha=0.15, lightness=1, name=None, deterministic=False, random_state=None)
			#emboss, like sharpen
			q9 = iaa.Emboss(alpha=1, strength=1, name=None, deterministic=False, random_state=None)
			#fliplr, upside down
			q10 = iaa.Fliplr(1.0)
			#gaussian blur
			q11 = iaa.GaussianBlur(3.0)
			#scale y axis randomly x0.8-1.2 
			q12 = iaa.Affine(scale={"y": (0.8, 1.2)})
			#scale x axis randomly x0.8-1.2
			q13 = iaa.Affine(scale={"x": (0.8, 1.2)})
			#randomly combine 2 of all the operations
			q = iaa.SomeOf(2,[q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11,q12,q13])
                        
                        #save_path1 = os.path.dirname(path) + "/aug1_" + path.split('/')[-1].split('.')[0] + ".jpg"
                        #print("save_path1 is : ", save_path1)
                        #save pre-processed images
			for i in range(10):
				#augment each image by 10 randomly chosen methods  
				img_aug = q.augment_images([img])
				print("img_aug type is:", type(img_aug))
				#generate save path
				save_path = os.path.dirname(path) + "/aug"+str(i)+"_" + path.split('/')[-1].split('.')[0] + ".jpg"
				#save images
				cv2.imwrite(save_path,img_aug[0])
Пример #28
0
def Augmentation(input_image):

    with tf.Graph().as_default():
        gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)
        sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options,
                                                log_device_placement=False))

        with sess.as_default():
            pnet, rnet, onet = detect_face.create_mtcnn(sess, './npy')

    sometimes = lambda aug: iaa.Sometimes(0.5, aug)

    aug_name = input_image.split("/")[-1].split(".")[0]

    minsize = 35  # minimum size of face
    threshold = [0.6, 0.7, 0.7]  # three steps's threshold
    factor = 0.709  # scale factor
    margin = 44
    image_size = 200

    nb_batches = 16

    aug_faces = []
    batches = []
    seq = iaa.Sequential(
        [
            iaa.Fliplr(0.5),
            sometimes(
                iaa.CropAndPad(
                    percent=(-0.05, 0.1), pad_mode=ia.ALL, pad_cval=(0, 255))),
            sometimes(
                iaa.Affine(scale={
                    "x": (0.8, 1.0),
                    "y": (0.8, 1.0)
                },
                           translate_percent={
                               "x": (-0.2, 0.2),
                               "y": (0, 0.2)
                           },
                           rotate=(-10, 10),
                           shear=(-16, 16),
                           order=[0, 1],
                           cval=(0, 255))),
            iaa.SomeOf(
                (0, 4),
                [
                    iaa.OneOf([
                        iaa.GaussianBlur((0, 3.0)),
                        iaa.AverageBlur(k=(2, 7)),
                        iaa.MedianBlur(k=(3, 11)),
                    ]),
                    iaa.Sharpen(alpha=(0, 1.0),
                                lightness=(0.75, 1.5)),  # sharpen images
                    iaa.Emboss(alpha=(0, 1.0),
                               strength=(0, 1.0)),  # emboss images
                    iaa.SimplexNoiseAlpha(
                        iaa.OneOf([
                            iaa.EdgeDetect(alpha=(0.2, 0.5)),
                            iaa.DirectedEdgeDetect(alpha=(0.2, 0.5),
                                                   direction=(0.0, 1.0)),
                        ])),
                    iaa.AdditiveGaussianNoise(
                        loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5),
                    iaa.Dropout((0.01, 0.1), per_channel=0.5),
                    iaa.Add((-10, 10), per_channel=0.5),
                    iaa.AddToHueAndSaturation((-20, 20)),
                    iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5),
                    iaa.Grayscale(alpha=(0.0, 1.0)),
                    sometimes(
                        iaa.ElasticTransformation(alpha=(0.5, 2), sigma=0.25)),
                    sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.03))),
                    sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.1)))
                ],
                random_order=True)
        ],
        random_order=True)
    img = misc.imread(input_image)
    if img.ndim < 2:
        print("Unable !")
    elif img.ndim == 2:
        img = facenet.to_rgb(img)
    img = img[:, :, 0:3]

    batches.append(np.array([img for _ in range(nb_batches)], dtype=np.uint8))

    aug_images = seq.augment_images(batches[0])

    for aug_img in aug_images:
        bounding_boxes, _ = detect_face.detect_face(aug_img, minsize, pnet,
                                                    rnet, onet, threshold,
                                                    factor)
        nrof_faces = bounding_boxes.shape[0]

        if nrof_faces > 0:
            det = bounding_boxes[:, 0:4]
            img_size = np.asarray(img.shape)[0:2]

            if nrof_faces > 1:
                bounding_box_size = (det[:, 2] - det[:, 0]) * (det[:, 3] -
                                                               det[:, 1])
                img_center = img_size / 2
                offsets = np.vstack([
                    (det[:, 0] + det[:, 2]) / 2 - img_center[1],
                    (det[:, 1] + det[:, 3]) / 2 - img_center[0]
                ])

                offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
                index = np.argmax(bounding_box_size -
                                  offset_dist_squared * 2.0)
                det = det[index, :]

            det = np.squeeze(det)
            bb_temp = np.zeros(4, dtype=np.int32)

            bb_temp[0] = det[0]
            bb_temp[1] = det[1]
            bb_temp[2] = det[2]
            bb_temp[3] = det[3]

            cropped_temp = aug_img[bb_temp[1]:bb_temp[3],
                                   bb_temp[0]:bb_temp[2], :]
            scaled_temp = misc.imresize(cropped_temp, (image_size, image_size),
                                        interp='bilinear')
            aug_faces.append(scaled_temp)

    return aug_faces
Пример #29
0
def example_very_complex_augmentation_pipeline():
    print("Example: Very Complex Augmentation Pipeline")
    import numpy as np
    import imgaug as ia
    import imgaug.augmenters as iaa

    # random example images
    images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)

    # Sometimes(0.5, ...) applies the given augmenter in 50% of all cases,
    # e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second image.
    sometimes = lambda aug: iaa.Sometimes(0.5, aug)

    # Define our sequence of augmentation steps that will be applied to every image
    # All augmenters with per_channel=0.5 will sample one value _per image_
    # in 50% of all cases. In all other cases they will sample new values
    # _per channel_.

    seq = iaa.Sequential(
        [
            # apply the following augmenters to most images
            iaa.Fliplr(0.5),  # horizontally flip 50% of all images
            iaa.Flipud(0.2),  # vertically flip 20% of all images
            # crop images by -5% to 10% of their height/width
            sometimes(
                iaa.CropAndPad(
                    percent=(-0.05, 0.1), pad_mode=ia.ALL, pad_cval=(0, 255))),
            sometimes(
                iaa.Affine(
                    scale={
                        "x": (0.8, 1.2),
                        "y": (0.8, 1.2)
                    },  # scale images to 80-120% of their size, individually per axis
                    translate_percent={
                        "x": (-0.2, 0.2),
                        "y": (-0.2, 0.2)
                    },  # translate by -20 to +20 percent (per axis)
                    rotate=(-45, 45),  # rotate by -45 to +45 degrees
                    shear=(-16, 16),  # shear by -16 to +16 degrees
                    order=[
                        0,
                        1
                    ],  # use nearest neighbour or bilinear interpolation (fast)
                    cval=(
                        0, 255
                    ),  # if mode is constant, use a cval between 0 and 255
                    mode=ia.
                    ALL  # use any of scikit-image's warping modes (see 2nd image from the top for examples)
                )),
            # execute 0 to 5 of the following (less important) augmenters per image
            # don't execute all of them, as that would often be way too strong
            iaa.SomeOf(
                (0, 5),
                [
                    sometimes(
                        iaa.Superpixels(p_replace=(0, 1.0),
                                        n_segments=(20, 200))
                    ),  # convert images into their superpixel representation
                    iaa.OneOf([
                        iaa.GaussianBlur(
                            (0, 3.0
                             )),  # blur images with a sigma between 0 and 3.0
                        iaa.AverageBlur(
                            k=(2, 7)
                        ),  # blur image using local means with kernel sizes between 2 and 7
                        iaa.MedianBlur(
                            k=(3, 11)
                        ),  # blur image using local medians with kernel sizes between 2 and 7
                    ]),
                    iaa.Sharpen(alpha=(0, 1.0),
                                lightness=(0.75, 1.5)),  # sharpen images
                    iaa.Emboss(alpha=(0, 1.0),
                               strength=(0, 2.0)),  # emboss images
                    # search either for all edges or for directed edges,
                    # blend the result with the original image using a blobby mask
                    iaa.SimplexNoiseAlpha(
                        iaa.OneOf([
                            iaa.EdgeDetect(alpha=(0.5, 1.0)),
                            iaa.DirectedEdgeDetect(alpha=(0.5, 1.0),
                                                   direction=(0.0, 1.0)),
                        ])),
                    iaa.AdditiveGaussianNoise(
                        loc=0, scale=(0.0, 0.05 * 255),
                        per_channel=0.5),  # add gaussian noise to images
                    iaa.OneOf([
                        iaa.Dropout(
                            (0.01, 0.1), per_channel=0.5
                        ),  # randomly remove up to 10% of the pixels
                        iaa.CoarseDropout((0.03, 0.15),
                                          size_percent=(0.02, 0.05),
                                          per_channel=0.2),
                    ]),
                    iaa.Invert(0.05,
                               per_channel=True),  # invert color channels
                    iaa.Add(
                        (-10, 10), per_channel=0.5
                    ),  # change brightness of images (by -10 to 10 of original value)
                    iaa.AddToHueAndSaturation(
                        (-20, 20)),  # change hue and saturation
                    # either change the brightness of the whole image (sometimes
                    # per channel) or change the brightness of subareas
                    iaa.OneOf([
                        iaa.Multiply((0.5, 1.5), per_channel=0.5),
                        iaa.FrequencyNoiseAlpha(
                            exponent=(-4, 0),
                            first=iaa.Multiply((0.5, 1.5), per_channel=True),
                            second=iaa.LinearContrast((0.5, 2.0)))
                    ]),
                    iaa.LinearContrast(
                        (0.5, 2.0),
                        per_channel=0.5),  # improve or worsen the contrast
                    iaa.Grayscale(alpha=(0.0, 1.0)),
                    sometimes(
                        iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)
                    ),  # move pixels locally around (with random strengths)
                    sometimes(iaa.PiecewiseAffine(scale=(
                        0.01,
                        0.05))),  # sometimes move parts of the image around
                    sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.1)))
                ],
                random_order=True)
        ],
        random_order=True)
    images_aug = seq(images=images)

    # -----
    # Make sure that the example really does something
    assert not np.array_equal(images, images_aug)
Пример #30
0
def get_optimistic_img_aug():
    texture = iaa.OneOf([
        iaa.Superpixels(p_replace=(0.1, 0.3),
                        n_segments=(500, 1000),
                        interpolation="cubic",
                        name='Superpixels'),
        iaa.Sharpen(alpha=(0, 1.0), lightness=(0.5, 1.0), name='Sharpen'),
        iaa.Emboss(alpha=(0, 1.0), strength=(0.1, 0.3), name='Emboss'),
        iaa.OneOf([
            iaa.EdgeDetect(alpha=(0, 0.4)),
            iaa.DirectedEdgeDetect(alpha=(0, 0.7), direction=(0.0, 1.0)),
        ],
                  name='EdgeDetect'),
        iaa.ElasticTransformation(alpha=(0.5, 1.0),
                                  sigma=0.2,
                                  name='ElasticTransformation'),
    ])

    blur = iaa.OneOf([
        iaa.GaussianBlur((1, 5.0), name='GaussianBlur'),
        iaa.AverageBlur(k=(2, 15), name='AverageBlur'),
        iaa.MedianBlur(k=(3, 15), name='MedianBlur'),
        iaa.BilateralBlur(d=(3, 15),
                          sigma_color=(10, 250),
                          sigma_space=(10, 250),
                          name='BilaBlur'),
    ])

    affine = iaa.OneOf([
        iaa.Affine(rotate=(-3, 3)),
        iaa.Affine(translate_percent={
            "x": (0.95, 1.05),
            "y": (0.95, 1.05)
        }),
        iaa.Affine(scale={
            "x": (0.95, 1.05),
            "y": (0.95, 1.05)
        }),
        iaa.Affine(shear=(-2, 2)),
    ])

    factors = iaa.OneOf([
        iaa.Multiply(iap.Choice([0.75, 1.25]), per_channel=False),
        iaa.EdgeDetect(1.0),
    ])

    seq = iaa.Sequential(
        [

            # Size and shape ==================================================
            iaa.Sequential([
                iaa.Fliplr(0.5),
                iaa.OneOf([
                    iaa.Noop(),
                    iaa.Affine(rotate=90),
                    iaa.Affine(rotate=180),
                    iaa.Affine(rotate=270),
                ]),
                half_times(
                    iaa.SomeOf(
                        (1, 2),
                        [
                            iaa.Crop(percent=(0.1, 0.4)),  # Random Crops
                            iaa.PerspectiveTransform(scale=(0.10, 0.175)),
                            iaa.PiecewiseAffine(scale=(0.01, 0.06),
                                                nb_rows=(3, 6),
                                                nb_cols=(3, 6)),
                        ])),
            ]),

            # Texture ==================================================
            sometimes(
                iaa.SomeOf((1, 2), [
                    texture,
                    iaa.Alpha((0.0, 1.0), first=texture, per_channel=False)
                ],
                           random_order=True,
                           name='Texture')),
            half_times(
                iaa.SomeOf((1, 2), [
                    blur,
                    iaa.Alpha((0.0, 1.0), first=blur, per_channel=False),
                    iaa.Alpha(factor=(0.2, 0.8),
                              first=iaa.Sequential([
                                  affine,
                                  blur,
                              ]),
                              per_channel=False),
                ],
                           random_order=True,
                           name='Blur')),
            # Noise ==================================================
            sometimes(
                iaa.SomeOf(
                    (1, 2),
                    [
                        # Just noise
                        iaa.AdditiveGaussianNoise(
                            loc=0,
                            scale=(0.0, 0.15 * 255),
                            per_channel=False,
                            name='AdditiveGaussianNoise'),
                        iaa.SaltAndPepper(
                            0.05, per_channel=False, name='SaltAndPepper'),

                        # Regularization
                        iaa.Dropout(
                            (0.01, 0.1), per_channel=False, name='Dropout'),
                        iaa.CoarseDropout((0.03, 0.15),
                                          size_percent=(0.02, 0.05),
                                          per_channel=False,
                                          name='CoarseDropout'),
                        iaa.Alpha(
                            factor=(0.2, 0.8),
                            first=texture,
                            second=iaa.CoarseDropout(
                                p=0.1, size_percent=(0.02, 0.05)),
                            per_channel=False,
                        ),

                        # Perlin style noise
                        iaa.SimplexNoiseAlpha(first=factors,
                                              per_channel=False,
                                              aggregation_method="max",
                                              sigmoid=False,
                                              upscale_method='cubic',
                                              size_px_max=(2, 12),
                                              name='SimplexNoiseAlpha'),
                        iaa.FrequencyNoiseAlpha(first=factors,
                                                per_channel=False,
                                                aggregation_method="max",
                                                sigmoid=False,
                                                upscale_method='cubic',
                                                size_px_max=(2, 12),
                                                name='FrequencyNoiseAlpha'),
                    ],
                    random_order=True,
                    name='Noise')),
        ],
        random_order=False)

    def activator_masks(images, augmenter, parents, default):
        if 'Unnamed' not in augmenter.name:
            return False
        else:
            return default

    hooks_masks = ia.HooksImages(activator=activator_masks)

    return seq, hooks_masks