Python源码示例:imgaug.augmenters.Add()

示例1
def example_withchannels():
    print("Example: WithChannels")
    import numpy as np
    import imgaug.augmenters as iaa

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

    # add a random value from the range (-30, 30) to the first two channels of
    # input images (e.g. to the R and G channels)
    aug = iaa.WithChannels(
      channels=[0, 1],
      children=iaa.Add((-30, 30))
    )

    images_aug = aug(images=images) 
示例2
def main():
    image = data.astronaut()
    print("image shape:", image.shape)

    aug = iaa.WithColorspace(
        from_colorspace="RGB",
        to_colorspace="HSV",
        children=iaa.WithChannels(0, iaa.Add(50))
    )

    aug_no_colorspace = iaa.WithChannels(0, iaa.Add(50))

    img_show = np.hstack([
        image,
        aug.augment_image(image),
        aug_no_colorspace.augment_image(image)
    ])
    ia.imshow(img_show) 
示例3
def test_images_factor_is_tuple(self):
        image = np.zeros((1, 2, 1), dtype=np.uint8)
        nb_iterations = 1000
        aug = iaa.BlendAlpha((0.0, 1.0), iaa.Add(10), iaa.Add(110))
        values = []
        for _ in sm.xrange(nb_iterations):
            observed = aug.augment_image(image)
            observed_val = np.round(np.average(observed)) - 10
            values.append(observed_val / 100)

        nb_bins = 5
        hist, _ = np.histogram(values, bins=nb_bins, range=(0.0, 1.0),
                               density=False)
        density_expected = 1.0/nb_bins
        density_tolerance = 0.05
        for nb_samples in hist:
            density = nb_samples / nb_iterations
            assert np.isclose(density, density_expected,
                              rtol=0, atol=density_tolerance) 
示例4
def test_images_float_as_per_channel_tuple_as_factor_two_branches(self):
        aug = iaa.BlendAlpha(
            (0.0, 1.0),
            iaa.Add(100),
            iaa.Add(0),
            per_channel=0.5)
        seen = [0, 0]
        for _ in sm.xrange(200):
            observed = aug.augment_image(np.zeros((1, 1, 100), dtype=np.uint8))
            uq = np.unique(observed)
            if len(uq) == 1:
                seen[0] += 1
            elif len(uq) > 1:
                seen[1] += 1
            else:
                assert False
        assert 100 - 50 < seen[0] < 100 + 50
        assert 100 - 50 < seen[1] < 100 + 50 
示例5
def test_unusual_channel_numbers(self):
        shapes = [
            (1, 1, 4),
            (1, 1, 5),
            (1, 1, 512),
            (1, 1, 513)
        ]

        for shape in shapes:
            with self.subTest(shape=shape):
                image = np.full(shape, 0, dtype=np.uint8)
                aug = iaa.BlendAlpha(1.0, iaa.Add(1), iaa.Add(100))

                image_aug = aug(image=image)

                assert np.all(image_aug == 1)
                assert image_aug.dtype.name == "uint8"
                assert image_aug.shape == shape 
示例6
def test_hooks_limiting_propagation(self):
        aug = iaa.BlendAlphaElementwise(
            0.5,
            iaa.Add(100),
            iaa.Add(50),
            name="AlphaElementwiseTest")

        def propagator(images, augmenter, parents, default):
            if "AlphaElementwise" in augmenter.name:
                return False
            else:
                return default

        hooks = ia.HooksImages(propagator=propagator)
        image = np.zeros((10, 10, 3), dtype=np.uint8) + 10
        observed = aug.augment_image(image, hooks=hooks)
        assert np.array_equal(observed, image) 
示例7
def test_zero_sized_axes(self):
        shapes = [
            (0, 0),
            (0, 1),
            (1, 0),
            (0, 1, 0),
            (1, 0, 0),
            (0, 1, 1),
            (1, 0, 1)
        ]

        for shape in shapes:
            with self.subTest(shape=shape):
                image = np.full(shape, 0, dtype=np.uint8)
                aug = iaa.BlendAlpha(1.0, iaa.Add(1), iaa.Add(100))

                image_aug = aug(image=image)

                assert np.all(image_aug == 1)
                assert image_aug.dtype.name == "uint8"
                assert image_aug.shape == shape 
示例8
def test_unusual_channel_numbers(self):
        shapes = [
            (1, 1, 4),
            (1, 1, 5),
            (1, 1, 512),
            (1, 1, 513)
        ]

        for shape in shapes:
            with self.subTest(shape=shape):
                image = np.full(shape, 0, dtype=np.uint8)
                aug = iaa.BlendAlpha(1.0, iaa.Add(1), iaa.Add(100))

                image_aug = aug(image=image)

                assert np.all(image_aug == 1)
                assert image_aug.dtype.name == "uint8"
                assert image_aug.shape == shape 
示例9
def test_pickleable(self):
        shape = (15, 15, 3)
        iterations = 3
        augmenter = iaa.BlendAlphaBoundingBoxes(
            ["bb1", "bb2", "bb3"],
            foreground=iaa.Add((1, 10), seed=1),
            background=iaa.Add((11, 20), seed=2),
            nb_sample_labels=1,
            seed=3)
        image = np.mod(np.arange(int(np.prod(shape))), 256).astype(np.uint8)
        image = image.reshape(shape)
        bbs = [ia.BoundingBox(x1=1, y1=1, x2=5, y2=5, label="bb1"),
               ia.BoundingBox(x1=-3, y1=4, x2=20, y2=8, label="bb2")]

        augmenter_pkl = pickle.loads(pickle.dumps(augmenter, protocol=-1))

        for _ in np.arange(iterations):
            image_aug, bbs_aug = augmenter(
                image=image, bounding_boxes=[bbs])
            image_aug_pkl, bbs_aug_pkl = augmenter_pkl(
                image=image, bounding_boxes=[bbs])
            assert np.array_equal(image_aug, image_aug_pkl) 
示例10
def test_n(self, mock_main, mock_initial):
        mock_main.return_value = [iaa.Add(1), iaa.Add(2), iaa.Add(4)]
        mock_initial.return_value = []

        img = np.zeros((1, 1, 3), dtype=np.uint8)
        expected = {
            0: [0],
            1: [1, 2, 4],
            2: [1+1, 1+2, 1+4, 2+2, 2+4, 4+4]
        }

        for n in [0, 1, 2]:
            with self.subTest(n=n):
                aug = iaa.RandAugment(n=n)
                img_aug = aug(image=img)
                assert img_aug[0, 0, 0] in expected[n]

    # for some reason these mocks don't work with
    # imgaug.augmenters.collections.(...) 
示例11
def __init__(self):
        self.seq = iaa.Sequential([
            iaa.Sometimes(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.Sometimes(0.5, iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5)),
            iaa.Sometimes(0.5, iaa.Add((-10, 10), per_channel=0.5)),
            iaa.Sometimes(0.5, iaa.AddToHueAndSaturation((-20, 20))),
            iaa.Sometimes(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.Sometimes(0.5, iaa.PiecewiseAffine(scale=(0.01, 0.05))),
            iaa.Sometimes(0.5, iaa.PerspectiveTransform(scale=(0.01, 0.1)))
        ], random_order=True) 
示例12
def __init__(self, augmentation_rate):
        self.augs = iaa.Sometimes(
            augmentation_rate,
            iaa.SomeOf(
                (4, 7),
                [
                    iaa.Affine(rotate=(-10, 10)),
                    iaa.Fliplr(0.2),
                    iaa.AverageBlur(k=(2, 10)),
                    iaa.Add((-10, 10), per_channel=0.5),
                    iaa.Multiply((0.75, 1.25), per_channel=0.5),
                    iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5),
                    iaa.Crop(px=(0, 20))
                ],
                random_order=True
            )
        ) 
示例13
def main():
    image = data.astronaut()
    print("image shape:", image.shape)

    aug = iaa.WithColorspace(
        from_colorspace="RGB",
        to_colorspace="HSV",
        children=iaa.WithChannels(0, iaa.Add(50))
    )

    aug_no_colorspace = iaa.WithChannels(0, iaa.Add(50))

    img_show = np.hstack([
        image,
        aug.augment_image(image),
        aug_no_colorspace.augment_image(image)
    ])
    misc.imshow(img_show) 
示例14
def example_withchannels():
    print("Example: WithChannels")
    from imgaug import augmenters as iaa
    import numpy as np

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

    # add a random value from the range (-30, 30) to the first two channels of
    # input images (e.g. to the R and G channels)
    aug = iaa.WithChannels(
      channels=[0, 1],
      children=iaa.Add((-30, 30))
    )

    images_aug = aug.augment_images(images) 
示例15
def __init__(self):
        self.imgaug_transform = iaa.Sequential(
            [iaa.Multiply((1.5, 1.5), per_channel=False), iaa.Add((127, 127), per_channel=False)]
        )
        self.augmentor_pipeline = Pipeline()
        self.augmentor_pipeline.add_operation(
            Operations.RandomBrightness(probability=1, min_factor=1.5, max_factor=1.5)
        )
        self.augmentor_pipeline.add_operation(Operations.RandomContrast(probability=1, min_factor=1.5, max_factor=1.5))
        self.solt_stream = slc.Stream(
            [
                slt.ImageRandomBrightness(p=1, brightness_range=(127, 127)),
                slt.ImageRandomContrast(p=1, contrast_range=(1.5, 1.5)),
            ]
        ) 
示例16
def __init__(self,data_dir, back_dir,
                 batch_size=50,gan=True,imsize=128,
                 res_x=640,res_y=480,
                 **kwargs):
        '''
        data_dir: Folder that contains cropped image+xyz
        back_dir: Folder that contains random background images
            batch_size: batch size for training
        gan: if False, gt for GAN is not yielded
        '''
        self.data_dir = data_dir
        self.back_dir = back_dir
        self.imsize=imsize
        self.batch_size = batch_size
        self.gan = gan
        self.backfiles = os.listdir(back_dir)
        data_list = os.listdir(data_dir)
        self.datafiles=[]
        self.res_x=res_x
        self.res_y=res_y

        for file in data_list:
            if(file.endswith(".npy")):
                self.datafiles.append(file)

        self.n_data = len(self.datafiles)
        self.n_background = len(self.backfiles)
        print("Total training views:", self.n_data)

        self.seq_syn= iaa.Sequential([
                                    iaa.WithChannels(0, iaa.Add((-15, 15))),
                                    iaa.WithChannels(1, iaa.Add((-15, 15))),
                                    iaa.WithChannels(2, iaa.Add((-15, 15))),
                                    iaa.ContrastNormalization((0.8, 1.3)),
                                    iaa.Multiply((0.8, 1.2),per_channel=0.5),
                                    iaa.GaussianBlur(sigma=(0.0, 0.5)),
                                    iaa.Sometimes(0.1, iaa.AdditiveGaussianNoise(scale=10, per_channel=True)),
                                    iaa.Sometimes(0.5, iaa.ContrastNormalization((0.5, 2.2), per_channel=0.3)),
                                    ], random_order=True) 
示例17
def main():
    image = ia.quokka_square(size=(128, 128))
    images = []

    for i in range(15):
        aug = iaa.WithHueAndSaturation(iaa.WithChannels(0, iaa.Add(i*20)))
        images.append(aug.augment_image(image))

    for i in range(15):
        aug = iaa.WithHueAndSaturation(iaa.WithChannels(1, iaa.Add(i*20)))
        images.append(aug.augment_image(image))

    ia.imshow(ia.draw_grid(images, rows=2)) 
示例18
def main():
    image = data.astronaut()
    print("image shape:", image.shape)
    print("Press ENTER or wait %d ms to proceed to the next image." % (TIME_PER_STEP,))

    children_all = [
        ("hflip", iaa.Fliplr(1)),
        ("add", iaa.Add(50)),
        ("dropout", iaa.Dropout(0.2)),
        ("affine", iaa.Affine(rotate=35))
    ]

    channels_all = [
        None,
        0,
        [],
        [0],
        [0, 1],
        [1, 2],
        [0, 1, 2]
    ]

    cv2.namedWindow("aug", cv2.WINDOW_NORMAL)
    cv2.imshow("aug", image[..., ::-1])
    cv2.waitKey(TIME_PER_STEP)

    for children_title, children in children_all:
        for channels in channels_all:
            aug = iaa.WithChannels(channels=channels, children=children)
            img_aug = aug.augment_image(image)
            print("dtype", img_aug.dtype, "averages", np.average(img_aug, axis=tuple(range(0, img_aug.ndim-1))))

            title = "children=%s " channels=%s" % (children_title, channels)
            img_aug = ia.draw_text(img_aug, x=5, y=5, text=title)

            cv2.imshow("aug", img_aug[..., ::-1])  # here with rgb2bgr
            cv2.waitKey(TIME_PER_STEP) 
示例19
def test_images_factor_is_0(self):
        aug = iaa.BlendAlpha(0, iaa.Add(10), iaa.Add(20))
        observed = aug.augment_image(self.image)
        expected = np.round(self.image + 20).astype(np.uint8)
        assert np.allclose(observed, expected) 
示例20
def test_images_factor_is_075(self):
        aug = iaa.BlendAlpha(0.75, iaa.Add(10), iaa.Add(20))
        observed = aug.augment_image(self.image)
        expected = np.round(
            self.image
            + 0.75 * 10
            + 0.25 * 20
        ).astype(np.uint8)
        assert np.allclose(observed, expected) 
示例21
def test_images_factor_is_075_fg_branch_is_none(self):
        aug = iaa.BlendAlpha(0.75, None, iaa.Add(20))
        observed = aug.augment_image(self.image + 10)
        expected = np.round(
            self.image
            + 0.75 * 10
            + 0.25 * (10 + 20)
        ).astype(np.uint8)
        assert np.allclose(observed, expected) 
示例22
def test_images_factor_is_075_bg_branch_is_none(self):
        aug = iaa.BlendAlpha(0.75, iaa.Add(10), None)
        observed = aug.augment_image(self.image + 10)
        expected = np.round(
            self.image
            + 0.75 * (10 + 10)
            + 0.25 * 10
        ).astype(np.uint8)
        assert np.allclose(observed, expected) 
示例23
def test_images_with_per_channel_in_both_alpha_and_child(self):
        image = np.zeros((1, 1, 1000), dtype=np.uint8)
        aug = iaa.BlendAlpha(
            1.0,
            iaa.Add((0, 100), per_channel=True),
            None,
            per_channel=True)
        observed = aug.augment_image(image)
        uq = np.unique(observed)
        assert len(uq) > 1
        assert np.max(observed) > 80
        assert np.min(observed) < 20 
示例24
def test_images_with_per_channel_in_alpha_and_tuple_as_factor(self):
        image = np.zeros((1, 1, 1000), dtype=np.uint8)
        aug = iaa.BlendAlpha(
            (0.0, 1.0),
            iaa.Add(100),
            None,
            per_channel=True)
        observed = aug.augment_image(image)
        uq = np.unique(observed)
        assert len(uq) > 1
        assert np.max(observed) > 80
        assert np.min(observed) < 20 
示例25
def test_bad_datatype_for_per_channel_fails(self):
        # bad datatype for per_channel
        got_exception = False
        try:
            _ = iaa.BlendAlpha(0.5, iaa.Add(10), None, per_channel="test")
        except Exception as exc:
            assert "Expected " in str(exc)
            got_exception = True
        assert got_exception 
示例26
def test_hooks_limiting_propagation(self):
        aug = iaa.BlendAlpha(0.5, iaa.Add(100), iaa.Add(50), name="AlphaTest")

        def propagator(images, augmenter, parents, default):
            if "Alpha" in augmenter.name:
                return False
            else:
                return default

        hooks = ia.HooksImages(propagator=propagator)
        image = np.zeros((10, 10, 3), dtype=np.uint8) + 1
        observed = aug.augment_image(image, hooks=hooks)
        assert np.array_equal(observed, image) 
示例27
def test_get_parameters(self):
        fg = iaa.Identity()
        bg = iaa.Sequential([iaa.Add(1)])
        aug = iaa.BlendAlpha(0.65, fg, bg, per_channel=1)
        params = aug.get_parameters()
        assert params[0] is aug.factor
        assert params[1] is aug.per_channel
        assert 0.65 - 1e-6 < params[0].value < 0.65 + 1e-6
        assert params[1].value == 1 
示例28
def test_get_children_lists(self):
        fg = iaa.Identity()
        bg = iaa.Sequential([iaa.Add(1)])
        aug = iaa.BlendAlpha(0.65, fg, bg, per_channel=1)
        children_lsts = aug.get_children_lists()
        assert len(children_lsts) == 2
        assert ia.is_iterable([lst for lst in children_lsts])
        assert fg in children_lsts[0]
        assert bg == children_lsts[1] 
示例29
def test_pickleable(self):
        aug = iaa.BlendAlpha(
            (0.1, 0.9),
            iaa.Add((1, 10), seed=1),
            iaa.Add((11, 20), seed=2),
            per_channel=True,
            seed=3)
        runtest_pickleable_uint8_img(aug, iterations=10) 
示例30
def test_images_factor_is_1(self):
        aug = iaa.BlendAlphaElementwise(1, iaa.Add(10), iaa.Add(20))
        observed = aug.augment_image(self.image)
        expected = self.image + 10
        assert np.allclose(observed, expected)