Exemplo n.º 1
0
 def test_hdx_rgb_roundtrip(self):
     from skimage.color.colorconv import hdx_from_rgb, rgb_from_hdx
     img_rgb = self.img_rgb
     conv = combine_stains(separate_stains(img_rgb, hdx_from_rgb),
                           rgb_from_hdx)
     with expected_warnings(['precision loss']):
         assert_equal(img_as_ubyte(conv), img_rgb)
Exemplo n.º 2
0
def test_binary_descriptors():
    descs1 = np.array([[True, True, False, True, True],
                       [False, True, False, True, True]])
    descs2 = np.array([[True, False, False, True, False],
                       [False, False, True, True, True]])
    matches = match_descriptors(descs1, descs2)
    assert_equal(matches, [[0, 0], [1, 1]])
Exemplo n.º 3
0
def test_basic():
    x = np.array([[1, 1, 3],
                  [0, 2, 0],
                  [4, 3, 1]])
    path, cost = spath.shortest_path(x)
    assert_array_equal(path, [0, 0, 1])
    assert_equal(cost, 1)
Exemplo n.º 4
0
def test_reach():
    x = np.array([[1, 1, 3],
                  [0, 2, 0],
                  [4, 3, 1]])
    path, cost = spath.shortest_path(x, reach=2)
    assert_array_equal(path, [0, 0, 2])
    assert_equal(cost, 0)
Exemplo n.º 5
0
def test_imexport_imimport():
    shape = (2, 2)
    image = np.zeros(shape)
    with expected_warnings(['precision loss']):
        pil_image = ndarray_to_pil(image)
    out = pil_to_ndarray(pil_image)
    assert_equal(out.shape, shape)
Exemplo n.º 6
0
def test_binary_descriptors_rotation_crosscheck_true():
    """Verify matched keypoints and their corresponding masks results between
    image and its rotated version with the expected keypoint pairs with
    cross_check enabled."""
    img = data.astronaut()
    img = rgb2gray(img)
    tform = tf.SimilarityTransform(scale=1, rotation=0.15, translation=(0, 0))
    rotated_img = tf.warp(img, tform, clip=False)

    extractor = BRIEF(descriptor_size=512)

    keypoints1 = corner_peaks(corner_harris(img), min_distance=5,
                              threshold_abs=0, threshold_rel=0.1)
    extractor.extract(img, keypoints1)
    descriptors1 = extractor.descriptors

    keypoints2 = corner_peaks(corner_harris(rotated_img), min_distance=5,
                              threshold_abs=0, threshold_rel=0.1)
    extractor.extract(rotated_img, keypoints2)
    descriptors2 = extractor.descriptors

    matches = match_descriptors(descriptors1, descriptors2, cross_check=True)

    exp_matches1 = np.array([ 0,  2,  3,  4,  5,  6,  9, 11, 12, 13, 14, 17,
                             18, 19, 21, 22, 23, 26, 27, 28, 29, 31, 32, 33,
                             34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46])
    exp_matches2 = np.array([ 0,  2,  3,  1,  4,  6,  5,  7, 13, 10,  9, 11,
                             15,  8, 14, 12, 16, 18, 19, 21, 20, 24, 25, 26,
                             28, 27, 22, 23, 29, 30, 31, 32, 35, 33, 34, 36])
    assert_equal(matches[:, 0], exp_matches1)
    assert_equal(matches[:, 1], exp_matches2)
Exemplo n.º 7
0
def test_pad_input():
    """Test `match_template` when `pad_input=True`.

    This test places two full templates (one with values lower than the image
    mean, the other higher) and two half templates, which are on the edges of
    the image. The two full templates should score the top (positive and
    negative) matches and the centers of the half templates should score 2nd.
    """
    # Float prefactors ensure that image range is between 0 and 1
    template = 0.5 * diamond(2)
    image = 0.5 * np.ones((9, 19))
    mid = slice(2, 7)
    image[mid, :3] -= template[:, -3:]  # half min template centered at 0
    image[mid, 4:9] += template         # full max template centered at 6
    image[mid, -9:-4] -= template       # full min template centered at 12
    image[mid, -3:] += template[:, :3]  # half max template centered at 18

    result = match_template(image, template, pad_input=True,
                            constant_values=image.mean())

    # get the max and min results.
    sorted_result = np.argsort(result.flat)
    i, j = np.unravel_index(sorted_result[:2], result.shape)
    assert_equal(j, (12, 0))
    i, j = np.unravel_index(sorted_result[-2:], result.shape)
    assert_equal(j, (18, 6))
Exemplo n.º 8
0
def test_hough_line_peaks_zero_input():
    # Test to make sure empty input doesn't cause a failure
    img = np.zeros((100, 100), dtype='uint8')
    theta = np.linspace(0, np.pi, 100)
    hspace, angles, dists = transform.hough_line(img, theta)
    h, a, d = transform.hough_line_peaks(hspace, angles, dists)
    assert_equal(a, np.array([]))
Exemplo n.º 9
0
def test_denoise_bilateral_nan():
    img = np.full((50, 50), np.NaN)
    # This is in fact an optional warning for our test suite.
    # Python 3.5 will not trigger a warning.
    with expected_warnings([r'invalid|\A\Z']):
        out = restoration.denoise_bilateral(img, multichannel=False)
    assert_equal(img, out)
Exemplo n.º 10
0
def test_rect_tool():
    img = data.camera()
    viewer = ImageViewer(img)

    tool = RectangleTool(viewer, maxdist=10)
    tool.extents = (100, 150, 100, 150)

    assert_equal(tool.corners,
                 ((100, 150, 150, 100), (100, 100, 150, 150)))
    assert_equal(tool.extents, (100, 150, 100, 150))
    assert_equal(tool.edge_centers,
                 ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150)))
    assert_equal(tool.geometry, (100, 150, 100, 150))

    # grab a corner and move it
    do_event(viewer, 'mouse_press', xdata=100, ydata=100)
    do_event(viewer, 'move', xdata=120, ydata=120)
    do_event(viewer, 'mouse_release')
    # assert_equal(tool.geometry, [120, 150, 120, 150])

    # create a new line
    do_event(viewer, 'mouse_press', xdata=10, ydata=10)
    do_event(viewer, 'move', xdata=100, ydata=100)
    do_event(viewer, 'mouse_release')
    assert_equal(tool.geometry, [10, 100,  10, 100])
def test_ssim_patch_range():
    N = 51
    X = (np.random.rand(N, N) * 255).astype(np.uint8)
    Y = (np.random.rand(N, N) * 255).astype(np.uint8)

    assert(ssim(X, Y, win_size=N) < 0.1)
    assert_equal(ssim(X, X, win_size=N), 1)
Exemplo n.º 12
0
def test_ransac_is_model_valid():
    def is_model_valid(model, data):
        return False
    model, inliers = ransac(np.empty((10, 2)), LineModelND, 2, np.inf,
                            is_model_valid=is_model_valid, random_state=1)
    assert_equal(model, None)
    assert_equal(inliers, None)
Exemplo n.º 13
0
def test_threshold_minimum_synthetic():
    img = np.arange(25*25, dtype=np.uint8).reshape((25, 25))
    img[0:9, :] = 50
    img[14:25, :] = 250

    threshold = threshold_minimum(img)
    assert_equal(threshold, 95)
Exemplo n.º 14
0
 def test_median_default_value(self):
     a = np.zeros((3, 3), dtype=np.uint8)
     a[1] = 1
     full_selem = np.ones((3, 3), dtype=np.uint8)
     assert_equal(rank.median(a), rank.median(a, full_selem))
     assert rank.median(a)[1, 1] == 0
     assert rank.median(a, disk(1))[1, 1] == 1
Exemplo n.º 15
0
def test_subdivide_polygon():
    new_square1 = square
    new_square2 = square[:-1]
    new_square3 = square[:-1]
    # test iterative subdvision
    for _ in range(10):
        square1, square2, square3 = new_square1, new_square2, new_square3
        # test different B-Spline degrees
        for degree in range(1, 7):
            mask_len = len(_SUBDIVISION_MASKS[degree][0])
            # test circular
            new_square1 = subdivide_polygon(square1, degree)
            assert_array_equal(new_square1[-1], new_square1[0])
            assert_equal(new_square1.shape[0],
                         2 * square1.shape[0] - 1)
            # test non-circular
            new_square2 = subdivide_polygon(square2, degree)
            assert_equal(new_square2.shape[0],
                         2 * (square2.shape[0] - mask_len + 1))
            # test non-circular, preserve_ends
            new_square3 = subdivide_polygon(square3, degree, True)
            assert_equal(new_square3[0], square3[0])
            assert_equal(new_square3[-1], square3[-1])

            assert_equal(new_square3.shape[0],
                         2 * (square3.shape[0] - mask_len + 2))

    # not supported B-Spline degree
    with testing.raises(ValueError):
        subdivide_polygon(square, 0)
    with testing.raises(ValueError):
        subdivide_polygon(square, 8)
Exemplo n.º 16
0
def test_regular_grid_3d_8():
    ar = np.zeros((3, 20, 40))
    g = regular_grid(ar.shape, 8)
    assert_equal(g, [slice(1.0, None, 3.0), slice(5.0, None, 10.0),
                     slice(5.0, None, 10.0)])
    ar[g] = 1
    assert_equal(ar.sum(), 8)
Exemplo n.º 17
0
def test_ransac_is_data_valid():
    def is_data_valid(data):
        return data.shape[0] > 2
    model, inliers = ransac(np.empty((10, 2)), LineModelND, 2, np.inf,
                            is_data_valid=is_data_valid, random_state=1)
    assert_equal(model, None)
    assert_equal(inliers, None)
Exemplo n.º 18
0
    def test_custom_load_func(self):

        def load_fn(x):
            return x

        ic = ImageCollection(os.pathsep.join(self.pattern), load_func=load_fn)
        assert_equal(ic[0], self.pattern[0])
def test_masked_registration_random_masks_non_equal_sizes():
    """masked_register_translation should be able to register
    translations between images that are not the same size even
    with random masks."""
    # See random number generator for reproducible results
    np.random.seed(23)

    reference_image = camera()
    shift = (-7, 12)
    shifted = np.real(np.fft.ifft2(fourier_shift(
        np.fft.fft2(reference_image), shift)))

    # Crop the shifted image
    shifted = shifted[64:-64, 64:-64]

    # Random masks with 75% of pixels being valid
    ref_mask = np.random.choice(
        [True, False], reference_image.shape, p=[3 / 4, 1 / 4])
    shifted_mask = np.random.choice(
        [True, False], shifted.shape, p=[3 / 4, 1 / 4])

    measured_shift = masked_register_translation(
        reference_image,
        shifted,
        np.ones_like(ref_mask),
        np.ones_like(shifted_mask))
    assert_equal(measured_shift, -np.array(shift))
Exemplo n.º 20
0
 def test_ndarray_exclude_border(self):
     nd_image = np.zeros((5, 5, 5))
     nd_image[[1, 0, 0], [0, 1, 0], [0, 0, 1]] = 1
     nd_image[3, 0, 0] = 1
     nd_image[2, 2, 2] = 1
     expected = np.zeros_like(nd_image, dtype=np.bool)
     expected[2, 2, 2] = True
     expectedNoBorder = nd_image > 0
     result = peak.peak_local_max(nd_image, min_distance=2,
         exclude_border=2, indices=False)
     assert_equal(result, expected)
     # Check that bools work as expected
     assert_equal(
         peak.peak_local_max(nd_image, min_distance=2,
             exclude_border=2, indices=False),
         peak.peak_local_max(nd_image, min_distance=2,
             exclude_border=True, indices=False)
         )
     assert_equal(
         peak.peak_local_max(nd_image, min_distance=2,
             exclude_border=0, indices=False),
         peak.peak_local_max(nd_image, min_distance=2,
             exclude_border=False, indices=False)
         )
     # Check both versions with  no border
     assert_equal(
         peak.peak_local_max(nd_image, min_distance=2,
             exclude_border=0, indices=False),
         expectedNoBorder,
         )
     assert_equal(
         peak.peak_local_max(nd_image,
             exclude_border=False, indices=False),
         expectedNoBorder,
         )
Exemplo n.º 21
0
 def test_rectangle_selem(self):
     """Test rectangle structuring elements"""
     for i in range(0, 5):
         for j in range(0, 5):
             actual_mask = selem.rectangle(i, j)
             expected_mask = np.ones((i, j), dtype='uint8')
             assert_equal(expected_mask, actual_mask)
def test_masked_registration_padfield_data():
    """ Masked translation registration should behave like in the original 
    publication """
    # Test translated from MATLABimplementation `MaskedFFTRegistrationTest` 
    # file. You can find the source code here: 
    # http://www.dirkpadfield.com/Home/MaskedFFTRegistrationCode.zip

    shifts = [(75, 75), (-130, 130), (130, 130)]
    for xi, yi in shifts:
        
        fixed_image = imread(
            IMAGES_DIR / 'OriginalX{:d}Y{:d}.png'.format(xi, yi))
        moving_image = imread(
            IMAGES_DIR / 'TransformedX{:d}Y{:d}.png'.format(xi, yi))

        # Valid pixels are 1
        fixed_mask = (fixed_image != 0)
        moving_mask = (moving_image != 0)

        # Note that shifts in x and y and shifts in cols and rows
        shift_y, shift_x = masked_register_translation(fixed_image, 
                                                       moving_image, 
                                                       fixed_mask, 
                                                       moving_mask, 
                                                       overlap_ratio = 1/10)
        # Note: by looking at the test code from Padfield's 
        # MaskedFFTRegistrationCode repository, the 
        # shifts were not xi and yi, but xi and -yi
        assert_equal((shift_x, shift_y), (-xi, yi))
Exemplo n.º 23
0
def test_descriptor_orb():
    detector_extractor = ORB(fast_n=12, fast_threshold=0.20)

    exp_descriptors = np.array([[0, 1, 1, 1, 0, 1, 0, 1, 0, 1],
                                [1, 1, 1, 0, 0, 1, 0, 0, 1, 1],
                                [1, 0, 1, 1, 0, 0, 1, 1, 0, 0],
                                [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                                [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
                                [1, 1, 0, 1, 1, 1, 0, 0, 1, 1],
                                [1, 1, 0, 1, 0, 0, 1, 0, 1, 1],
                                [0, 0, 1, 0, 1, 0, 0, 1, 1, 0],
                                [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
                                [0, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                                [1, 1, 0, 1, 0, 1, 0, 0, 1, 1],
                                [1, 1, 1, 0, 0, 0, 1, 1, 1, 0],
                                [1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
                                [1, 1, 1, 0, 1, 1, 1, 1, 0, 0],
                                [1, 1, 0, 0, 1, 0, 0, 1, 0, 1],
                                [1, 1, 0, 0, 0, 0, 1, 0, 0, 1],
                                [0, 0, 0, 0, 1, 1, 1, 0, 1, 0],
                                [0, 0, 0, 0, 1, 1, 1, 0, 0, 1],
                                [0, 0, 0, 0, 0, 1, 1, 0, 1, 1],
                                [0, 0, 0, 0, 1, 0, 1, 0, 1, 1]], dtype=bool)
    detector_extractor.detect(img)
    detector_extractor.extract(img, detector_extractor.keypoints,
                               detector_extractor.scales,
                               detector_extractor.orientations)
    assert_equal(exp_descriptors,
                 detector_extractor.descriptors[100:120, 10:20])

    detector_extractor.detect_and_extract(img)
    assert_equal(exp_descriptors,
                 detector_extractor.descriptors[100:120, 10:20])
Exemplo n.º 24
0
def test_peak_float_out_of_range_dtype():
    im = np.array([10, 100], dtype=np.float16)
    nbins = 10
    frequencies, bin_centers = exposure.histogram(im, nbins=nbins, source_range='dtype')
    assert_almost_equal(np.min(bin_centers), -0.9, 3)
    assert_almost_equal(np.max(bin_centers), 0.9, 3)
    assert_equal(len(bin_centers), 10)
Exemplo n.º 25
0
def test_string_sort():
    filenames = ['f9.10.png', 'f9.9.png', 'f10.10.png', 'f10.9.png',
                 'e9.png', 'e10.png', 'em.png']
    sorted_filenames = ['e9.png', 'e10.png', 'em.png', 'f9.9.png',
                        'f9.10.png', 'f10.9.png', 'f10.10.png']
    sorted_filenames = sorted(filenames, key=alphanumeric_key)
    assert_equal(sorted_filenames, sorted_filenames)
Exemplo n.º 26
0
def test_hough_line_angles():
    img = np.zeros((10, 10))
    img[0, 0] = 1

    out, angles, d = transform.hough_line(img, np.linspace(0, 360, 10))

    assert_equal(len(angles), 10)
Exemplo n.º 27
0
    def test_structuring_element8(self):
        # check the output for a custom structuring element

        r = np.array([[0, 0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 0, 0],
                      [0, 0, 255, 0, 0, 0],
                      [0, 0, 255, 255, 255, 0],
                      [0, 0, 0, 255, 255, 0],
                      [0, 0, 0, 0, 0, 0]])

        # 8-bit
        image = np.zeros((6, 6), dtype=np.uint8)
        image[2, 2] = 255
        elem = np.asarray([[1, 1, 0], [1, 1, 1], [0, 0, 1]], dtype=np.uint8)
        out = np.empty_like(image)
        mask = np.ones(image.shape, dtype=np.uint8)

        rank.maximum(image=image, selem=elem, out=out, mask=mask,
                     shift_x=1, shift_y=1)
        assert_equal(r, out)

        # 16-bit
        image = np.zeros((6, 6), dtype=np.uint16)
        image[2, 2] = 255
        out = np.empty_like(image)

        rank.maximum(image=image, selem=elem, out=out, mask=mask,
                     shift_x=1, shift_y=1)
        assert_equal(r, out)
Exemplo n.º 28
0
 def test_concatenate(self):
     for img in self.imgs:
         if img[0].shape != img[-1].shape:
             with testing.raises(ValueError):
                 img.concatenate()
             continue
         array = img.concatenate()
         assert_equal(array.shape, (len(img),) + img[0].shape)
Exemplo n.º 29
0
    def test_custom_load(self):
        load_pattern = [(1, 'one'), (2, 'two')]

        def load_fn(x):
            return x

        ic = ImageCollection(load_pattern, load_func=load_fn)
        assert_equal(ic[1], (2, 'two'))
Exemplo n.º 30
0
def test_use_priority():
    manage_plugins.use_plugin(priority_plugin)
    plug, func = manage_plugins.plugin_store['imread'][0]
    assert_equal(plug, priority_plugin)

    manage_plugins.use_plugin('matplotlib')
    plug, func = manage_plugins.plugin_store['imread'][0]
    assert_equal(plug, 'matplotlib')
Exemplo n.º 31
0
def test_view_as_blocks_2D_array():
    A = np.arange(4 * 4).reshape(4, 4)
    B = view_as_blocks(A, (2, 2))
    assert_equal(B[0, 1], np.array([[2, 3], [6, 7]]))
    assert_equal(B[1, 0, 1, 1], 13)
Exemplo n.º 32
0
def test_view_as_blocks_3D_array():
    A = np.arange(4 * 4 * 6).reshape(4, 4, 6)
    B = view_as_blocks(A, (1, 2, 2))
    assert_equal(B.shape, (4, 2, 3, 1, 2, 2))
    assert_equal(B[2:, 0, 2],
                 np.array([[[[52, 53], [58, 59]]], [[[76, 77], [82, 83]]]]))
Exemplo n.º 33
0
 def test_gray_morphology(self):
     expected = dict(
         np.load(os.path.join(data_dir, 'gray_morph_output.npz')))
     calculated = self._build_expected_output()
     assert_equal(expected, calculated)
Exemplo n.º 34
0
def test_signed_scaling_float32():
    x = np.array([-128, 127], dtype=np.int8)
    y = img_as_float32(x)
    assert_equal(y.max(), 1)
Exemplo n.º 35
0
def test_denoise_bilateral_zeros():
    img = np.zeros((10, 10))
    assert_equal(img, restoration.denoise_bilateral(img, multichannel=False))
Exemplo n.º 36
0
def test_multi_crop():
    arr = np.arange(45).reshape(9, 5)
    out = crop(arr, ((1, 2), (2, 1)))
    assert_array_equal(out[0], [7, 8])
    assert_array_equal(out[-1], [32, 33])
    assert_equal(out.shape, (6, 2))
Exemplo n.º 37
0
def test_color_2d():
    rnd = np.random.RandomState(0)
    img = np.zeros((20, 21, 3))
    img[:10, :10, 0] = 1
    img[10:, :10, 1] = 1
    img[10:, 10:, 2] = 1
    img += 0.01 * rnd.normal(size=img.shape)
    img[img > 1] = 1
    img[img < 0] = 0
    seg = slic(img,
               n_segments=4,
               sigma=0,
               enforce_connectivity=False,
               start_label=0)

    # we expect 4 segments
    assert_equal(len(np.unique(seg)), 4)
    assert_equal(seg.shape, img.shape[:-1])
    assert_equal(seg[:10, :10], 0)
    assert_equal(seg[10:, :10], 2)
    assert_equal(seg[:10, 10:], 1)
    assert_equal(seg[10:, 10:], 3)
Exemplo n.º 38
0
def test_horse():
    """ Test that "horse" image can be loaded. """
    horse = data.horse()
    assert_equal(horse.ndim, 2)
    assert_equal(horse.dtype, np.dtype('bool'))
Exemplo n.º 39
0
def test_astronaut():
    """ Test that "astronaut" image can be loaded. """
    astronaut = data.astronaut()
    assert_equal(astronaut.shape, (512, 512, 3))
Exemplo n.º 40
0
def test_float32_passthrough():
    x = np.array([-1, 1], dtype=np.float32)
    y = img_as_float(x)
    assert_equal(y.dtype, x.dtype)
Exemplo n.º 41
0
def test_denoise_bilateral_3d_multichannel():
    img = np.ones((50, 50, 50))
    with expected_warnings(["grayscale"]):
        result = restoration.denoise_bilateral(img, multichannel=True)

    assert_equal(result, img)
Exemplo n.º 42
0
def _verify_range(msg, x, vmin, vmax, dtype):
    assert_equal(x[0], vmin)
    assert_equal(x[-1], vmax)
    assert x.dtype == dtype
Exemplo n.º 43
0
def test_view_as_blocks_1D_array():
    A = np.arange(10)
    B = view_as_blocks(A, (5, ))
    assert_equal(B, np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]))
Exemplo n.º 44
0
def test_slic_zero():
    # Same as test_color_2d but with slic_zero=True
    rnd = np.random.RandomState(0)
    img = np.zeros((20, 21, 3))
    img[:10, :10, 0] = 1
    img[10:, :10, 1] = 1
    img[10:, 10:, 2] = 1
    img += 0.01 * rnd.normal(size=img.shape)
    img[img > 1] = 1
    img[img < 0] = 0
    seg = slic(img, n_segments=4, sigma=0, slic_zero=True, start_label=0)

    # we expect 4 segments
    assert_equal(len(np.unique(seg)), 4)
    assert_equal(seg.shape, img.shape[:-1])
    assert_equal(seg[:10, :10], 0)
    assert_equal(seg[10:, :10], 2)
    assert_equal(seg[:10, 10:], 1)
    assert_equal(seg[10:, 10:], 3)
Exemplo n.º 45
0
def test_logo():
    """ Test that "logo" image can be loaded. """
    logo = data.logo()
    assert_equal(logo.ndim, 3)
    assert_equal(logo.shape[2], 4)
Exemplo n.º 46
0
def test_color_2d_mask():
    rnd = np.random.RandomState(0)
    msk = np.zeros((20, 21))
    msk[2:-2, 2:-2] = 1
    img = np.zeros((20, 21, 3))
    img[:10, :10, 0] = 1
    img[10:, :10, 1] = 1
    img[10:, 10:, 2] = 1
    img += 0.01 * rnd.normal(size=img.shape)
    np.clip(img, 0, 1, out=img)
    seg = slic(img,
               n_segments=4,
               sigma=0,
               enforce_connectivity=False,
               mask=msk)

    # we expect 4 segments + masked area
    assert_equal(len(np.unique(seg)), 5)
    assert_equal(seg.shape, img.shape[:-1])
    # segments
    assert_equal(seg[2:10, 2:10], 1)
    assert_equal(seg[10:-2, 2:10], 4)
    assert_equal(seg[2:10, 10:-2], 2)
    assert_equal(seg[10:-2, 10:-2], 3)
    # non masked area
    assert_equal(seg[:2, :], 0)
    assert_equal(seg[-2:, :], 0)
    assert_equal(seg[:, :2], 0)
    assert_equal(seg[:, -2:], 0)
Exemplo n.º 47
0
def test_camera():
    """ Test that "camera" image can be loaded. """
    cameraman = data.camera()
    assert_equal(cameraman.ndim, 2)
Exemplo n.º 48
0
def test_in_place_holes():
    image = test_holes_image.copy()
    observed = remove_small_holes(image, area_threshold=3, in_place=True)
    assert_equal(observed is image, True,
                 "remove_small_holes in_place argument failed.")
Exemplo n.º 49
0
    def test_sum(self):
        # check the number of valid pixels in the neighborhood

        image8 = np.array([[0, 0, 0, 0, 0],
                           [0, 1, 1, 1, 0],
                           [0, 1, 1, 1, 0],
                           [0, 1, 1, 1, 0],
                           [0, 0, 0, 0, 0]], dtype=np.uint8)
        image16 = 400 * np.array([[0, 0, 0, 0, 0],
                                  [0, 1, 1, 1, 0],
                                  [0, 1, 1, 1, 0],
                                  [0, 1, 1, 1, 0],
                                  [0, 0, 0, 0, 0]], dtype=np.uint16)
        elem = np.ones((3, 3), dtype=np.uint8)
        out8 = np.empty_like(image8)
        out16 = np.empty_like(image16)
        mask = np.ones(image8.shape, dtype=np.uint8)

        r = np.array([[1, 2, 3, 2, 1],
                      [2, 4, 6, 4, 2],
                      [3, 6, 9, 6, 3],
                      [2, 4, 6, 4, 2],
                      [1, 2, 3, 2, 1]], dtype=np.uint8)
        rank.sum(image=image8, selem=elem, out=out8, mask=mask)
        assert_equal(r, out8)
        rank.sum_percentile(
            image=image8, selem=elem, out=out8, mask=mask, p0=.0, p1=1.)
        assert_equal(r, out8)
        rank.sum_bilateral(
            image=image8, selem=elem, out=out8, mask=mask, s0=255, s1=255)
        assert_equal(r, out8)

        r = 400 * np.array([[1, 2, 3, 2, 1],
                            [2, 4, 6, 4, 2],
                            [3, 6, 9, 6, 3],
                            [2, 4, 6, 4, 2],
                            [1, 2, 3, 2, 1]], dtype=np.uint16)
        rank.sum(image=image16, selem=elem, out=out16, mask=mask)
        assert_equal(r, out16)
        rank.sum_percentile(
            image=image16, selem=elem, out=out16, mask=mask, p0=.0, p1=1.)
        assert_equal(r, out16)
        rank.sum_bilateral(
            image=image16, selem=elem, out=out16, mask=mask, s0=1000, s1=1000)
        assert_equal(r, out16)
Exemplo n.º 50
0
def test_slice():
    padded = np.pad(SAMPLE, ((2, 4), (5, 2)), mode='constant')
    nrow, ncol = SAMPLE.shape
    result = regionprops(padded)[0].slice
    expected = (slice(2, 2 + nrow), slice(5, 5 + ncol))
    assert_equal(result, expected)
Exemplo n.º 51
0
        def check_all():
            selem = morphology.disk(1)
            refs = np.load(os.path.join(skimage.data_dir, "rank_filter_tests.npz"))

            assert_equal(refs["autolevel"],
                         rank.autolevel(self.image, selem))
            assert_equal(refs["autolevel_percentile"],
                         rank.autolevel_percentile(self.image, selem))
            assert_equal(refs["bottomhat"],
                         rank.bottomhat(self.image, selem))
            assert_equal(refs["equalize"],
                         rank.equalize(self.image, selem))
            assert_equal(refs["gradient"],
                         rank.gradient(self.image, selem))
            assert_equal(refs["gradient_percentile"],
                         rank.gradient_percentile(self.image, selem))
            assert_equal(refs["maximum"],
                         rank.maximum(self.image, selem))
            assert_equal(refs["mean"],
                         rank.mean(self.image, selem))
            assert_equal(refs["geometric_mean"],
                         rank.geometric_mean(self.image, selem)),
            assert_equal(refs["mean_percentile"],
                         rank.mean_percentile(self.image, selem))
            assert_equal(refs["mean_bilateral"],
                         rank.mean_bilateral(self.image, selem))
            assert_equal(refs["subtract_mean"],
                         rank.subtract_mean(self.image, selem))
            assert_equal(refs["subtract_mean_percentile"],
                         rank.subtract_mean_percentile(self.image, selem))
            assert_equal(refs["median"],
                         rank.median(self.image, selem))
            assert_equal(refs["minimum"],
                         rank.minimum(self.image, selem))
            assert_equal(refs["modal"],
                         rank.modal(self.image, selem))
            assert_equal(refs["enhance_contrast"],
                         rank.enhance_contrast(self.image, selem))
            assert_equal(refs["enhance_contrast_percentile"],
                         rank.enhance_contrast_percentile(self.image, selem))
            assert_equal(refs["pop"],
                         rank.pop(self.image, selem))
            assert_equal(refs["pop_percentile"],
                         rank.pop_percentile(self.image, selem))
            assert_equal(refs["pop_bilateral"],
                         rank.pop_bilateral(self.image, selem))
            assert_equal(refs["sum"],
                         rank.sum(self.image, selem))
            assert_equal(refs["sum_bilateral"],
                         rank.sum_bilateral(self.image, selem))
            assert_equal(refs["sum_percentile"],
                         rank.sum_percentile(self.image, selem))
            assert_equal(refs["threshold"],
                         rank.threshold(self.image, selem))
            assert_equal(refs["threshold_percentile"],
                         rank.threshold_percentile(self.image, selem))
            assert_equal(refs["tophat"],
                         rank.tophat(self.image, selem))
            assert_equal(refs["noise_filter"],
                         rank.noise_filter(self.image, selem))
            assert_equal(refs["entropy"],
                         rank.entropy(self.image, selem))
            assert_equal(refs["otsu"],
                         rank.otsu(self.image, selem))
            assert_equal(refs["percentile"],
                         rank.percentile(self.image, selem))
            assert_equal(refs["windowed_histogram"],
                         rank.windowed_histogram(self.image, selem))
Exemplo n.º 52
0
    def test_random_sizes(self):
        # make sure the size is not a problem

        elem = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], dtype=np.uint8)
        for m, n in np.random.randint(1, 101, size=(10, 2)):
            mask = np.ones((m, n), dtype=np.uint8)

            image8 = np.ones((m, n), dtype=np.uint8)
            out8 = np.empty_like(image8)
            rank.mean(image=image8, selem=elem, mask=mask, out=out8,
                      shift_x=0, shift_y=0)
            assert_equal(image8.shape, out8.shape)
            rank.mean(image=image8, selem=elem, mask=mask, out=out8,
                      shift_x=+1, shift_y=+1)
            assert_equal(image8.shape, out8.shape)

            rank.geometric_mean(image=image8, selem=elem, mask=mask, out=out8,
                                shift_x=0, shift_y=0)
            assert_equal(image8.shape, out8.shape)
            rank.geometric_mean(image=image8, selem=elem, mask=mask, out=out8,
                                shift_x=+1, shift_y=+1)
            assert_equal(image8.shape, out8.shape)

            image16 = np.ones((m, n), dtype=np.uint16)
            out16 = np.empty_like(image8, dtype=np.uint16)
            rank.mean(image=image16, selem=elem, mask=mask, out=out16,
                      shift_x=0, shift_y=0)
            assert_equal(image16.shape, out16.shape)
            rank.mean(image=image16, selem=elem, mask=mask, out=out16,
                      shift_x=+1, shift_y=+1)
            assert_equal(image16.shape, out16.shape)

            rank.geometric_mean(image=image16, selem=elem, mask=mask, out=out16,
                                shift_x=0, shift_y=0)
            assert_equal(image16.shape, out16.shape)
            rank.geometric_mean(image=image16, selem=elem, mask=mask, out=out16,
                                shift_x=+1, shift_y=+1)
            assert_equal(image16.shape, out16.shape)

            rank.mean_percentile(image=image16, mask=mask, out=out16,
                                 selem=elem, shift_x=0, shift_y=0, p0=.1, p1=.9)
            assert_equal(image16.shape, out16.shape)
            rank.mean_percentile(image=image16, mask=mask, out=out16,
                                 selem=elem, shift_x=+1, shift_y=+1, p0=.1, p1=.9)
            assert_equal(image16.shape, out16.shape)
Exemplo n.º 53
0
def test_line_model_nd_residuals():
    model = LineModelND()
    model.params = (np.array([0, 0, 0]), np.array([0, 0, 1]))
    assert_equal(abs(model.residuals(np.array([[0, 0, 0]]))), 0)
    assert_equal(abs(model.residuals(np.array([[0, 0, 1]]))), 0)
    assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)
Exemplo n.º 54
0
def test_in_place():
    observed = remove_small_objects(test_image, min_size=6, in_place=True)
    assert_equal(observed is test_image, True,
                 "remove_small_objects in_place argument failed.")
Exemplo n.º 55
0
def test_cycle_spinning_multichannel():
    sigma = 0.1
    rstate = np.random.RandomState(1234)

    for multichannel in True, False:
        if multichannel:
            img = astro
            # can either omit or be 0 along the channels axis
            valid_shifts = [1, (0, 1), (1, 0), (1, 1), (1, 1, 0)]
            # can either omit or be 1 on channels axis.
            valid_steps = [1, 2, (1, 2), (1, 2, 1)]
            # too few or too many shifts or non-zero shift on channels
            invalid_shifts = [(1, 1, 2), (1, ), (1, 1, 0, 1)]
            # too few or too many shifts or any shifts <= 0
            invalid_steps = [(1, ), (1, 1, 1, 1), (0, 1), (-1, -1)]
        else:
            img = astro_gray
            valid_shifts = [1, (0, 1), (1, 0), (1, 1)]
            valid_steps = [1, 2, (1, 2)]
            invalid_shifts = [(1, 1, 2), (1, )]
            invalid_steps = [(1, ), (1, 1, 1), (0, 1), (-1, -1)]

        noisy = img.copy() + 0.1 * rstate.randn(*(img.shape))

        denoise_func = restoration.denoise_wavelet
        func_kw = dict(sigma=sigma, multichannel=multichannel)

        # max_shifts=0 is equivalent to just calling denoise_func
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            dn_cc = restoration.cycle_spin(noisy,
                                           denoise_func,
                                           max_shifts=0,
                                           func_kw=func_kw,
                                           multichannel=multichannel)
            dn = denoise_func(noisy, **func_kw)
        assert_equal(dn, dn_cc)

        # denoising with cycle spinning will give better PSNR than without
        for max_shifts in valid_shifts:
            with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
                dn_cc = restoration.cycle_spin(noisy,
                                               denoise_func,
                                               max_shifts=max_shifts,
                                               func_kw=func_kw,
                                               multichannel=multichannel)
            assert_(compare_psnr(img, dn_cc) > compare_psnr(img, dn))

        for shift_steps in valid_steps:
            with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
                dn_cc = restoration.cycle_spin(noisy,
                                               denoise_func,
                                               max_shifts=2,
                                               shift_steps=shift_steps,
                                               func_kw=func_kw,
                                               multichannel=multichannel)
            assert_(compare_psnr(img, dn_cc) > compare_psnr(img, dn))

        for max_shifts in invalid_shifts:
            with testing.raises(ValueError):
                dn_cc = restoration.cycle_spin(noisy,
                                               denoise_func,
                                               max_shifts=max_shifts,
                                               func_kw=func_kw,
                                               multichannel=multichannel)
        for shift_steps in invalid_steps:
            with testing.raises(ValueError):
                dn_cc = restoration.cycle_spin(noisy,
                                               denoise_func,
                                               max_shifts=2,
                                               shift_steps=shift_steps,
                                               func_kw=func_kw,
                                               multichannel=multichannel)
Exemplo n.º 56
0
def test_ransac_dynamic_max_trials():
    # Numbers hand-calculated and confirmed on page 119 (Table 4.3) in
    #   Hartley, R.~I. and Zisserman, A., 2004,
    #   Multiple View Geometry in Computer Vision, Second Edition,
    #   Cambridge University Press, ISBN: 0521540518

    # e = 0%, min_samples = X
    assert_equal(_dynamic_max_trials(100, 100, 2, 0.99), 1)

    # e = 5%, min_samples = 2
    assert_equal(_dynamic_max_trials(95, 100, 2, 0.99), 2)
    # e = 10%, min_samples = 2
    assert_equal(_dynamic_max_trials(90, 100, 2, 0.99), 3)
    # e = 30%, min_samples = 2
    assert_equal(_dynamic_max_trials(70, 100, 2, 0.99), 7)
    # e = 50%, min_samples = 2
    assert_equal(_dynamic_max_trials(50, 100, 2, 0.99), 17)

    # e = 5%, min_samples = 8
    assert_equal(_dynamic_max_trials(95, 100, 8, 0.99), 5)
    # e = 10%, min_samples = 8
    assert_equal(_dynamic_max_trials(90, 100, 8, 0.99), 9)
    # e = 30%, min_samples = 8
    assert_equal(_dynamic_max_trials(70, 100, 8, 0.99), 78)
    # e = 50%, min_samples = 8
    assert_equal(_dynamic_max_trials(50, 100, 8, 0.99), 1177)

    # e = 0%, min_samples = 5
    assert_equal(_dynamic_max_trials(1, 100, 5, 0), 0)
    assert_equal(_dynamic_max_trials(1, 100, 5, 1), np.inf)
Exemplo n.º 57
0
def test_pair_tuple_crop():
    arr = np.arange(45).reshape(9, 5)
    out = crop(arr, ((1, 2), ))
    assert_array_equal(out[0], [6, 7])
    assert_array_equal(out[-1], [31, 32])
    assert_equal(out.shape, (6, 2))
Exemplo n.º 58
0
def test_int_tuple_crop():
    arr = np.arange(45).reshape(9, 5)
    out = crop(arr, (1, ))
    assert_array_equal(out[0], [6, 7, 8])
    assert_array_equal(out[-1], [36, 37, 38])
    assert_equal(out.shape, (7, 3))
Exemplo n.º 59
0
def test_denoise_bilateral_constant():
    img = np.ones((10, 10)) * 5
    assert_equal(img, restoration.denoise_bilateral(img, multichannel=False))
Exemplo n.º 60
0
def test_polygon_perimeter_outside_image():
    rr, cc = polygon_perimeter([-1, -1, 3, 3], [-1, 4, 4, -1], shape=(3, 4))
    assert_equal(len(rr), 0)
    assert_equal(len(cc), 0)