Fixed database typo and removed unnecessary class identifier.

This commit is contained in:
Batuhan Berk Başoğlu 2020-10-14 10:10:37 -04:00
parent 00ad49a143
commit 45fb349a7d
5098 changed files with 952558 additions and 85 deletions

View file

@ -0,0 +1,9 @@
from ..._shared.testing import setup_test, teardown_test
def setup():
setup_test()
def teardown():
teardown_test()

View file

@ -0,0 +1,96 @@
import numpy as np
from skimage._shared.testing import assert_array_almost_equal
from skimage.filters import threshold_local, gaussian
from skimage.util.apply_parallel import apply_parallel
import pytest
da = pytest.importorskip('dask.array')
def test_apply_parallel():
# data
a = np.arange(144).reshape(12, 12).astype(float)
# apply the filter
expected1 = threshold_local(a, 3)
result1 = apply_parallel(threshold_local, a, chunks=(6, 6), depth=5,
extra_arguments=(3,),
extra_keywords={'mode': 'reflect'})
assert_array_almost_equal(result1, expected1)
def wrapped_gauss(arr):
return gaussian(arr, 1, mode='reflect')
expected2 = gaussian(a, 1, mode='reflect')
result2 = apply_parallel(wrapped_gauss, a, chunks=(6, 6), depth=5)
assert_array_almost_equal(result2, expected2)
expected3 = gaussian(a, 1, mode='reflect')
result3 = apply_parallel(
wrapped_gauss, da.from_array(a, chunks=(6, 6)), depth=5, compute=True
)
assert isinstance(result3, np.ndarray)
assert_array_almost_equal(result3, expected3)
def test_apply_parallel_lazy():
# data
a = np.arange(144).reshape(12, 12).astype(float)
d = da.from_array(a, chunks=(6, 6))
# apply the filter
expected1 = threshold_local(a, 3)
result1 = apply_parallel(threshold_local, a, chunks=(6, 6), depth=5,
extra_arguments=(3,),
extra_keywords={'mode': 'reflect'},
compute=False)
# apply the filter on a Dask Array
result2 = apply_parallel(threshold_local, d, depth=5,
extra_arguments=(3,),
extra_keywords={'mode': 'reflect'})
assert isinstance(result1, da.Array)
assert_array_almost_equal(result1.compute(), expected1)
assert isinstance(result2, da.Array)
assert_array_almost_equal(result2.compute(), expected1)
def test_no_chunks():
a = np.ones(1 * 4 * 8 * 9).reshape(1, 4, 8, 9)
def add_42(arr):
return arr + 42
expected = add_42(a)
result = apply_parallel(add_42, a)
assert_array_almost_equal(result, expected)
def test_apply_parallel_wrap():
def wrapped(arr):
return gaussian(arr, 1, mode='wrap')
a = np.arange(144).reshape(12, 12).astype(float)
expected = gaussian(a, 1, mode='wrap')
result = apply_parallel(wrapped, a, chunks=(6, 6), depth=5, mode='wrap')
assert_array_almost_equal(result, expected)
def test_apply_parallel_nearest():
def wrapped(arr):
return gaussian(arr, 1, mode='nearest')
a = np.arange(144).reshape(12, 12).astype(float)
expected = gaussian(a, 1, mode='nearest')
result = apply_parallel(wrapped, a, chunks=(6, 6), depth={0: 5, 1: 5},
mode='nearest')
assert_array_almost_equal(result, expected)

View file

@ -0,0 +1,48 @@
import numpy as np
from skimage.util import crop
from skimage._shared.testing import (assert_array_equal, assert_equal)
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))
def test_pair_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))
def test_int_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))
def test_copy_crop():
arr = np.arange(45).reshape(9, 5)
out0 = crop(arr, 1, copy=True)
assert out0.flags.c_contiguous
out0[0, 0] = 100
assert not np.any(arr == 100)
assert not np.may_share_memory(arr, out0)
out1 = crop(arr, 1)
out1[0, 0] = 100
assert arr[1, 1] == 100
assert np.may_share_memory(arr, out1)
def test_zero_crop():
arr = np.arange(45).reshape(9, 5)
out = crop(arr, 0)
assert out.shape == (9, 5)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,64 @@
import numpy as np
from skimage._shared.testing import assert_array_equal
from skimage._shared import testing
from skimage.util.compare import compare_images
def test_compate_images_ValueError_shape():
img1 = np.zeros((10, 10), dtype=np.uint8)
img2 = np.zeros((10, 1), dtype=np.uint8)
with testing.raises(ValueError):
compare_images(img1, img2)
def test_compare_images_diff():
img1 = np.zeros((10, 10), dtype=np.uint8)
img1[3:8, 3:8] = 255
img2 = np.zeros_like(img1)
img2[3:8, 0:8] = 255
expected_result = np.zeros_like(img1, dtype=np.float64)
expected_result[3:8, 0:3] = 1
result = compare_images(img1, img2, method='diff')
assert_array_equal(result, expected_result)
def test_compare_images_blend():
img1 = np.zeros((10, 10), dtype=np.uint8)
img1[3:8, 3:8] = 255
img2 = np.zeros_like(img1)
img2[3:8, 0:8] = 255
expected_result = np.zeros_like(img1, dtype=np.float64)
expected_result[3:8, 3:8] = 1
expected_result[3:8, 0:3] = 0.5
result = compare_images(img1, img2, method='blend')
assert_array_equal(result, expected_result)
def test_compare_images_checkerboard_default():
img1 = np.zeros((2**4, 2**4), dtype=np.uint8)
img2 = np.full(img1.shape, fill_value=255, dtype=np.uint8)
res = compare_images(img1, img2, method='checkerboard')
exp_row1 = np.array([0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1.])
exp_row2 = np.array([1., 1., 0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1., 0., 0.])
for i in (0, 1, 4, 5, 8, 9, 12, 13):
assert_array_equal(res[i, :], exp_row1)
for i in (2, 3, 6, 7, 10, 11, 14, 15):
assert_array_equal(res[i, :], exp_row2)
def test_compare_images_checkerboard_tuple():
img1 = np.zeros((2**4, 2**4), dtype=np.uint8)
img2 = np.full(img1.shape, fill_value=255, dtype=np.uint8)
res = compare_images(img1, img2, method='checkerboard', n_tiles=(4, 8))
exp_row1 = np.array(
[0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1.]
)
exp_row2 = np.array(
[1., 1., 0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1., 0., 0.]
)
for i in (0, 1, 2, 3, 8, 9, 10, 11):
assert_array_equal(res[i, :], exp_row1)
for i in (4, 5, 6, 7, 12, 13, 14, 15):
assert_array_equal(res[i, :], exp_row2)

View file

@ -0,0 +1,193 @@
import warnings
import numpy as np
import itertools
from skimage import (img_as_float, img_as_float32, img_as_float64,
img_as_int, img_as_uint, img_as_ubyte)
from skimage.util.dtype import _convert
from skimage._shared._warnings import expected_warnings
from skimage._shared import testing
from skimage._shared.testing import assert_equal, parametrize
dtype_range = {np.uint8: (0, 255),
np.uint16: (0, 65535),
np.int8: (-128, 127),
np.int16: (-32768, 32767),
np.float32: (-1.0, 1.0),
np.float64: (-1.0, 1.0)}
img_funcs = (img_as_int, img_as_float64, img_as_float32,
img_as_uint, img_as_ubyte)
dtypes_for_img_funcs = (np.int16, np.float64, np.float32, np.uint16, np.ubyte)
img_funcs_and_types = zip(img_funcs, dtypes_for_img_funcs)
def _verify_range(msg, x, vmin, vmax, dtype):
assert_equal(x[0], vmin)
assert_equal(x[-1], vmax)
assert x.dtype == dtype
@parametrize("dtype, f_and_dt",
itertools.product(dtype_range, img_funcs_and_types))
def test_range(dtype, f_and_dt):
imin, imax = dtype_range[dtype]
x = np.linspace(imin, imax, 10).astype(dtype)
f, dt = f_and_dt
y = f(x)
omin, omax = dtype_range[dt]
if imin == 0 or omin == 0:
omin = 0
imin = 0
_verify_range("From %s to %s" % (np.dtype(dtype), np.dtype(dt)),
y, omin, omax, np.dtype(dt))
# Add non-standard data types that are allowed by the `_convert` function.
dtype_range_extra = dtype_range.copy()
dtype_range_extra.update({np.int32: (-2147483648, 2147483647),
np.uint32: (0, 4294967295)})
dtype_pairs = [(np.uint8, np.uint32),
(np.int8, np.uint32),
(np.int8, np.int32),
(np.int32, np.int8),
(np.float64, np.float32),
(np.int32, np.float32)]
@parametrize("dtype_in, dt", dtype_pairs)
def test_range_extra_dtypes(dtype_in, dt):
"""Test code paths that are not skipped by `test_range`"""
imin, imax = dtype_range_extra[dtype_in]
x = np.linspace(imin, imax, 10).astype(dtype_in)
y = _convert(x, dt)
omin, omax = dtype_range_extra[dt]
_verify_range("From %s to %s" % (np.dtype(dtype_in), np.dtype(dt)),
y, omin, omax, np.dtype(dt))
def test_downcast():
x = np.arange(10).astype(np.uint64)
with expected_warnings(['Downcasting']):
y = img_as_int(x)
assert np.allclose(y, x.astype(np.int16))
assert y.dtype == np.int16, y.dtype
def test_float_out_of_range():
too_high = np.array([2], dtype=np.float32)
with testing.raises(ValueError):
img_as_int(too_high)
too_low = np.array([-2], dtype=np.float32)
with testing.raises(ValueError):
img_as_int(too_low)
def test_float_float_all_ranges():
arr_in = np.array([[-10., 10., 1e20]], dtype=np.float32)
np.testing.assert_array_equal(img_as_float(arr_in), arr_in)
def test_copy():
x = np.array([1], dtype=np.float64)
y = img_as_float(x)
z = img_as_float(x, force_copy=True)
assert y is x
assert z is not x
def test_bool():
img_ = np.zeros((10, 10), np.bool_)
img8 = np.zeros((10, 10), np.bool8)
img_[1, 1] = True
img8[1, 1] = True
for (func, dt) in [(img_as_int, np.int16),
(img_as_float, np.float64),
(img_as_uint, np.uint16),
(img_as_ubyte, np.ubyte)]:
converted_ = func(img_)
assert np.sum(converted_) == dtype_range[dt][1]
converted8 = func(img8)
assert np.sum(converted8) == dtype_range[dt][1]
def test_clobber():
# The `img_as_*` functions should never modify input arrays.
for func_input_type in img_funcs:
for func_output_type in img_funcs:
img = np.random.rand(5, 5)
img_in = func_input_type(img)
img_in_before = img_in.copy()
func_output_type(img_in)
assert_equal(img_in, img_in_before)
def test_signed_scaling_float32():
x = np.array([-128, 127], dtype=np.int8)
y = img_as_float32(x)
assert_equal(y.max(), 1)
def test_float32_passthrough():
x = np.array([-1, 1], dtype=np.float32)
y = img_as_float(x)
assert_equal(y.dtype, x.dtype)
float_dtype_list = [float, np.float, np.double, np.single, np.float32,
np.float64, 'float32', 'float64']
def test_float_conversion_dtype():
"""Test any convertion from a float dtype to an other."""
x = np.array([-1, 1])
# Test all combinations of dtypes convertions
dtype_combin = np.array(np.meshgrid(float_dtype_list,
float_dtype_list)).T.reshape(-1, 2)
for dtype_in, dtype_out in dtype_combin:
x = x.astype(dtype_in)
y = _convert(x, dtype_out)
assert y.dtype == np.dtype(dtype_out)
def test_float_conversion_dtype_warns():
"""Test that convert issues a warning when called"""
from skimage.util.dtype import convert
x = np.array([-1, 1])
# Test all combinations of dtypes convertions
dtype_combin = np.array(np.meshgrid(float_dtype_list,
float_dtype_list)).T.reshape(-1, 2)
for dtype_in, dtype_out in dtype_combin:
x = x.astype(dtype_in)
with expected_warnings(["The use of this function is discouraged"]):
y = convert(x, dtype_out)
assert y.dtype == np.dtype(dtype_out)
def test_subclass_conversion():
"""Check subclass conversion behavior"""
x = np.array([-1, 1])
for dtype in float_dtype_list:
x = x.astype(dtype)
y = _convert(x, np.floating)
assert y.dtype == x.dtype

View file

@ -0,0 +1,77 @@
import numpy as np
from skimage import dtype_limits
from skimage.util.dtype import dtype_range
from skimage.util import invert
from skimage._shared.testing import assert_array_equal
def test_invert_bool():
dtype = 'bool'
image = np.zeros((3, 3), dtype=dtype)
upper_dtype_limit = dtype_limits(image, clip_negative=False)[1]
image[1, :] = upper_dtype_limit
expected = np.zeros((3, 3), dtype=dtype) + upper_dtype_limit
expected[1, :] = 0
result = invert(image)
assert_array_equal(expected, result)
def test_invert_uint8():
dtype = 'uint8'
image = np.zeros((3, 3), dtype=dtype)
upper_dtype_limit = dtype_limits(image, clip_negative=False)[1]
image[1, :] = upper_dtype_limit
expected = np.zeros((3, 3), dtype=dtype) + upper_dtype_limit
expected[1, :] = 0
result = invert(image)
assert_array_equal(expected, result)
def test_invert_int8():
dtype = 'int8'
image = np.zeros((3, 3), dtype=dtype)
lower_dtype_limit, upper_dtype_limit = \
dtype_limits(image, clip_negative=False)
image[1, :] = lower_dtype_limit
image[2, :] = upper_dtype_limit
expected = np.zeros((3, 3), dtype=dtype)
expected[2, :] = lower_dtype_limit
expected[1, :] = upper_dtype_limit
expected[0, :] = -1
result = invert(image)
assert_array_equal(expected, result)
def test_invert_float64_signed():
dtype = 'float64'
image = np.zeros((3, 3), dtype=dtype)
lower_dtype_limit, upper_dtype_limit = \
dtype_limits(image, clip_negative=False)
image[1, :] = lower_dtype_limit
image[2, :] = upper_dtype_limit
expected = np.zeros((3, 3), dtype=dtype)
expected[2, :] = lower_dtype_limit
expected[1, :] = upper_dtype_limit
result = invert(image, signed_float=True)
assert_array_equal(expected, result)
def test_invert_float64_unsigned():
dtype = 'float64'
image = np.zeros((3, 3), dtype=dtype)
lower_dtype_limit, upper_dtype_limit = \
dtype_limits(image, clip_negative=True)
image[2, :] = upper_dtype_limit
expected = np.zeros((3, 3), dtype=dtype)
expected[0, :] = upper_dtype_limit
expected[1, :] = upper_dtype_limit
result = invert(image)
assert_array_equal(expected, result)
def test_invert_roundtrip():
for t, limits in dtype_range.items():
image = np.array(limits, dtype=t)
expected = invert(invert(image))
assert_array_equal(image, expected)

View file

@ -0,0 +1,55 @@
import numpy as np
from skimage.util._map_array import map_array, ArrayMap
from skimage._shared import testing
from skimage._shared.testing import assert_array_equal
import pytest
def test_map_array_incorrect_output_shape():
labels = np.random.randint(0, 5, size=(24, 25))
out = np.empty((24, 24))
in_values = np.unique(labels)
out_values = np.random.random(in_values.shape).astype(out.dtype)
with testing.raises(ValueError):
map_array(labels, in_values, out_values, out=out)
def test_map_array_non_contiguous_output_array():
labels = np.random.randint(0, 5, size=(24, 25))
out = np.empty((24 * 3, 25 * 2))[::3, ::2]
in_values = np.unique(labels)
out_values = np.random.random(in_values.shape).astype(out.dtype)
with testing.raises(ValueError):
map_array(labels, in_values, out_values, out=out)
def test_arraymap_long_str():
labels = np.random.randint(0, 40, size=(24, 25))
in_values = np.unique(labels)
out_values = np.random.random(in_values.shape)
m = ArrayMap(in_values, out_values)
assert len(str(m).split('\n')) == m._max_str_lines + 2
def test_arraymap_update():
in_values = np.unique(np.random.randint(0, 200, size=5))
out_values = np.random.random(len(in_values))
m = ArrayMap(in_values, out_values)
image = np.random.randint(1, len(m), size=(512, 512))
assert np.all(m[image] < 1) # missing values map to 0.
m[1:] += 1
assert np.all(m[image] >= 1)
def test_arraymap_bool_index():
in_values = np.unique(np.random.randint(0, 200, size=5))
out_values = np.random.random(len(in_values))
m = ArrayMap(in_values, out_values)
image = np.random.randint(1, len(in_values), size=(512, 512))
assert np.all(m[image] < 1) # missing values map to 0.
positive = np.ones(len(m), dtype=bool)
positive[0] = False
m[positive] += 1
assert np.all(m[image] >= 1)

View file

@ -0,0 +1,145 @@
from skimage._shared import testing
from skimage._shared.testing import assert_equal, assert_array_equal
from skimage._shared._warnings import expected_warnings
import numpy as np
from skimage.util import montage
def test_montage_simple_gray():
n_images, n_rows, n_cols = 3, 2, 3
arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float)
arr_in = arr_in.reshape(n_images, n_rows, n_cols)
arr_out = montage(arr_in)
arr_ref = np.array(
[[ 0. , 1. , 2. , 6. , 7. , 8. ],
[ 3. , 4. , 5. , 9. , 10. , 11. ],
[ 12. , 13. , 14. , 8.5, 8.5, 8.5],
[ 15. , 16. , 17. , 8.5, 8.5, 8.5]]
)
assert_array_equal(arr_out, arr_ref)
def test_montage_simple_rgb():
n_images, n_rows, n_cols, n_channels = 2, 2, 2, 2
arr_in = np.arange(n_images * n_rows * n_cols * n_channels, dtype=np.float)
arr_in = arr_in.reshape(n_images, n_rows, n_cols, n_channels)
arr_out = montage(arr_in, multichannel=True)
arr_ref = np.array(
[[[ 0, 1],
[ 2, 3],
[ 8, 9],
[10, 11]],
[[ 4, 5],
[ 6, 7],
[12, 13],
[14, 15]],
[[ 7, 8],
[ 7, 8],
[ 7, 8],
[ 7, 8]],
[[ 7, 8],
[ 7, 8],
[ 7, 8],
[ 7, 8]]]
)
assert_array_equal(arr_out, arr_ref)
def test_montage_fill_gray():
n_images, n_rows, n_cols = 3, 2, 3
arr_in = np.arange(n_images*n_rows*n_cols, dtype=np.float)
arr_in = arr_in.reshape(n_images, n_rows, n_cols)
arr_out = montage(arr_in, fill=0)
arr_ref = np.array(
[[ 0. , 1. , 2. , 6. , 7. , 8. ],
[ 3. , 4. , 5. , 9. , 10. , 11. ],
[ 12. , 13. , 14. , 0. , 0. , 0. ],
[ 15. , 16. , 17. , 0. , 0. , 0. ]]
)
assert_array_equal(arr_out, arr_ref)
def test_montage_grid_default_gray():
n_images, n_rows, n_cols = 15, 11, 7
arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float)
arr_in = arr_in.reshape(n_images, n_rows, n_cols)
n_tiles = int(np.ceil(np.sqrt(n_images)))
arr_out = montage(arr_in)
assert_equal(arr_out.shape, (n_tiles * n_rows, n_tiles * n_cols))
def test_montage_grid_custom_gray():
n_images, n_rows, n_cols = 6, 2, 2
arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float32)
arr_in = arr_in.reshape(n_images, n_rows, n_cols)
arr_out = montage(arr_in, grid_shape=(3, 2))
arr_ref = np.array(
[[ 0., 1., 4., 5.],
[ 2., 3., 6., 7.],
[ 8., 9., 12., 13.],
[ 10., 11., 14., 15.],
[ 16., 17., 20., 21.],
[ 18., 19., 22., 23.]]
)
assert_array_equal(arr_out, arr_ref)
def test_montage_rescale_intensity_gray():
n_images, n_rows, n_cols = 4, 3, 3
arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float32)
arr_in = arr_in.reshape(n_images, n_rows, n_cols)
arr_out = montage(arr_in, rescale_intensity=True)
arr_ref = np.array(
[[ 0. , 0.125, 0.25 , 0. , 0.125, 0.25 ],
[ 0.375, 0.5 , 0.625, 0.375, 0.5 , 0.625],
[ 0.75 , 0.875, 1. , 0.75 , 0.875, 1. ],
[ 0. , 0.125, 0.25 , 0. , 0.125, 0.25 ],
[ 0.375, 0.5 , 0.625, 0.375, 0.5 , 0.625],
[ 0.75 , 0.875, 1. , 0.75 , 0.875, 1. ]]
)
assert_equal(arr_out.min(), 0.0)
assert_equal(arr_out.max(), 1.0)
assert_array_equal(arr_out, arr_ref)
def test_montage_simple_padding_gray():
n_images, n_rows, n_cols = 2, 2, 2
arr_in = np.arange(n_images * n_rows * n_cols)
arr_in = arr_in.reshape(n_images, n_rows, n_cols)
arr_out = montage(arr_in, padding_width=1)
arr_ref = np.array(
[[3, 3, 3, 3, 3, 3, 3],
[3, 0, 1, 3, 4, 5, 3],
[3, 2, 3, 3, 6, 7, 3],
[3, 3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3, 3]]
)
assert_array_equal(arr_out, arr_ref)
def test_error_ndim():
arr_error = np.random.randn(1, 2)
with testing.raises(ValueError):
montage(arr_error)
arr_error = np.random.randn(1, 2, 3, 4)
with testing.raises(ValueError):
montage(arr_error)
arr_error = np.random.randn(1, 2, 3)
with testing.raises(ValueError):
montage(arr_error, multichannel=True)
arr_error = np.random.randn(1, 2, 3, 4, 5)
with testing.raises(ValueError):
montage(arr_error, multichannel=True)

View file

@ -0,0 +1,214 @@
from skimage._shared import testing
from skimage._shared.testing import assert_array_equal, assert_allclose
import numpy as np
from skimage.data import camera
from skimage.util import random_noise, img_as_float
def test_set_seed():
seed = 42
cam = camera()
test = random_noise(cam, seed=seed)
assert_array_equal(test, random_noise(cam, seed=seed))
def test_salt():
seed = 42
cam = img_as_float(camera())
cam_noisy = random_noise(cam, seed=seed, mode='salt', amount=0.15)
saltmask = cam != cam_noisy
# Ensure all changes are to 1.0
assert_allclose(cam_noisy[saltmask], np.ones(saltmask.sum()))
# Ensure approximately correct amount of noise was added
proportion = float(saltmask.sum()) / (cam.shape[0] * cam.shape[1])
assert 0.11 < proportion <= 0.15
def test_salt_p1():
image = np.random.rand(2, 3)
noisy = random_noise(image, mode='salt', amount=1)
assert_array_equal(noisy, [[1, 1, 1], [1, 1, 1]])
def test_singleton_dim():
"""Ensure images where size of a given dimension is 1 work correctly."""
image = np.random.rand(1, 20)
noisy = random_noise(image, mode='salt', amount=0.1, seed=42)
assert np.sum(noisy == 1) == 2
def test_pepper():
seed = 42
cam = img_as_float(camera())
data_signed = cam * 2. - 1. # Same image, on range [-1, 1]
cam_noisy = random_noise(cam, seed=seed, mode='pepper', amount=0.15)
peppermask = cam != cam_noisy
# Ensure all changes are to 1.0
assert_allclose(cam_noisy[peppermask], np.zeros(peppermask.sum()))
# Ensure approximately correct amount of noise was added
proportion = float(peppermask.sum()) / (cam.shape[0] * cam.shape[1])
assert 0.11 < proportion <= 0.15
# Check to make sure pepper gets added properly to signed images
orig_zeros = (data_signed == -1).sum()
cam_noisy_signed = random_noise(data_signed, seed=seed, mode='pepper',
amount=.15)
proportion = (float((cam_noisy_signed == -1).sum() - orig_zeros) /
(cam.shape[0] * cam.shape[1]))
assert 0.11 < proportion <= 0.15
def test_salt_and_pepper():
seed = 42
cam = img_as_float(camera())
cam_noisy = random_noise(cam, seed=seed, mode='s&p', amount=0.15,
salt_vs_pepper=0.25)
saltmask = np.logical_and(cam != cam_noisy, cam_noisy == 1.)
peppermask = np.logical_and(cam != cam_noisy, cam_noisy == 0.)
# Ensure all changes are to 0. or 1.
assert_allclose(cam_noisy[saltmask], np.ones(saltmask.sum()))
assert_allclose(cam_noisy[peppermask], np.zeros(peppermask.sum()))
# Ensure approximately correct amount of noise was added
proportion = float(
saltmask.sum() + peppermask.sum()) / (cam.shape[0] * cam.shape[1])
assert 0.11 < proportion <= 0.18
# Verify the relative amount of salt vs. pepper is close to expected
assert 0.18 < saltmask.sum() / float(peppermask.sum()) < 0.33
def test_gaussian():
seed = 42
data = np.zeros((128, 128)) + 0.5
data_gaussian = random_noise(data, seed=seed, var=0.01)
assert 0.008 < data_gaussian.var() < 0.012
data_gaussian = random_noise(data, seed=seed, mean=0.3, var=0.015)
assert 0.28 < data_gaussian.mean() - 0.5 < 0.32
assert 0.012 < data_gaussian.var() < 0.018
def test_localvar():
seed = 42
data = np.zeros((128, 128)) + 0.5
local_vars = np.zeros((128, 128)) + 0.001
local_vars[:64, 64:] = 0.1
local_vars[64:, :64] = 0.25
local_vars[64:, 64:] = 0.45
data_gaussian = random_noise(data, mode='localvar', seed=seed,
local_vars=local_vars, clip=False)
assert 0. < data_gaussian[:64, :64].var() < 0.002
assert 0.095 < data_gaussian[:64, 64:].var() < 0.105
assert 0.245 < data_gaussian[64:, :64].var() < 0.255
assert 0.445 < data_gaussian[64:, 64:].var() < 0.455
# Ensure local variance bounds checking works properly
bad_local_vars = np.zeros_like(data)
with testing.raises(ValueError):
random_noise(data, mode='localvar', seed=seed,
local_vars=bad_local_vars)
bad_local_vars += 0.1
bad_local_vars[0, 0] = -1
with testing.raises(ValueError):
random_noise(data, mode='localvar', seed=seed,
local_vars=bad_local_vars)
def test_speckle():
seed = 42
data = np.zeros((128, 128)) + 0.1
np.random.seed(seed=seed)
noise = np.random.normal(0.1, 0.02 ** 0.5, (128, 128))
expected = np.clip(data + data * noise, 0, 1)
data_speckle = random_noise(data, mode='speckle', seed=seed, mean=0.1,
var=0.02)
assert_allclose(expected, data_speckle)
def test_poisson():
seed = 42
data = camera() # 512x512 grayscale uint8
cam_noisy = random_noise(data, mode='poisson', seed=seed)
cam_noisy2 = random_noise(data, mode='poisson', seed=seed, clip=False)
np.random.seed(seed=seed)
expected = np.random.poisson(img_as_float(data) * 256) / 256.
assert_allclose(cam_noisy, np.clip(expected, 0., 1.))
assert_allclose(cam_noisy2, expected)
def test_clip_poisson():
seed = 42
data = camera() # 512x512 grayscale uint8
data_signed = img_as_float(data) * 2. - 1. # Same image, on range [-1, 1]
# Signed and unsigned, clipped
cam_poisson = random_noise(data, mode='poisson', seed=seed, clip=True)
cam_poisson2 = random_noise(data_signed, mode='poisson', seed=seed,
clip=True)
assert (cam_poisson.max() == 1.) and (cam_poisson.min() == 0.)
assert (cam_poisson2.max() == 1.) and (cam_poisson2.min() == -1.)
# Signed and unsigned, unclipped
cam_poisson = random_noise(data, mode='poisson', seed=seed, clip=False)
cam_poisson2 = random_noise(data_signed, mode='poisson', seed=seed,
clip=False)
assert (cam_poisson.max() > 1.15) and (cam_poisson.min() == 0.)
assert (cam_poisson2.max() > 1.3) and (cam_poisson2.min() == -1.)
def test_clip_gaussian():
seed = 42
data = camera() # 512x512 grayscale uint8
data_signed = img_as_float(data) * 2. - 1. # Same image, on range [-1, 1]
# Signed and unsigned, clipped
cam_gauss = random_noise(data, mode='gaussian', seed=seed, clip=True)
cam_gauss2 = random_noise(data_signed, mode='gaussian', seed=seed,
clip=True)
assert (cam_gauss.max() == 1.) and (cam_gauss.min() == 0.)
assert (cam_gauss2.max() == 1.) and (cam_gauss2.min() == -1.)
# Signed and unsigned, unclipped
cam_gauss = random_noise(data, mode='gaussian', seed=seed, clip=False)
cam_gauss2 = random_noise(data_signed, mode='gaussian', seed=seed,
clip=False)
assert (cam_gauss.max() > 1.22) and (cam_gauss.min() < -0.36)
assert (cam_gauss2.max() > 1.219) and (cam_gauss2.min() < -1.337)
def test_clip_speckle():
seed = 42
data = camera() # 512x512 grayscale uint8
data_signed = img_as_float(data) * 2. - 1. # Same image, on range [-1, 1]
# Signed and unsigned, clipped
cam_speckle = random_noise(data, mode='speckle', seed=seed, clip=True)
cam_speckle2 = random_noise(data_signed, mode='speckle', seed=seed,
clip=True)
assert (cam_speckle.max() == 1.) and (cam_speckle.min() == 0.)
assert (cam_speckle2.max() == 1.) and (cam_speckle2.min() == -1.)
# Signed and unsigned, unclipped
cam_speckle = random_noise(data, mode='speckle', seed=seed, clip=False)
cam_speckle2 = random_noise(data_signed, mode='speckle', seed=seed,
clip=False)
assert (cam_speckle.max() > 1.219) and (cam_speckle.min() == 0.)
assert (cam_speckle2.max() > 1.219) and (cam_speckle2.min() < -1.306)
def test_bad_mode():
data = np.zeros((64, 64))
with testing.raises(KeyError):
random_noise(data, 'perlin')

View file

@ -0,0 +1,36 @@
import numpy as np
from skimage.util import regular_grid
from skimage._shared.testing import assert_equal
def test_regular_grid_full():
ar = np.zeros((2, 2))
g = regular_grid(ar, 25)
assert_equal(g, [slice(None, None, None), slice(None, None, None)])
ar[g] = 1
assert_equal(ar.size, ar.sum())
def test_regular_grid_2d_8():
ar = np.zeros((20, 40))
g = regular_grid(ar.shape, 8)
assert_equal(g, [slice(5.0, None, 10.0), slice(5.0, None, 10.0)])
ar[g] = 1
assert_equal(ar.sum(), 8)
def test_regular_grid_2d_32():
ar = np.zeros((20, 40))
g = regular_grid(ar.shape, 32)
assert_equal(g, [slice(2.0, None, 5.0), slice(2.0, None, 5.0)])
ar[g] = 1
assert_equal(ar.sum(), 32)
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)

View file

@ -0,0 +1,192 @@
import numpy as np
from skimage._shared import testing
from skimage._shared.testing import assert_equal, assert_warns
from skimage.util.shape import view_as_blocks, view_as_windows
def test_view_as_blocks_block_not_a_tuple():
A = np.arange(10)
with testing.raises(TypeError):
view_as_blocks(A, [5])
def test_view_as_blocks_negative_shape():
A = np.arange(10)
with testing.raises(ValueError):
view_as_blocks(A, (-2,))
def test_view_as_blocks_block_too_large():
A = np.arange(10)
with testing.raises(ValueError):
view_as_blocks(A, (11,))
def test_view_as_blocks_wrong_block_dimension():
A = np.arange(10)
with testing.raises(ValueError):
view_as_blocks(A, (2, 2))
def test_view_as_blocks_1D_array_wrong_block_shape():
A = np.arange(10)
with testing.raises(ValueError):
view_as_blocks(A, (3,))
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]]))
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)
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]]]]))
def test_view_as_windows_input_not_array():
A = [1, 2, 3, 4, 5]
with testing.raises(TypeError):
view_as_windows(A, (2,))
def test_view_as_windows_wrong_window_dimension():
A = np.arange(10)
with testing.raises(ValueError):
view_as_windows(A, (2, 2))
def test_view_as_windows_negative_window_length():
A = np.arange(10)
with testing.raises(ValueError):
view_as_windows(A, (-1,))
def test_view_as_windows_window_too_large():
A = np.arange(10)
with testing.raises(ValueError):
view_as_windows(A, (11,))
def test_view_as_windows_step_below_one():
A = np.arange(10)
with testing.raises(ValueError):
view_as_windows(A, (11,), step=0.9)
def test_view_as_windows_1D():
A = np.arange(10)
window_shape = (3,)
B = view_as_windows(A, window_shape)
assert_equal(B, np.array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7],
[6, 7, 8],
[7, 8, 9]]))
def test_view_as_windows_2D():
A = np.arange(5 * 4).reshape(5, 4)
window_shape = (4, 3)
B = view_as_windows(A, window_shape)
assert_equal(B.shape, (2, 2, 4, 3))
assert_equal(B, np.array([[[[0, 1, 2],
[4, 5, 6],
[8, 9, 10],
[12, 13, 14]],
[[1, 2, 3],
[5, 6, 7],
[9, 10, 11],
[13, 14, 15]]],
[[[4, 5, 6],
[8, 9, 10],
[12, 13, 14],
[16, 17, 18]],
[[5, 6, 7],
[9, 10, 11],
[13, 14, 15],
[17, 18, 19]]]]))
def test_view_as_windows_with_skip():
A = np.arange(20).reshape((5, 4))
B = view_as_windows(A, 2, step=2)
assert_equal(B, [[[[0, 1],
[4, 5]],
[[2, 3],
[6, 7]]],
[[[8, 9],
[12, 13]],
[[10, 11],
[14, 15]]]])
C = view_as_windows(A, 2, step=4)
assert_equal(C.shape, (1, 1, 2, 2))
def test_views_non_contiguous():
A = np.arange(16).reshape((4, 4))
A = A[::2, :]
res_b = view_as_blocks(A, (2, 2))
res_w = view_as_windows(A, (2, 2))
print(res_b)
print(res_w)
expected_b = [[[[0, 1],
[8, 9]],
[[2, 3],
[10, 11]]]]
expected_w = [[[[ 0, 1],
[ 8, 9]],
[[ 1, 2],
[ 9, 10]],
[[ 2, 3],
[10, 11]]]]
assert_equal(res_b, expected_b)
assert_equal(res_w, expected_w)
def test_view_as_windows_step_tuple():
A = np.arange(24).reshape((6, 4))
B = view_as_windows(A, (3, 2), step=3)
assert B.shape == (2, 1, 3, 2)
assert B.size != A.size
C = view_as_windows(A, (3, 2), step=(3, 2))
assert C.shape == (2, 2, 3, 2)
assert C.size == A.size
assert_equal(C, [[[[0, 1],
[4, 5],
[8, 9]],
[[2, 3],
[6, 7],
[10, 11]]],
[[[12, 13],
[16, 17],
[20, 21]],
[[14, 15],
[18, 19],
[22, 23]]]])

View file

@ -0,0 +1,39 @@
import numpy as np
from skimage.util import unique_rows
from skimage._shared import testing
from skimage._shared.testing import assert_equal
def test_discontiguous_array():
ar = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]], np.uint8)
ar = ar[::2]
ar_out = unique_rows(ar)
desired_ar_out = np.array([[1, 0, 1]], np.uint8)
assert_equal(ar_out, desired_ar_out)
def test_uint8_array():
ar = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]], np.uint8)
ar_out = unique_rows(ar)
desired_ar_out = np.array([[0, 1, 0], [1, 0, 1]], np.uint8)
assert_equal(ar_out, desired_ar_out)
def test_float_array():
ar = np.array([[1.1, 0.0, 1.1], [0.0, 1.1, 0.0], [1.1, 0.0, 1.1]],
np.float)
ar_out = unique_rows(ar)
desired_ar_out = np.array([[0.0, 1.1, 0.0], [1.1, 0.0, 1.1]], np.float)
assert_equal(ar_out, desired_ar_out)
def test_1d_array():
ar = np.array([1, 0, 1, 1], np.uint8)
with testing.raises(ValueError):
unique_rows(ar)
def test_3d_array():
ar = np.arange(8).reshape((2, 2, 2))
with testing.raises(ValueError):
unique_rows(ar)