Exemplo n.º 1
0
    def _test_augment_polygons__kernel_size_differs(self, shape, shape_exp):
        from imgaug.augmentables.polys import Polygon, PolygonsOnImage
        polys = [Polygon([(1.5, 5.5), (5.5, 1.5), (5.5, 5.5)])]
        psoi = PolygonsOnImage(polys, shape=shape)
        aug = self.augmenter(
            (iap.Deterministic(3), iap.Deterministic(2)),
            keep_size=False)

        psoi_aug = aug.augment_polygons(psoi)

        expected = PolygonsOnImage(
            [Polygon([
                ((1.5/shape[1])*shape_exp[1], (5.5/shape[0])*shape_exp[0]),
                ((5.5/shape[1])*shape_exp[1], (1.5/shape[0])*shape_exp[0]),
                ((5.5/shape[1])*shape_exp[1], (5.5/shape[0])*shape_exp[0])
            ])],
            shape=shape_exp)
        assert_cbaois_equal(psoi_aug, expected)
Exemplo n.º 2
0
    def _test_augment_keypoints__kernel_size_differs(self, shape,
                                                     shape_exp):
        from imgaug.augmentables.kps import Keypoint, KeypointsOnImage
        kps = [Keypoint(x=1.5, y=5.5), Keypoint(x=5.5, y=1.5)]
        kpsoi = KeypointsOnImage(kps, shape=shape)
        aug = self.augmenter(
            (iap.Deterministic(3), iap.Deterministic(2)),
            keep_size=False)

        kpsoi_aug = aug.augment_keypoints(kpsoi)

        expected = KeypointsOnImage.from_xy_array(
            np.float32([
                [(1.5/shape[1])*shape_exp[1], (5.5/shape[0])*shape_exp[0]],
                [(5.5/shape[1])*shape_exp[1], (1.5/shape[0])*shape_exp[0]]
            ]),
            shape=shape_exp)
        assert_cbaois_equal(kpsoi_aug, expected)
Exemplo n.º 3
0
    def test_augment_images__kernel_size_differs(self):
        aug = iaa.AveragePooling((iap.Deterministic(3), iap.Deterministic(2)),
                                 keep_size=False)

        image = np.uint8([
            [50 - 2, 50 - 1, 120 - 4, 120 + 4],
            [50 + 1, 50 + 2, 120 + 2, 120 - 1],
            [50 - 5, 50 + 5, 120 - 2, 120 + 1],
        ])
        image = np.tile(image[:, :, np.newaxis], (1, 1, 3))

        expected = np.uint8([[50, 120]])
        expected = np.tile(expected[:, :, np.newaxis], (1, 1, 3))

        image_aug = aug.augment_image(image)
        diff = np.abs(image_aug.astype(np.int32) - expected)
        assert image_aug.dtype.name == "uint8"
        assert image_aug.shape == (1, 2, 3)
        assert np.all(diff <= 1)
Exemplo n.º 4
0
    def _test_augment_bounding_boxes__kernel_size_differs(
            self, shape, shape_exp):
        from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage
        bbs = [BoundingBox(x1=1.5, y1=2.5, x2=5.5, y2=6.5)]
        bbsoi = BoundingBoxesOnImage(bbs, shape=shape)
        aug = self.augmenter((iap.Deterministic(3), iap.Deterministic(2)),
                             keep_size=False)

        bbsoi_aug = aug.augment_bounding_boxes(bbsoi)

        expected = BoundingBoxesOnImage([
            BoundingBox(
                x1=(1.5 / shape[1]) * shape_exp[1],
                y1=(2.5 / shape[0]) * shape_exp[0],
                x2=(5.5 / shape[1]) * shape_exp[1],
                y2=(6.5 / shape[0]) * shape_exp[0],
            )
        ],
                                        shape=shape_exp)
        assert_cbaois_equal(bbsoi_aug, expected)
Exemplo n.º 5
0
    def _test_augment_line_strings__kernel_size_differs(
            self, shape, shape_exp):
        from imgaug.augmentables.lines import LineString, LineStringsOnImage
        ls = [LineString([(1.5, 5.5), (5.5, 1.5), (5.5, 5.5)])]
        lsoi = LineStringsOnImage(ls, shape=shape)
        aug = self.augmenter((iap.Deterministic(3), iap.Deterministic(2)),
                             keep_size=False)

        lsoi_aug = aug.augment_line_strings(lsoi)

        expected = LineStringsOnImage([
            LineString([((1.5 / shape[1]) * shape_exp[1],
                         (5.5 / shape[0]) * shape_exp[0]),
                        ((5.5 / shape[1]) * shape_exp[1],
                         (1.5 / shape[0]) * shape_exp[0]),
                        ((5.5 / shape[1]) * shape_exp[1],
                         (5.5 / shape[0]) * shape_exp[0])])
        ],
                                      shape=shape_exp)
        assert_cbaois_equal(lsoi_aug, expected)
Exemplo n.º 6
0
    def test_augment_images__kernel_size_differs__requires_padding(self):
        aug = iaa.AveragePooling((iap.Deterministic(3), iap.Deterministic(1)),
                                 keep_size=False)

        image = np.uint8([[50 - 2, 50 - 1, 120 - 4, 120 + 4],
                          [50 + 1, 50 + 2, 120 + 2, 120 - 1]])
        image = np.tile(image[:, :, np.newaxis], (1, 1, 3))

        expected = np.uint8([[(50 - 2 + 50 + 1 + 50 - 2) / 3,
                              (50 - 1 + 50 + 2 + 50 - 1) / 3,
                              (120 - 4 + 120 + 2 + 120 - 4) / 3,
                              (120 + 4 + 120 - 1 + 120 + 4) / 3]])
        expected = np.tile(expected[:, :, np.newaxis], (1, 1, 3))

        image_aug = aug.augment_image(image)

        diff = np.abs(image_aug.astype(np.int32) - expected)
        assert image_aug.dtype.name == "uint8"
        assert image_aug.shape == (1, 4, 3)
        assert np.all(diff <= 1)
Exemplo n.º 7
0
 def test___str___single_value_hysteresis(self):
     alpha = iap.Deterministic(0.2)
     hysteresis_thresholds = iap.Deterministic(10)
     sobel_kernel_size = iap.Deterministic(3)
     colorizer = iaa.RandomColorsBinaryImageColorizer(
         color_true=10, color_false=20)
     aug = iaa.Canny(
         alpha=alpha,
         hysteresis_thresholds=hysteresis_thresholds,
         sobel_kernel_size=sobel_kernel_size,
         colorizer=colorizer
     )
     observed = aug.__str__()
     expected = ("Canny(alpha=%s, hysteresis_thresholds=%s, "
                 "sobel_kernel_size=%s, colorizer=%s, name=UnnamedCanny, "
                 "deterministic=False)") % (
                     str(aug.alpha),
                     str(aug.hysteresis_thresholds),
                     str(aug.sobel_kernel_size),
                     colorizer)
     assert observed == expected
Exemplo n.º 8
0
    def test__draw_samples__tuple_as_hysteresis(self):
        seed = 1
        nb_images = 10

        aug = iaa.Canny(
            alpha=0.2,
            hysteresis_thresholds=([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                                   iap.DiscreteUniform(5, 100)),
            sobel_kernel_size=[3, 5, 7],
            random_state=iarandom.RNG(seed))
        aug.alpha = remove_prefetching(aug.alpha)
        aug.hysteresis_thresholds = (
            remove_prefetching(aug.hysteresis_thresholds[0]),
            remove_prefetching(aug.hysteresis_thresholds[1])
        )
        aug.sobel_kernel_size = remove_prefetching(aug.sobel_kernel_size)

        example_image = np.zeros((5, 5, 3), dtype=np.uint8)
        samples = aug._draw_samples([example_image] * nb_images,
                                    random_state=iarandom.RNG(seed))
        alpha_samples = samples[0]
        hthresh_samples = samples[1]
        sobel_samples = samples[2]

        rss = iarandom.RNG(seed).duplicate(4)
        alpha_expected = iap.Deterministic(0.2).draw_samples((nb_images,),
                                                             rss[0])
        hthresh_expected = [None, None]
        hthresh_expected[0] = iap.Choice(
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).draw_samples((nb_images,),
                                                             rss[1])
        # TODO simplify this to rss[2].randint(5, 100+1)
        #      would currenlty be a bit more ugly, because DiscrUniform
        #      samples two values for a and b first from rss[2]
        hthresh_expected[1] = iap.DiscreteUniform(5, 100).draw_samples(
            (nb_images,), rss[2])
        hthresh_expected = np.stack(hthresh_expected, axis=-1)

        sobel_expected = iap.Choice([3, 5, 7]).draw_samples((nb_images,),
                                                            rss[3])

        invalid = hthresh_expected[:, 0] > hthresh_expected[:, 1]
        hthresh_expected[invalid, :] = hthresh_expected[invalid, :][:, [1, 0]]
        assert hthresh_expected.shape == (nb_images, 2)
        assert not np.any(hthresh_expected[:, 0] > hthresh_expected[:, 1])

        assert np.allclose(alpha_samples, alpha_expected)
        assert np.allclose(hthresh_samples, hthresh_expected)
        assert np.allclose(sobel_samples, sobel_expected)
Exemplo n.º 9
0
    def _test_augmenter(cls, augmenter_name, func_expected,
                        dependent_on_seed):
        # this test verifies:
        # - called function seems to be the expected function
        # - images produced by augmenter match images produced by function
        # - a different seed (and sometimes severity) will lead to a
        #   different image
        # - augmenter can be pickled
        severity = 5
        aug_cls = getattr(iaa.imgcorruptlike, augmenter_name)
        image = np.mod(
            np.arange(32*32*3), 256
        ).reshape((32, 32, 3)).astype(np.uint8)

        with iap.no_prefetching():
            rng = iarandom.RNG(1)
            # Replay sampling of severities.
            # Even for deterministic values this is required as currently
            # there is an advance() at the end of each draw_samples().
            _ = iap.Deterministic(1).draw_samples((1,), rng)

            # As for the functions above, we can't just change the seed value
            # to get different augmentations as many functions are dependend
            # only on the severity. So we change only for some functions only
            # the seed and for the others severity+seed.
            image_aug1 = aug_cls(severity=severity, seed=1)(image=image)
            image_aug2 = aug_cls(severity=severity, seed=1)(image=image)
            if dependent_on_seed:
                image_aug3 = aug_cls(severity=severity, seed=2)(
                    image=image)
            else:
                image_aug3 = aug_cls(severity=severity-1, seed=2)(
                    image=image)
            image_aug_exp = func_expected(
                image,
                severity=severity,
                seed=rng.generate_seed_())

        assert aug_cls(severity=severity).func is func_expected
        assert np.array_equal(image_aug1, image_aug_exp)
        assert np.array_equal(image_aug2, image_aug_exp)
        assert not np.array_equal(image_aug3, image_aug2)

        # pickling test
        aug = aug_cls(severity=(1, 5))
        runtest_pickleable_uint8_img(aug, shape=(32, 32, 3))
Exemplo n.º 10
0
    def test__draw_samples__single_value_hysteresis(self):
        seed = 1
        nb_images = 1000

        aug = iaa.Canny(
            alpha=0.2,
            hysteresis_thresholds=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            sobel_kernel_size=[3, 5, 7],
            random_state=iarandom.RNG(seed))
        aug.alpha = remove_prefetching(aug.alpha)
        aug.hysteresis_thresholds = remove_prefetching(
            aug.hysteresis_thresholds)
        aug.sobel_kernel_size = remove_prefetching(aug.sobel_kernel_size)

        example_image = np.zeros((5, 5, 3), dtype=np.uint8)
        samples = aug._draw_samples([example_image] * nb_images,
                                    random_state=iarandom.RNG(seed))
        alpha_samples = samples[0]
        hthresh_samples = samples[1]
        sobel_samples = samples[2]

        rss = iarandom.RNG(seed).duplicate(4)
        alpha_expected = iap.Deterministic(0.2).draw_samples((nb_images,),
                                                             rss[0])
        hthresh_expected = iap.Choice(
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).draw_samples((nb_images, 2),
                                                             rss[1])
        sobel_expected = iap.Choice([3, 5, 7]).draw_samples((nb_images,),
                                                            rss[2])

        invalid = hthresh_expected[:, 0] > hthresh_expected[:, 1]
        assert np.any(invalid)
        hthresh_expected[invalid, :] = hthresh_expected[invalid, :][:, [1, 0]]
        assert hthresh_expected.shape == (nb_images, 2)
        assert not np.any(hthresh_expected[:, 0] > hthresh_expected[:, 1])

        assert np.allclose(alpha_samples, alpha_expected)
        assert np.allclose(hthresh_samples, hthresh_expected)
        assert np.allclose(sobel_samples, sobel_expected)
Exemplo n.º 11
0
def test_Superpixels():
    reseed()

    def _array_equals_tolerant(a, b, tolerance):
        diff = np.abs(a.astype(np.int32) - b.astype(np.int32))
        return np.all(diff <= tolerance)

    base_img = [[255, 255, 255, 0, 0, 0], [255, 235, 255, 0, 20, 0],
                [250, 250, 250, 5, 5, 5]]
    base_img = np.tile(
        np.array(base_img, dtype=np.uint8)[..., np.newaxis], (1, 1, 3))

    base_img_superpixels = [[251, 251, 251, 4, 4, 4], [251, 251, 251, 4, 4, 4],
                            [251, 251, 251, 4, 4, 4]]
    base_img_superpixels = np.tile(
        np.array(base_img_superpixels, dtype=np.uint8)[..., np.newaxis],
        (1, 1, 3))

    base_img_superpixels_left = np.copy(base_img_superpixels)
    base_img_superpixels_left[:, 3:, :] = base_img[:, 3:, :]

    base_img_superpixels_right = np.copy(base_img_superpixels)
    base_img_superpixels_right[:, :3, :] = base_img[:, :3, :]

    aug = iaa.Superpixels(p_replace=0, n_segments=2)
    observed = aug.augment_image(base_img)
    expected = base_img
    assert np.allclose(observed, expected)

    aug = iaa.Superpixels(p_replace=1.0, n_segments=2)
    observed = aug.augment_image(base_img)
    expected = base_img_superpixels
    assert _array_equals_tolerant(observed, expected, 2)

    aug = iaa.Superpixels(p_replace=1.0, n_segments=iap.Deterministic(2))
    observed = aug.augment_image(base_img)
    expected = base_img_superpixels
    assert _array_equals_tolerant(observed, expected, 2)

    aug = iaa.Superpixels(p_replace=iap.Binomial(iap.Choice([0.0, 1.0])),
                          n_segments=2)
    observed = aug.augment_image(base_img)
    assert np.allclose(observed, base_img) or _array_equals_tolerant(
        observed, base_img_superpixels, 2)

    aug = iaa.Superpixels(p_replace=0.5, n_segments=2)
    seen = {"none": False, "left": False, "right": False, "both": False}
    for _ in sm.xrange(100):
        observed = aug.augment_image(base_img)
        if _array_equals_tolerant(observed, base_img, 2):
            seen["none"] = True
        elif _array_equals_tolerant(observed, base_img_superpixels_left, 2):
            seen["left"] = True
        elif _array_equals_tolerant(observed, base_img_superpixels_right, 2):
            seen["right"] = True
        elif _array_equals_tolerant(observed, base_img_superpixels, 2):
            seen["both"] = True
        else:
            raise Exception(
                "Generated superpixels image does not match any expected image."
            )
        if all(seen.values()):
            break
    assert all(seen.values())

    # test exceptions for wrong parameter types
    got_exception = False
    try:
        _ = iaa.Superpixels(p_replace="test", n_segments=100)
    except Exception:
        got_exception = True
    assert got_exception

    got_exception = False
    try:
        _ = iaa.Superpixels(p_replace=1, n_segments="test")
    except Exception:
        got_exception = True
    assert got_exception

    # test get_parameters()
    aug = iaa.Superpixels(p_replace=0.5,
                          n_segments=2,
                          max_size=100,
                          interpolation="nearest")
    params = aug.get_parameters()
    assert isinstance(params[0], iap.Binomial)
    assert isinstance(params[0].p, iap.Deterministic)
    assert isinstance(params[1], iap.Deterministic)
    assert 0.5 - 1e-4 < params[0].p.value < 0.5 + 1e-4
    assert params[1].value == 2
    assert params[2] == 100
    assert params[3] == "nearest"
Exemplo n.º 12
0
 def test_p_replace_1_n_segments_stochastic_parameter(self):
     aug = iaa.Superpixels(p_replace=1.0, n_segments=iap.Deterministic(2))
     observed = aug.augment_image(self.base_img)
     expected = self.base_img_superpixels
     assert self._array_equals_tolerant(observed, expected, 2)
Exemplo n.º 13
0
def test_Superpixels():
    reseed()

    def _array_equals_tolerant(a, b, tolerance):
        diff = np.abs(a.astype(np.int32) - b.astype(np.int32))
        return np.all(diff <= tolerance)

    base_img = [[255, 255, 255, 0, 0, 0], [255, 235, 255, 0, 20, 0],
                [250, 250, 250, 5, 5, 5]]
    base_img = np.tile(
        np.array(base_img, dtype=np.uint8)[..., np.newaxis], (1, 1, 3))

    base_img_superpixels = [[251, 251, 251, 4, 4, 4], [251, 251, 251, 4, 4, 4],
                            [251, 251, 251, 4, 4, 4]]
    base_img_superpixels = np.tile(
        np.array(base_img_superpixels, dtype=np.uint8)[..., np.newaxis],
        (1, 1, 3))

    base_img_superpixels_left = np.copy(base_img_superpixels)
    base_img_superpixels_left[:, 3:, :] = base_img[:, 3:, :]

    base_img_superpixels_right = np.copy(base_img_superpixels)
    base_img_superpixels_right[:, :3, :] = base_img[:, :3, :]

    aug = iaa.Superpixels(p_replace=0, n_segments=2)
    observed = aug.augment_image(base_img)
    expected = base_img
    assert np.allclose(observed, expected)

    aug = iaa.Superpixels(p_replace=1.0, n_segments=2)
    observed = aug.augment_image(base_img)
    expected = base_img_superpixels
    assert _array_equals_tolerant(observed, expected, 2)

    aug = iaa.Superpixels(p_replace=1.0, n_segments=iap.Deterministic(2))
    observed = aug.augment_image(base_img)
    expected = base_img_superpixels
    assert _array_equals_tolerant(observed, expected, 2)

    aug = iaa.Superpixels(p_replace=iap.Binomial(iap.Choice([0.0, 1.0])),
                          n_segments=2)
    observed = aug.augment_image(base_img)
    assert np.allclose(observed, base_img) or _array_equals_tolerant(
        observed, base_img_superpixels, 2)

    aug = iaa.Superpixels(p_replace=0.5, n_segments=2)
    seen = {"none": False, "left": False, "right": False, "both": False}
    for _ in sm.xrange(100):
        observed = aug.augment_image(base_img)
        if _array_equals_tolerant(observed, base_img, 2):
            seen["none"] = True
        elif _array_equals_tolerant(observed, base_img_superpixels_left, 2):
            seen["left"] = True
        elif _array_equals_tolerant(observed, base_img_superpixels_right, 2):
            seen["right"] = True
        elif _array_equals_tolerant(observed, base_img_superpixels, 2):
            seen["both"] = True
        else:
            raise Exception(
                "Generated superpixels image does not match any expected image."
            )
        if all(seen.values()):
            break
    assert all(seen.values())

    # test exceptions for wrong parameter types
    got_exception = False
    try:
        _ = iaa.Superpixels(p_replace="test", n_segments=100)
    except Exception:
        got_exception = True
    assert got_exception

    got_exception = False
    try:
        _ = iaa.Superpixels(p_replace=1, n_segments="test")
    except Exception:
        got_exception = True
    assert got_exception

    # test get_parameters()
    aug = iaa.Superpixels(p_replace=0.5,
                          n_segments=2,
                          max_size=100,
                          interpolation="nearest")
    params = aug.get_parameters()
    assert isinstance(params[0], iap.Binomial)
    assert isinstance(params[0].p, iap.Deterministic)
    assert isinstance(params[1], iap.Deterministic)
    assert 0.5 - 1e-4 < params[0].p.value < 0.5 + 1e-4
    assert params[1].value == 2
    assert params[2] == 100
    assert params[3] == "nearest"

    ###################
    # test other dtypes
    ###################
    # bool
    aug = iaa.Superpixels(p_replace=1.0, n_segments=2)
    img = np.array([[False, False, True, True], [False, False, True, True]],
                   dtype=bool)
    img_aug = aug.augment_image(img)
    assert img_aug.dtype == img.dtype
    assert np.all(img_aug == img)

    aug = iaa.Superpixels(p_replace=1.0, n_segments=1)
    img = np.array([[True, True, True, True], [False, True, True, True]],
                   dtype=bool)
    img_aug = aug.augment_image(img)
    assert img_aug.dtype == img.dtype
    assert np.all(img_aug)

    for dtype in [np.uint8, np.uint16, np.uint32, np.int8, np.int16, np.int32]:
        min_value, center_value, max_value = iadt.get_value_range_of_dtype(
            dtype)

        if np.dtype(dtype).kind == "i":
            values = [
                int(center_value),
                int(0.1 * max_value),
                int(0.2 * max_value),
                int(0.5 * max_value), max_value - 100
            ]
            values = [((-1) * value, value) for value in values]
        else:
            values = [(0, int(center_value)), (10, int(0.1 * max_value)),
                      (10, int(0.2 * max_value)), (10, int(0.5 * max_value)),
                      (0, max_value), (int(center_value), max_value)]

        for v1, v2 in values:
            aug = iaa.Superpixels(p_replace=1.0, n_segments=2)
            img = np.array([[v1, v1, v2, v2], [v1, v1, v2, v2]], dtype=dtype)
            img_aug = aug.augment_image(img)
            assert img_aug.dtype == np.dtype(dtype)
            assert np.array_equal(img_aug, img)

            aug = iaa.Superpixels(p_replace=1.0, n_segments=1)
            img = np.array([[v2, v2, v2, v2], [v1, v2, v2, v2]], dtype=dtype)
            img_aug = aug.augment_image(img)
            assert img_aug.dtype == np.dtype(dtype)
            assert np.all(img_aug == int(np.round((7 / 8) * v2 +
                                                  (1 / 8) * v1)))

    for dtype in []:

        def _allclose(a, b):
            atol = 1e-4 if dtype == np.float16 else 1e-8
            return np.allclose(a, b, atol=atol, rtol=0)

        isize = np.dtype(dtype).itemsize
        for value in [0, 1.0, 10.0, 1000**(isize - 1)]:
            v1 = (-1) * value
            v2 = value

            aug = iaa.Superpixels(p_replace=1.0, n_segments=2)
            img = np.array([[v1, v1, v2, v2], [v1, v1, v2, v2]], dtype=dtype)
            img_aug = aug.augment_image(img)
            assert img_aug.dtype == np.dtype(dtype)
            assert _allclose(img_aug, img)

            aug = iaa.Superpixels(p_replace=1.0, n_segments=1)
            img = np.array([[v2, v2, v2, v2], [v1, v2, v2, v2]], dtype=dtype)
            img_aug = aug.augment_image(img)
            assert img_aug.dtype == np.dtype(dtype)
            assert _allclose(img_aug, (7 / 8) * v2 + (1 / 8) * v1)
Exemplo n.º 14
0
def test_SigmoidContrast():
    reseed()

    img = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    img = np.uint8(img)
    img3d = np.tile(img[:, :, np.newaxis], (1, 1, 3))

    # check basic functionality with per_chanenl on/off (makes no difference due to deterministic
    # parameters)
    for per_channel in [False, 0, 0.0, True, 1, 1.0]:
        for gain, cutoff in itertools.product([5, 10], [0.25, 0.75]):
            aug = iaa.SigmoidContrast(gain=iap.Deterministic(gain), cutoff=iap.Deterministic(cutoff), per_channel=per_channel)
            img_aug = aug.augment_image(img)
            img3d_aug = aug.augment_image(img3d)
            assert img_aug.dtype.type == np.uint8
            assert img3d_aug.dtype.type == np.uint8
            assert np.array_equal(img_aug, skimage.exposure.adjust_sigmoid(img, gain=gain, cutoff=cutoff))
            assert np.array_equal(img3d_aug, skimage.exposure.adjust_sigmoid(img3d, gain=gain, cutoff=cutoff))

    # check that tuple to uniform works
    # note that gain and cutoff are saved in inverted order in _ContrastFuncWrapper to match
    # the order of skimage's function
    aug = iaa.SigmoidContrast(gain=(1, 2), cutoff=(0.25, 0.75))
    assert isinstance(aug.params1d[0], iap.Uniform)
    assert isinstance(aug.params1d[0].a, iap.Deterministic)
    assert isinstance(aug.params1d[0].b, iap.Deterministic)
    assert np.allclose(aug.params1d[0].a.value, 0.25)
    assert np.allclose(aug.params1d[0].b.value, 0.75)
    assert isinstance(aug.params1d[1], iap.Uniform)
    assert isinstance(aug.params1d[1].a, iap.Deterministic)
    assert isinstance(aug.params1d[1].b, iap.Deterministic)
    assert aug.params1d[1].a.value == 1
    assert aug.params1d[1].b.value == 2

    # check that list to choice works
    # note that gain and cutoff are saved in inverted order in _ContrastFuncWrapper to match
    # the order of skimage's function
    aug = iaa.SigmoidContrast(gain=[1, 2], cutoff=[0.25, 0.75])
    assert isinstance(aug.params1d[0], iap.Choice)
    assert all([np.allclose(val, val_choice) for val, val_choice in zip([0.25, 0.75], aug.params1d[0].a)])
    assert isinstance(aug.params1d[1], iap.Choice)
    assert all([val in aug.params1d[1].a for val in [1, 2]])

    # check that per_channel at 50% prob works
    aug = iaa.SigmoidContrast(gain=(1, 10), cutoff=(0.25, 0.75), per_channel=0.5)
    seen = [False, False]
    img1000d = np.zeros((1, 1, 1000), dtype=np.uint8) + 128
    for _ in sm.xrange(100):
        img_aug = aug.augment_image(img1000d)
        assert img_aug.dtype.type == np.uint8
        l = len(set(img_aug.flatten().tolist()))
        if l == 1:
            seen[0] = True
        else:
            seen[1] = True
        if all(seen):
            break
    assert all(seen)

    # check that keypoints are not changed
    kpsoi = ia.KeypointsOnImage([ia.Keypoint(1, 1)], shape=(3, 3, 3))
    kpsoi_aug = iaa.SigmoidContrast(gain=10, cutoff=0.5).augment_keypoints([kpsoi])
    assert keypoints_equal([kpsoi], kpsoi_aug)

    # check that heatmaps are not changed
    heatmaps = ia.HeatmapsOnImage(np.zeros((3, 3, 1), dtype=np.float32) + 0.5, shape=(3, 3, 3))
    heatmaps_aug = iaa.SigmoidContrast(gain=10, cutoff=0.5).augment_heatmaps([heatmaps])[0]
    assert np.allclose(heatmaps.arr_0to1, heatmaps_aug.arr_0to1)
Exemplo n.º 15
0
def test_LinearContrast():
    reseed()

    img = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    img = np.uint8(img)
    img3d = np.tile(img[:, :, np.newaxis], (1, 1, 3))

    # check basic functionality with alpha=1 or 2 (deterministic) and per_chanenl on/off (makes
    # no difference due to deterministic alpha)
    for per_channel in [False, 0, 0.0, True, 1, 1.0]:
        for alpha in [1, 2]:
            aug = iaa.LinearContrast(alpha=iap.Deterministic(alpha),
                                     per_channel=per_channel)
            img_aug = aug.augment_image(img)
            img3d_aug = aug.augment_image(img3d)
            assert img_aug.dtype.type == np.uint8
            assert img3d_aug.dtype.type == np.uint8
            assert np.array_equal(
                img_aug, contrast_lib._adjust_linear(img, alpha=alpha))
            assert np.array_equal(
                img3d_aug, contrast_lib._adjust_linear(img3d, alpha=alpha))

    # check that tuple to uniform works
    aug = iaa.LinearContrast((1, 2))
    assert isinstance(aug.params1d[0], iap.Uniform)
    assert isinstance(aug.params1d[0].a, iap.Deterministic)
    assert isinstance(aug.params1d[0].b, iap.Deterministic)
    assert aug.params1d[0].a.value == 1
    assert aug.params1d[0].b.value == 2

    # check that list to choice works
    aug = iaa.LinearContrast([1, 2])
    assert isinstance(aug.params1d[0], iap.Choice)
    assert all([val in aug.params1d[0].a for val in [1, 2]])

    # check that per_channel at 50% prob works
    aug = iaa.LinearContrast((0.5, 2.0), per_channel=0.5)
    seen = [False, False]
    # must not use just value 128 here, otherwise nothing will change as all values would have
    # distance 0 to 128
    img1000d = np.zeros((1, 1, 1000), dtype=np.uint8) + 128 + 20
    for _ in sm.xrange(100):
        img_aug = aug.augment_image(img1000d)
        assert img_aug.dtype.type == np.uint8
        l = len(set(img_aug.flatten().tolist()))
        if l == 1:
            seen[0] = True
        else:
            seen[1] = True
        if all(seen):
            break
    assert all(seen)

    # check that keypoints are not changed
    kpsoi = ia.KeypointsOnImage([ia.Keypoint(1, 1)], shape=(3, 3, 3))
    kpsoi_aug = iaa.LinearContrast(alpha=2).augment_keypoints([kpsoi])
    assert keypoints_equal([kpsoi], kpsoi_aug)

    # check that heatmaps are not changed
    heatmaps = ia.HeatmapsOnImage(np.zeros((3, 3, 1), dtype=np.float32) + 0.5,
                                  shape=(3, 3, 3))
    heatmaps_aug = iaa.LinearContrast(alpha=2).augment_heatmaps([heatmaps])[0]
    assert np.allclose(heatmaps.arr_0to1, heatmaps_aug.arr_0to1)
Exemplo n.º 16
0
def test_GammaContrast():
    reseed()

    img = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    img = np.uint8(img)
    img3d = np.tile(img[:, :, np.newaxis], (1, 1, 3))

    # check basic functionality with gamma=1 or 2 (deterministic) and per_chanenl on/off (makes
    # no difference due to deterministic gamma)
    for per_channel in [False, 0, 0.0, True, 1, 1.0]:
        for gamma in [1, 2]:
            aug = iaa.GammaContrast(gamma=iap.Deterministic(gamma),
                                    per_channel=per_channel)
            img_aug = aug.augment_image(img)
            img3d_aug = aug.augment_image(img3d)
            assert img_aug.dtype.type == np.uint8
            assert img3d_aug.dtype.type == np.uint8
            assert np.array_equal(
                img_aug, skimage.exposure.adjust_gamma(img, gamma=gamma))
            assert np.array_equal(
                img3d_aug, skimage.exposure.adjust_gamma(img3d, gamma=gamma))

    # check that tuple to uniform works
    aug = iaa.GammaContrast((1, 2))
    assert isinstance(aug.params1d[0], iap.Uniform)
    assert isinstance(aug.params1d[0].a, iap.Deterministic)
    assert isinstance(aug.params1d[0].b, iap.Deterministic)
    assert aug.params1d[0].a.value == 1
    assert aug.params1d[0].b.value == 2

    # check that list to choice works
    aug = iaa.GammaContrast([1, 2])
    assert isinstance(aug.params1d[0], iap.Choice)
    assert all([val in aug.params1d[0].a for val in [1, 2]])

    # check that per_channel at 50% prob works
    aug = iaa.GammaContrast((0.5, 2.0), per_channel=0.5)
    seen = [False, False]
    img1000d = np.zeros((1, 1, 1000), dtype=np.uint8) + 128
    for _ in sm.xrange(100):
        img_aug = aug.augment_image(img1000d)
        assert img_aug.dtype.type == np.uint8
        l = len(set(img_aug.flatten().tolist()))
        if l == 1:
            seen[0] = True
        else:
            seen[1] = True
        if all(seen):
            break
    assert all(seen)

    # check that keypoints are not changed
    kpsoi = ia.KeypointsOnImage([ia.Keypoint(1, 1)], shape=(3, 3, 3))
    kpsoi_aug = iaa.GammaContrast(gamma=2).augment_keypoints([kpsoi])
    assert keypoints_equal([kpsoi], kpsoi_aug)

    # check that heatmaps are not changed
    heatmaps = ia.HeatmapsOnImage(np.zeros((3, 3, 1), dtype=np.float32) + 0.5,
                                  shape=(3, 3, 3))
    heatmaps_aug = iaa.GammaContrast(gamma=2).augment_heatmaps([heatmaps])[0]
    assert np.allclose(heatmaps.arr_0to1, heatmaps_aug.arr_0to1)

    ###################
    # test other dtypes
    ###################
    # uint, int
    for dtype in [
            np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16,
            np.int32, np.int64
    ]:
        min_value, center_value, max_value = meta.get_value_range_of_dtype(
            dtype)

        exps = [1, 2, 3]
        values = [0, 100, int(center_value + 0.1 * max_value)]
        tolerances = [
            0, 0, 1e-8 * max_value if dtype in [np.uint64, np.int64] else 0
        ]

        for exp in exps:
            aug = iaa.GammaContrast(exp)
            for value, tolerance in zip(values, tolerances):
                image = np.full((3, 3), value, dtype=dtype)
                expected = (((image.astype(np.float128) / max_value)**exp) *
                            max_value).astype(dtype)
                image_aug = aug.augment_image(image)
                assert image_aug.dtype == np.dtype(dtype)
                assert len(np.unique(image_aug)) == 1
                value_aug = int(image_aug[0, 0])
                value_expected = int(expected[0, 0])
                diff = abs(value_aug - value_expected)
                assert diff <= tolerance

    # float
    for dtype in [np.float16, np.float32, np.float64]:

        def _allclose(a, b):
            atol = 1e-3 if dtype == np.float16 else 1e-8
            return np.allclose(a, b, atol=atol, rtol=0)

        exps = [1, 2]
        isize = np.dtype(dtype).itemsize
        values = [0, 1.0, 50.0, 100**(isize - 1)]

        for exp in exps:
            aug = iaa.GammaContrast(exp)
            for value in values:
                image = np.full((3, 3), value, dtype=dtype)
                expected = (image.astype(np.float128)**exp).astype(dtype)
                image_aug = aug.augment_image(image)
                assert image_aug.dtype == np.dtype(dtype)
                assert _allclose(image_aug, expected)
Exemplo n.º 17
0
def test_SigmoidContrast():
    reseed()

    img = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    img = np.uint8(img)
    img3d = np.tile(img[:, :, np.newaxis], (1, 1, 3))

    # check basic functionality with per_chanenl on/off (makes no difference due to deterministic
    # parameters)
    for per_channel in [False, 0, 0.0, True, 1, 1.0]:
        for gain, cutoff in itertools.product([5, 10], [0.25, 0.75]):
            aug = iaa.SigmoidContrast(gain=iap.Deterministic(gain),
                                      cutoff=iap.Deterministic(cutoff),
                                      per_channel=per_channel)
            img_aug = aug.augment_image(img)
            img3d_aug = aug.augment_image(img3d)
            assert img_aug.dtype.type == np.uint8
            assert img3d_aug.dtype.type == np.uint8
            assert np.array_equal(
                img_aug,
                skimage.exposure.adjust_sigmoid(img, gain=gain, cutoff=cutoff))
            assert np.array_equal(
                img3d_aug,
                skimage.exposure.adjust_sigmoid(img3d,
                                                gain=gain,
                                                cutoff=cutoff))

    # check that tuple to uniform works
    # note that gain and cutoff are saved in inverted order in _ContrastFuncWrapper to match
    # the order of skimage's function
    aug = iaa.SigmoidContrast(gain=(1, 2), cutoff=(0.25, 0.75))
    assert isinstance(aug.params1d[0], iap.Uniform)
    assert isinstance(aug.params1d[0].a, iap.Deterministic)
    assert isinstance(aug.params1d[0].b, iap.Deterministic)
    assert np.allclose(aug.params1d[0].a.value, 0.25)
    assert np.allclose(aug.params1d[0].b.value, 0.75)
    assert isinstance(aug.params1d[1], iap.Uniform)
    assert isinstance(aug.params1d[1].a, iap.Deterministic)
    assert isinstance(aug.params1d[1].b, iap.Deterministic)
    assert aug.params1d[1].a.value == 1
    assert aug.params1d[1].b.value == 2

    # check that list to choice works
    # note that gain and cutoff are saved in inverted order in _ContrastFuncWrapper to match
    # the order of skimage's function
    aug = iaa.SigmoidContrast(gain=[1, 2], cutoff=[0.25, 0.75])
    assert isinstance(aug.params1d[0], iap.Choice)
    assert all([
        np.allclose(val, val_choice)
        for val, val_choice in zip([0.25, 0.75], aug.params1d[0].a)
    ])
    assert isinstance(aug.params1d[1], iap.Choice)
    assert all([val in aug.params1d[1].a for val in [1, 2]])

    # check that per_channel at 50% prob works
    aug = iaa.SigmoidContrast(gain=(1, 10),
                              cutoff=(0.25, 0.75),
                              per_channel=0.5)
    seen = [False, False]
    img1000d = np.zeros((1, 1, 1000), dtype=np.uint8) + 128
    for _ in sm.xrange(100):
        img_aug = aug.augment_image(img1000d)
        assert img_aug.dtype.type == np.uint8
        l = len(set(img_aug.flatten().tolist()))
        if l == 1:
            seen[0] = True
        else:
            seen[1] = True
        if all(seen):
            break
    assert all(seen)

    # check that keypoints are not changed
    kpsoi = ia.KeypointsOnImage([ia.Keypoint(1, 1)], shape=(3, 3, 3))
    kpsoi_aug = iaa.SigmoidContrast(gain=10,
                                    cutoff=0.5).augment_keypoints([kpsoi])
    assert keypoints_equal([kpsoi], kpsoi_aug)

    # check that heatmaps are not changed
    heatmaps = ia.HeatmapsOnImage(np.zeros((3, 3, 1), dtype=np.float32) + 0.5,
                                  shape=(3, 3, 3))
    heatmaps_aug = iaa.SigmoidContrast(gain=10,
                                       cutoff=0.5).augment_heatmaps([heatmaps
                                                                     ])[0]
    assert np.allclose(heatmaps.arr_0to1, heatmaps_aug.arr_0to1)

    ###################
    # test other dtypes
    ###################
    # uint, int
    for dtype in [
            np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16,
            np.int32, np.int64
    ]:
        min_value, center_value, max_value = meta.get_value_range_of_dtype(
            dtype)

        gains = [5, 20]
        cutoffs = [0.25, 0.75]
        values = [0, 100, int(center_value + 0.1 * max_value)]
        tmax = 1e-8 * max_value if dtype in [np.uint64, np.int64] else 0
        tolerances = [tmax, tmax, tmax]

        for gain, cutoff in itertools.product(gains, cutoffs):
            aug = iaa.SigmoidContrast(gain=gain, cutoff=cutoff)
            for value, tolerance in zip(values, tolerances):
                image = np.full((3, 3), value, dtype=dtype)
                # 1/(1 + exp(gain*(cutoff - I_ij/max)))
                expected = (1 / (1 + np.exp(
                    gain * (cutoff - image.astype(np.float128) / max_value))))
                expected = (expected * max_value).astype(dtype)
                image_aug = aug.augment_image(image)
                assert image_aug.dtype == np.dtype(dtype)
                assert len(np.unique(image_aug)) == 1
                value_aug = int(image_aug[0, 0])
                value_expected = int(expected[0, 0])
                diff = abs(value_aug - value_expected)
                assert diff <= tolerance

    # float
    for dtype in [np.float16, np.float32, np.float64]:

        def _allclose(a, b):
            atol = 1e-3 if dtype == np.float16 else 1e-8
            return np.allclose(a, b, atol=atol, rtol=0)

        gains = [5, 20]
        cutoffs = [0.25, 0.75]
        isize = np.dtype(dtype).itemsize
        values = [0, 1.0, 50.0, 100**(isize - 1)]

        for gain, cutoff in itertools.product(gains, cutoffs):
            aug = iaa.SigmoidContrast(gain=gain, cutoff=cutoff)
            for value in values:
                image = np.full((3, 3), value, dtype=dtype)
                expected = (1 /
                            (1 + np.exp(gain *
                                        (cutoff - image.astype(np.float128))))
                            ).astype(dtype)
                image_aug = aug.augment_image(image)
                assert image_aug.dtype == np.dtype(dtype)
                assert _allclose(image_aug, expected)