From 874d68ba3f01860d22e3db9b7460dc875cac3a7a Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 20 Dec 2014 16:15:28 -0600 Subject: [PATCH 01/28] # This is a combination of 7 commits. # The first commit's message is: Add a known_warning decorator and suppress warnings in color pkg # This is the 2nd commit message: Use the existing all_warnings context manager # This is the 3rd commit message: Raise warnings in data # This is the 4th commit message: Raise warnings in draw # This is the 5th commit message: Raise warnings in exposure # This is the 6th commit message: Suppress warnings in exposure tests # This is the 7th commit message: Add comments about warning suppressions --- skimage/_shared/utils.py | 1 + skimage/color/tests/__init__.py | 2 ++ skimage/color/tests/test_adapt_rgb.py | 25 +++++++++++++------------ skimage/color/tests/test_colorconv.py | 7 +++++-- skimage/data/tests/__init__.py | 2 ++ skimage/draw/tests/__init__.py | 2 ++ skimage/exposure/tests/__init__.py | 2 ++ skimage/exposure/tests/test_exposure.py | 15 ++++++++++----- skimage/io/_plugins/pil_plugin.py | 4 +++- 9 files changed, 40 insertions(+), 20 deletions(-) create mode 100644 skimage/color/tests/__init__.py create mode 100644 skimage/data/tests/__init__.py create mode 100644 skimage/draw/tests/__init__.py create mode 100644 skimage/exposure/tests/__init__.py diff --git a/skimage/_shared/utils.py b/skimage/_shared/utils.py index 43fda35d..7be979bc 100644 --- a/skimage/_shared/utils.py +++ b/skimage/_shared/utils.py @@ -163,3 +163,4 @@ def assert_nD(array, ndim, arg_name='image'): ndim = [ndim] if not array.ndim in ndim: raise ValueError(msg % (arg_name, '-or-'.join([str(n) for n in ndim]))) + diff --git a/skimage/color/tests/__init__.py b/skimage/color/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/color/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/color/tests/test_adapt_rgb.py b/skimage/color/tests/test_adapt_rgb.py index 2f3060c5..f4da0e58 100644 --- a/skimage/color/tests/test_adapt_rgb.py +++ b/skimage/color/tests/test_adapt_rgb.py @@ -3,54 +3,55 @@ from functools import partial import numpy as np from skimage import img_as_float, img_as_uint -from skimage import color, data, filter +from skimage import color, data, filters from skimage.color.adapt_rgb import adapt_rgb, each_channel, hsv_value - +from skimage._shared.utils import all_warnings # Down-sample image for quicker testing. COLOR_IMAGE = data.astronaut()[::5, ::5] GRAY_IMAGE = data.camera()[::5, ::5] SIGMA = 3 -smooth = partial(filter.gaussian_filter, sigma=SIGMA) +smooth = partial(filters.gaussian_filter, sigma=SIGMA) assert_allclose = partial(np.testing.assert_allclose, atol=1e-8) @adapt_rgb(each_channel) def edges_each(image): - return filter.sobel(image) + return filters.sobel(image) @adapt_rgb(each_channel) def smooth_each(image, sigma): - return filter.gaussian_filter(image, sigma) + return filters.gaussian_filter(image, sigma) @adapt_rgb(hsv_value) def edges_hsv(image): - return filter.sobel(image) + return filters.sobel(image) @adapt_rgb(hsv_value) def smooth_hsv(image, sigma): - return filter.gaussian_filter(image, sigma) + return filters.gaussian_filter(image, sigma) @adapt_rgb(hsv_value) def edges_hsv_uint(image): - return img_as_uint(filter.sobel(image)) + with all_warnings(): # precision loss + return img_as_uint(filters.sobel(image)) def test_gray_scale_image(): # We don't need to test both `hsv_value` and `each_channel` since # `adapt_rgb` is handling gray-scale inputs. - assert_allclose(edges_each(GRAY_IMAGE), filter.sobel(GRAY_IMAGE)) + assert_allclose(edges_each(GRAY_IMAGE), filters.sobel(GRAY_IMAGE)) def test_each_channel(): filtered = edges_each(COLOR_IMAGE) for i, channel in enumerate(np.rollaxis(filtered, axis=-1)): - expected = img_as_float(filter.sobel(COLOR_IMAGE[:, :, i])) + expected = img_as_float(filters.sobel(COLOR_IMAGE[:, :, i])) assert_allclose(channel, expected) @@ -63,7 +64,7 @@ def test_each_channel_with_filter_argument(): def test_hsv_value(): filtered = edges_hsv(COLOR_IMAGE) value = color.rgb2hsv(COLOR_IMAGE)[:, :, 2] - assert_allclose(color.rgb2hsv(filtered)[:, :, 2], filter.sobel(value)) + assert_allclose(color.rgb2hsv(filtered)[:, :, 2], filters.sobel(value)) def test_hsv_value_with_filter_argument(): @@ -80,4 +81,4 @@ def test_hsv_value_with_non_float_output(): filtered_value = color.rgb2hsv(filtered)[:, :, 2] value = color.rgb2hsv(COLOR_IMAGE)[:, :, 2] # Reduce tolerance because dtype conversion. - assert_allclose(filtered_value, filter.sobel(value), rtol=1e-5, atol=1e-5) + assert_allclose(filtered_value, filters.sobel(value), rtol=1e-5, atol=1e-5) diff --git a/skimage/color/tests/test_colorconv.py b/skimage/color/tests/test_colorconv.py index cf960f4e..c61a67b2 100644 --- a/skimage/color/tests/test_colorconv.py +++ b/skimage/color/tests/test_colorconv.py @@ -39,7 +39,8 @@ from skimage.color import (rgb2hsv, hsv2rgb, guess_spatial_dimensions ) -from skimage import data_dir, data +from skimage import data_dir +from skimage._shared.utils import all_warnings import colorsys @@ -156,7 +157,9 @@ class TestColorconv(TestCase): # RGB<->HED roundtrip with ubyte image def test_hed_rgb_roundtrip(self): img_rgb = img_as_ubyte(self.img_rgb) - assert_equal(img_as_ubyte(hed2rgb(rgb2hed(img_rgb))), img_rgb) + with all_warnings(): # precision loss + new = img_as_ubyte(hed2rgb(rgb2hed(img_rgb))) + assert_equal(new, img_rgb) # RGB<->HED roundtrip with float image def test_hed_rgb_float_roundtrip(self): diff --git a/skimage/data/tests/__init__.py b/skimage/data/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/data/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/draw/tests/__init__.py b/skimage/draw/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/draw/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/exposure/tests/__init__.py b/skimage/exposure/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/exposure/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/exposure/tests/test_exposure.py b/skimage/exposure/tests/test_exposure.py index ec9840ee..bb047195 100644 --- a/skimage/exposure/tests/test_exposure.py +++ b/skimage/exposure/tests/test_exposure.py @@ -11,6 +11,7 @@ from skimage import exposure from skimage.exposure.exposure import intensity_range from skimage.color import rgb2gray from skimage.util.dtype import dtype_range +from skimage._shared.utils import all_warnings # Test integer histograms @@ -52,7 +53,8 @@ def test_equalize_uint8_approx(): def test_equalize_ubyte(): - img = skimage.img_as_ubyte(test_img) + with all_warnings(): # precision loss + img = skimage.img_as_ubyte(test_img) img_eq = exposure.equalize_hist(img) cdf, bin_edges = exposure.cumulative_distribution(img_eq) @@ -209,8 +211,9 @@ def test_adapthist_grayscale(): img = skimage.img_as_float(data.astronaut()) img = rgb2gray(img) img = np.dstack((img, img, img)) - adapted = exposure.equalize_adapthist(img, 10, 9, clip_limit=0.01, - nbins=128) + with all_warnings(): # precision loss + adapted = exposure.equalize_adapthist(img, 10, 9, clip_limit=0.01, + nbins=128) assert_almost_equal = np.testing.assert_almost_equal assert img.shape == adapted.shape assert_almost_equal(peak_snr(img, adapted), 97.6876, 3) @@ -226,7 +229,8 @@ def test_adapthist_color(): warnings.simplefilter('always') hist, bin_centers = exposure.histogram(img) assert len(w) > 0 - adapted = exposure.equalize_adapthist(img, clip_limit=0.01) + with all_warnings(): # precision loss + adapted = exposure.equalize_adapthist(img, clip_limit=0.01) assert_almost_equal = np.testing.assert_almost_equal assert adapted.min() == 0 @@ -244,7 +248,8 @@ def test_adapthist_alpha(): img = skimage.img_as_float(data.astronaut()) alpha = np.ones((img.shape[0], img.shape[1]), dtype=float) img = np.dstack((img, alpha)) - adapted = exposure.equalize_adapthist(img) + with all_warnings(): # precision loss + adapted = exposure.equalize_adapthist(img) assert adapted.shape != img.shape img = img[:, :, :3] full_scale = skimage.exposure.rescale_intensity(img) diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index 5018be49..1b0d9efd 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -39,6 +39,7 @@ def imread(fname, dtype=None, img_num=None, **kwargs): .. [2] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html """ + print('imread', fname) if hasattr(fname, 'lower') and dtype is None: kwargs.setdefault('key', img_num) if fname.lower().endswith(('.tiff', '.tif')): @@ -47,7 +48,8 @@ def imread(fname, dtype=None, img_num=None, **kwargs): im = Image.open(fname) try: # this will raise an IOError if the file is not readable - im.getdata()[0] + #im.getdata()[0] + pass except IOError: site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" raise ValueError('Could not load "%s"\nPlease see documentation at: %s' % (fname, site)) From 9e8f91930e9b257f0d538e5543c1c5d9e462b5d3 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 23 Dec 2014 16:46:44 -0600 Subject: [PATCH 02/28] Handle warnings in several packages Start handling warnings in data, exposure, and draw Add a known_warning decorator and suppress warnings in color pkg Use the existing all_warnings context manager Raise warnings in data Raise warnings in draw Raise warnings in exposure Suppress warnings in exposure tests Add comments about warning suppressions Raise warnings in feature Fix warnings in filter package Add warning handling to graph Handle warnings in io package --- skimage/_shared/testing.py | 32 ++++++++++++------- skimage/feature/tests/__init__.py | 2 ++ skimage/filters/rank/tests/__init__.py | 2 ++ skimage/filters/rank/tests/test_rank.py | 41 +++++++++++++++++-------- skimage/filters/tests/__init__.py | 2 ++ skimage/filters/tests/test_gaussian.py | 4 ++- skimage/filters/thresholding.py | 6 ++-- skimage/graph/tests/__init__.py | 2 ++ skimage/io/_plugins/pil_plugin.py | 10 +++--- skimage/io/tests/__init__.py | 2 ++ skimage/io/tests/test_pil.py | 7 +++-- skimage/io/tests/test_plugin_util.py | 23 +++++++++----- 12 files changed, 91 insertions(+), 42 deletions(-) create mode 100644 skimage/feature/tests/__init__.py create mode 100644 skimage/filters/rank/tests/__init__.py create mode 100644 skimage/filters/tests/__init__.py create mode 100644 skimage/graph/tests/__init__.py create mode 100644 skimage/io/tests/__init__.py diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index 0cf65cb4..1dae36c3 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -9,6 +9,7 @@ from skimage import ( data, io, img_as_uint, img_as_float, img_as_int, img_as_ubyte) from numpy import testing import numpy as np +from skimage._shared.utils import all_warnings SKIP_RE = re.compile("(\s*>>>.*?)(\s*)#\s*skip\s+if\s+(.*)$") @@ -115,20 +116,25 @@ def color_check(plugin, fmt='png'): testing.assert_allclose(img2.astype(np.uint8), r2) img3 = img_as_float(img) - r3 = roundtrip(img3, plugin, fmt) + with all_warnings(): # precision loss + r3 = roundtrip(img3, plugin, fmt) testing.assert_allclose(r3, img) - img4 = img_as_int(img) + with all_warnings(): # precision loss + img4 = img_as_int(img) if fmt.lower() in (('tif', 'tiff')): img4 -= 100 - r4 = roundtrip(img4, plugin, fmt) + with all_warnings(): # sign loss + r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img4) else: - r4 = roundtrip(img4, plugin, fmt) - testing.assert_allclose(r4, img_as_ubyte(img4)) + with all_warnings(): # sign loss + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img_as_ubyte(img4)) img5 = img_as_uint(img) - r5 = roundtrip(img5, plugin, fmt) + with all_warnings(): # precision loss + r5 = roundtrip(img5, plugin, fmt) testing.assert_allclose(r5, img) @@ -147,20 +153,24 @@ def mono_check(plugin, fmt='png'): testing.assert_allclose(img2.astype(np.uint8), r2) img3 = img_as_float(img) - r3 = roundtrip(img3, plugin, fmt) + with all_warnings(): # precision loss + r3 = roundtrip(img3, plugin, fmt) if r3.dtype.kind == 'f': testing.assert_allclose(img3, r3) else: testing.assert_allclose(r3, img_as_uint(img)) - img4 = img_as_int(img) + with all_warnings(): # precision loss + img4 = img_as_int(img) if fmt.lower() in (('tif', 'tiff')): img4 -= 100 - r4 = roundtrip(img4, plugin, fmt) + with all_warnings(): # sign loss + r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img4) else: - r4 = roundtrip(img4, plugin, fmt) - testing.assert_allclose(r4, img_as_uint(img4)) + with all_warnings(): # sign loss + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img_as_uint(img4)) img5 = img_as_uint(img) r5 = roundtrip(img5, plugin, fmt) diff --git a/skimage/feature/tests/__init__.py b/skimage/feature/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/feature/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/filters/rank/tests/__init__.py b/skimage/filters/rank/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/filters/rank/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/filters/rank/tests/test_rank.py b/skimage/filters/rank/tests/test_rank.py index 23745ebf..f2d91ff0 100644 --- a/skimage/filters/rank/tests/test_rank.py +++ b/skimage/filters/rank/tests/test_rank.py @@ -3,15 +3,22 @@ import numpy as np from numpy.testing import run_module_suite, assert_equal, assert_raises import skimage -from skimage import img_as_ubyte, img_as_uint, img_as_float +from skimage import img_as_ubyte, img_as_float from skimage import data, util, morphology from skimage.morphology import cmorph, disk from skimage.filters import rank +from skimage._shared.utils import all_warnings np.random.seed(0) def test_all(): + + with all_warnings(): # precision loss + check_all() + + +def check_all(): image = np.random.rand(25, 25) selem = morphology.disk(1) refs = np.load(os.path.join(skimage.data_dir, "rank_filter_tests.npz")) @@ -151,8 +158,9 @@ def test_bitdepth(): for i in range(5): image = np.ones((100, 100), dtype=np.uint16) * 255 * 2 ** i - r = rank.mean_percentile(image=image, selem=elem, mask=mask, - out=out, shift_x=0, shift_y=0, p0=.1, p1=.9) + with all_warnings(): # bit depth + rank.mean_percentile(image=image, selem=elem, mask=mask, + out=out, shift_x=0, shift_y=0, p0=.1, p1=.9) def test_population(): @@ -261,7 +269,8 @@ def test_compare_ubyte_vs_float(): for method in methods: func = getattr(rank, method) out_u = func(image_uint, disk(3)) - out_f = func(image_float, disk(3)) + with all_warnings(): # precision loss + out_f = func(image_float, disk(3)) assert_equal(out_u, out_f) @@ -273,9 +282,10 @@ def test_compare_8bit_unsigned_vs_signed(): image = img_as_ubyte(data.camera()) image[image > 127] = 0 image_s = image.astype(np.int8) - image_u = img_as_ubyte(image_s) + with all_warnings(): # precision loss + image_u = img_as_ubyte(image_s) - assert_equal(image_u, img_as_ubyte(image_s)) + assert_equal(image_u, img_as_ubyte(image_s)) methods = ['autolevel', 'bottomhat', 'equalize', 'gradient', 'maximum', 'mean', 'subtract_mean', 'median', 'minimum', 'modal', @@ -283,8 +293,10 @@ def test_compare_8bit_unsigned_vs_signed(): for method in methods: func = getattr(rank, method) - out_u = func(image_u, disk(3)) - out_s = func(image_s, disk(3)) + + with all_warnings(): # sign loss + out_u = func(image_u, disk(3)) + out_s = func(image_s, disk(3)) assert_equal(out_u, out_s) @@ -474,10 +486,12 @@ def test_entropy(): selem = np.ones((64, 64), dtype=np.uint8) data = np.tile( np.reshape(np.arange(4096), (64, 64)), (2, 2)).astype(np.uint16) - assert(np.max(rank.entropy(data, selem)) == 12) + with all_warnings(): # bitdepth + assert(np.max(rank.entropy(data, selem)) == 12) # make sure output is of dtype double - out = rank.entropy(data, np.ones((16, 16), dtype=np.uint8)) + with all_warnings(): # bitdepth + out = rank.entropy(data, np.ones((16, 16), dtype=np.uint8)) assert out.dtype == np.double @@ -508,9 +522,10 @@ def test_16bit(): for bitdepth in range(17): value = 2 ** bitdepth - 1 image[10, 10] = value - assert rank.minimum(image, selem)[10, 10] == 0 - assert rank.maximum(image, selem)[10, 10] == value - assert rank.mean(image, selem)[10, 10] == int(value / selem.size) + with all_warnings(): # bitdepth + assert rank.minimum(image, selem)[10, 10] == 0 + assert rank.maximum(image, selem)[10, 10] == value + assert rank.mean(image, selem)[10, 10] == int(value / selem.size) def test_bilateral(): diff --git a/skimage/filters/tests/__init__.py b/skimage/filters/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/filters/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/filters/tests/test_gaussian.py b/skimage/filters/tests/test_gaussian.py index 612dd9e4..01e1c12e 100644 --- a/skimage/filters/tests/test_gaussian.py +++ b/skimage/filters/tests/test_gaussian.py @@ -1,5 +1,6 @@ import numpy as np from skimage.filters._gaussian import gaussian_filter +from skimage._shared.utils import all_warnings def test_null_sigma(): @@ -25,7 +26,8 @@ def test_multichannel(): assert np.allclose([a[..., i].mean() for i in range(3)], [gaussian_rgb_a[..., i].mean() for i in range(3)]) # Test multichannel = None - gaussian_rgb_a = gaussian_filter(a, sigma=1, mode='reflect') + with all_warnings(): # multichannel + gaussian_rgb_a = gaussian_filter(a, sigma=1, mode='reflect') # Check that the mean value is conserved in each channel # (color channels are not mixed together) assert np.allclose([a[..., i].mean() for i in range(3)], diff --git a/skimage/filters/thresholding.py b/skimage/filters/thresholding.py index 5a737293..76a725a7 100644 --- a/skimage/filters/thresholding.py +++ b/skimage/filters/thresholding.py @@ -121,7 +121,7 @@ def threshold_otsu(image, nbins=256): >>> thresh = threshold_otsu(image) >>> binary = image <= thresh """ - hist, bin_centers = histogram(image, nbins) + hist, bin_centers = histogram(image.flatten(), nbins) hist = hist.astype(float) # class probabilities for all possible thresholds @@ -176,7 +176,7 @@ def threshold_yen(image, nbins=256): >>> thresh = threshold_yen(image) >>> binary = image <= thresh """ - hist, bin_centers = histogram(image, nbins) + hist, bin_centers = histogram(image.flatten(), nbins) # On blank images (e.g. filled with 0) with int dtype, `histogram()` # returns `bin_centers` containing only one value. Speed up with it. if bin_centers.size == 1: @@ -246,7 +246,7 @@ def threshold_isodata(image, nbins=256, return_all=False): >>> binary = image > thresh """ - hist, bin_centers = histogram(image, nbins) + hist, bin_centers = histogram(image.flatten(), nbins) # image only contains one unique value if len(bin_centers) == 1: diff --git a/skimage/graph/tests/__init__.py b/skimage/graph/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/graph/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index 1b0d9efd..f8414283 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -102,7 +102,7 @@ def pil_to_ndarray(im, dtype=None, img_num=None): dtype = '>u2' if im.mode.endswith('B') else ' Date: Sat, 20 Dec 2014 18:57:16 -0600 Subject: [PATCH 03/28] Handle more warnings and reset io plugins as needed Reset plugins prior to running collections test Handle warnings in morphology pkg Add __init__ for morpohology tests Handle warnings for novice pkg Handle warnings for restoration pkg Handle warnings for segmentation pkg Handle warnings for _shared pkg Handle warnings for transform pkg Handle warnings for util pkg Handle warnings in viewer module --- skimage/_shared/tests/__init__.py | 2 + skimage/io/tests/test_collection.py | 2 + skimage/morphology/tests/__init__.py | 2 + skimage/morphology/tests/test_binary.py | 19 ++++-- skimage/morphology/tests/test_ccomp.py | 32 +++++----- skimage/morphology/tests/test_grey.py | 21 +++++-- skimage/novice/tests/__init__.py | 2 + skimage/novice/tests/test_novice.py | 12 ++-- skimage/restoration/tests/__init__.py | 2 + skimage/restoration/tests/test_unwrap.py | 10 +++- skimage/segmentation/tests/__init__.py | 2 + .../segmentation/tests/test_random_walker.py | 58 +++++++++++++------ skimage/transform/tests/__init__.py | 2 + skimage/transform/tests/test_geometric.py | 13 +++-- .../transform/tests/test_hough_transform.py | 23 +++++--- skimage/util/tests/__init__.py | 2 + skimage/util/tests/test_dtype.py | 8 ++- skimage/viewer/tests/__init__.py | 2 + skimage/viewer/tests/test_plugins.py | 9 ++- skimage/viewer/tests/test_viewer.py | 5 +- skimage/viewer/tests/test_widgets.py | 8 ++- 21 files changed, 161 insertions(+), 75 deletions(-) create mode 100644 skimage/_shared/tests/__init__.py create mode 100644 skimage/morphology/tests/__init__.py create mode 100644 skimage/novice/tests/__init__.py create mode 100644 skimage/restoration/tests/__init__.py create mode 100644 skimage/segmentation/tests/__init__.py create mode 100644 skimage/transform/tests/__init__.py create mode 100644 skimage/util/tests/__init__.py create mode 100644 skimage/viewer/tests/__init__.py diff --git a/skimage/_shared/tests/__init__.py b/skimage/_shared/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/_shared/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/io/tests/test_collection.py b/skimage/io/tests/test_collection.py index 1e9fea73..c97e63ac 100644 --- a/skimage/io/tests/test_collection.py +++ b/skimage/io/tests/test_collection.py @@ -5,6 +5,7 @@ from numpy.testing import assert_raises, assert_equal, assert_allclose from skimage import data_dir from skimage.io.collection import ImageCollection, alphanumeric_key +from skimage.io import reset_plugins def test_string_split(): @@ -31,6 +32,7 @@ class TestImageCollection(): for pic in ['camera.png', 'moon.png']] def setUp(self): + reset_plugins() # Generic image collection with images of different shapes. self.images = ImageCollection(self.pattern) # Image collection with images having shapes that match. diff --git a/skimage/morphology/tests/__init__.py b/skimage/morphology/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/morphology/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/morphology/tests/test_binary.py b/skimage/morphology/tests/test_binary.py index 53ad504e..3a3abf97 100644 --- a/skimage/morphology/tests/test_binary.py +++ b/skimage/morphology/tests/test_binary.py @@ -4,6 +4,7 @@ from numpy import testing from skimage import data, color from skimage.util import img_as_bool from skimage.morphology import binary, grey, selem +from skimage._shared.utils import all_warnings from scipy import ndimage @@ -14,35 +15,40 @@ bw_img = img > 100 def test_non_square_image(): strel = selem.square(3) binary_res = binary.binary_erosion(bw_img[:100, :200], strel) - grey_res = img_as_bool(grey.erosion(bw_img[:100, :200], strel)) + with all_warnings(): # precision loss + grey_res = img_as_bool(grey.erosion(bw_img[:100, :200], strel)) testing.assert_array_equal(binary_res, grey_res) def test_binary_erosion(): strel = selem.square(3) binary_res = binary.binary_erosion(bw_img, strel) - grey_res = img_as_bool(grey.erosion(bw_img, strel)) + with all_warnings(): # precision loss + grey_res = img_as_bool(grey.erosion(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res) def test_binary_dilation(): strel = selem.square(3) binary_res = binary.binary_dilation(bw_img, strel) - grey_res = img_as_bool(grey.dilation(bw_img, strel)) + with all_warnings(): # precision loss + grey_res = img_as_bool(grey.dilation(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res) def test_binary_closing(): strel = selem.square(3) binary_res = binary.binary_closing(bw_img, strel) - grey_res = img_as_bool(grey.closing(bw_img, strel)) + with all_warnings(): # precision loss + grey_res = img_as_bool(grey.closing(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res) def test_binary_opening(): strel = selem.square(3) binary_res = binary.binary_opening(bw_img, strel) - grey_res = img_as_bool(grey.opening(bw_img, strel)) + with all_warnings(): # precision loss + grey_res = img_as_bool(grey.opening(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res) @@ -51,7 +57,8 @@ def test_selem_overflow(): img = np.zeros((20, 20)) img[2:19, 2:19] = 1 binary_res = binary.binary_erosion(img, strel) - grey_res = img_as_bool(grey.erosion(img, strel)) + with all_warnings(): # precision loss + grey_res = img_as_bool(grey.erosion(img, strel)) testing.assert_array_equal(binary_res, grey_res) diff --git a/skimage/morphology/tests/test_ccomp.py b/skimage/morphology/tests/test_ccomp.py index aebb443a..1a321a08 100644 --- a/skimage/morphology/tests/test_ccomp.py +++ b/skimage/morphology/tests/test_ccomp.py @@ -1,11 +1,9 @@ import numpy as np from numpy.testing import assert_array_equal, run_module_suite -from skimage.morphology import label +from skimage.morphology import label as _label import skimage.measure._ccomp as ccomp -from warnings import catch_warnings -from skimage._shared.utils import skimage_deprecation - +from skimage._shared.utils import all_warnings np.random.seed(0) # The background label value @@ -13,6 +11,12 @@ np.random.seed(0) BG = -1 +def label(*args, **kwargs): + """Wrap the label function to avoid deprecation warning""" + with all_warnings(): + return _label(*args, **kwargs) + + class TestConnectedComponents: def setup(self): self.x = np.array([[0, 0, 3, 2, 1, 9], @@ -34,7 +38,7 @@ class TestConnectedComponents: def test_random(self): x = (np.random.rand(20, 30) * 5).astype(np.int) - with catch_warnings(): + with all_warnings(): labels = label(x) n = labels.max() @@ -46,13 +50,13 @@ class TestConnectedComponents: x = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]) - with catch_warnings(): + with all_warnings(): assert_array_equal(label(x), x) def test_4_vs_8(self): x = np.array([[0, 1], [1, 0]], dtype=int) - with catch_warnings(): + with all_warnings(): assert_array_equal(label(x, 4), [[0, 1], [2, 3]]) @@ -65,7 +69,7 @@ class TestConnectedComponents: [1, 1, 5], [0, 0, 0]]) - with catch_warnings(): + with all_warnings(): assert_array_equal(label(x), [[0, 1, 1], [0, 0, 2], [3, 3, 3]]) @@ -101,7 +105,7 @@ class TestConnectedComponents: [0, 0, 6], [5, 5, 5]]) - with catch_warnings(): + with all_warnings(): assert_array_equal(label(x, return_num=True)[1], 4) assert_array_equal(label(x, background=0, return_num=True)[1], 3) @@ -152,7 +156,7 @@ class TestConnectedComponents3d: def test_random(self): x = (np.random.rand(20, 30) * 5).astype(np.int) - with catch_warnings(): + with all_warnings(): labels = label(x) n = labels.max() @@ -165,7 +169,7 @@ class TestConnectedComponents3d: x[0, 2, 2] = 1 x[1, 1, 1] = 1 x[2, 0, 0] = 1 - with catch_warnings(): + with all_warnings(): assert_array_equal(label(x), x) def test_4_vs_8(self): @@ -174,7 +178,7 @@ class TestConnectedComponents3d: x[1, 0, 0] = 1 label4 = x.copy() label4[1, 0, 0] = 2 - with catch_warnings(): + with all_warnings(): assert_array_equal(label(x, 4), label4) assert_array_equal(label(x, 8), x) @@ -202,7 +206,7 @@ class TestConnectedComponents3d: [BG, 0, 1], [BG, BG, BG]]) - with catch_warnings(): + with all_warnings(): assert_array_equal(label(x), lnb) assert_array_equal(label(x, background=0), lb) @@ -240,7 +244,7 @@ class TestConnectedComponents3d: [0, 0, 6], [5, 5, 5]]) - with catch_warnings(): + with all_warnings(): assert_array_equal(label(x, return_num=True)[1], 4) assert_array_equal(label(x, background=0, return_num=True)[1], 3) diff --git a/skimage/morphology/tests/test_grey.py b/skimage/morphology/tests/test_grey.py index 00f4ad37..9c978105 100644 --- a/skimage/morphology/tests/test_grey.py +++ b/skimage/morphology/tests/test_grey.py @@ -7,6 +7,7 @@ from scipy import ndimage import skimage from skimage import data_dir from skimage.morphology import grey, selem +from skimage._shared.utils import all_warnings lena = np.load(os.path.join(data_dir, 'lena_GRAY_U8.npy')) @@ -170,9 +171,12 @@ def test_3d_fallback_white_tophat(): image[2, 2:4, 2:4] = 1 image[3, 2:5, 2:5] = 1 image[4, 3:5, 3:5] = 1 - new_image = grey.white_tophat(image) + + with all_warnings(): # scipy upstream warning + new_image = grey.white_tophat(image) footprint = ndimage.generate_binary_structure(3,1) - image_expected = ndimage.white_tophat(image,footprint=footprint) + with all_warnings(): # scipy upstream warning + image_expected = ndimage.white_tophat(image,footprint=footprint) testing.assert_array_equal(new_image, image_expected) def test_3d_fallback_black_tophat(): @@ -180,9 +184,12 @@ def test_3d_fallback_black_tophat(): image[2, 2:4, 2:4] = 0 image[3, 2:5, 2:5] = 0 image[4, 3:5, 3:5] = 0 - new_image = grey.black_tophat(image) + + with all_warnings(): # scipy upstream warning + new_image = grey.black_tophat(image) footprint = ndimage.generate_binary_structure(3,1) - image_expected = ndimage.black_tophat(image,footprint=footprint) + with all_warnings(): # scipy upstream warning + image_expected = ndimage.black_tophat(image,footprint=footprint) testing.assert_array_equal(new_image, image_expected) def test_2d_ndimage_equivalence(): @@ -216,10 +223,12 @@ class TestDTypes(): self.expected_closing = np.load(fname_closing)[arrname] def _test_image(self, image): - result_opening = grey.opening(image, self.disk) + with all_warnings(): # precision loss + result_opening = grey.opening(image, self.disk) testing.assert_equal(result_opening, self.expected_opening) - result_closing = grey.closing(image, self.disk) + with all_warnings(): # precision loss + result_closing = grey.closing(image, self.disk) testing.assert_equal(result_closing, self.expected_closing) def test_float(self): diff --git a/skimage/novice/tests/__init__.py b/skimage/novice/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/novice/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/novice/tests/test_novice.py b/skimage/novice/tests/test_novice.py index a1f750ab..e2aafef0 100644 --- a/skimage/novice/tests/test_novice.py +++ b/skimage/novice/tests/test_novice.py @@ -7,16 +7,12 @@ from skimage import novice from skimage.novice._novice import (array_to_xy_origin, xy_to_array_origin, rgb_transpose) from skimage import data_dir - +from skimage._shared.utils import all_warnings IMAGE_PATH = os.path.join(data_dir, "chelsea.png") SMALL_IMAGE_PATH = os.path.join(data_dir, "block.png") -def _array_2d_to_RGBA(array): - return np.tile(array[:, :, np.newaxis], (1, 1, 4)) - - def _array_2d_to_RGBA(array): return np.tile(array[:, :, np.newaxis], (1, 1, 4)) @@ -62,7 +58,8 @@ def test_modify(): assert p.blue <= 128 s = pic.size - pic.size = (pic.width / 2, pic.height / 2) + with all_warnings(): # precision loss + pic.size = (pic.width / 2, pic.height / 2) assert_equal(pic.size, (int(s[0] / 2), int(s[1] / 2))) assert pic.modified @@ -139,7 +136,8 @@ def test_modified_on_set_pixel(): def test_update_on_save(): pic = novice.Picture(array=np.zeros((3, 3, 3))) - pic.size = (6, 6) + with all_warnings(): # precision loss + pic.size = (6, 6) assert pic.modified assert pic.path is None diff --git a/skimage/restoration/tests/__init__.py b/skimage/restoration/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/restoration/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/restoration/tests/test_unwrap.py b/skimage/restoration/tests/test_unwrap.py index 39723894..4819ea24 100644 --- a/skimage/restoration/tests/test_unwrap.py +++ b/skimage/restoration/tests/test_unwrap.py @@ -7,6 +7,7 @@ from numpy.testing import (run_module_suite, assert_array_almost_equal_nulp, import warnings from skimage.restoration import unwrap_phase +from skimage._shared.utils import all_warnings def assert_phase_almost_equal(a, b, *args, **kwargs): @@ -132,9 +133,12 @@ def test_mask(): assert_array_almost_equal_nulp(image_unwrapped[:, -1], image[i, -1]) # Same tests, but forcing use of the 3D unwrapper by reshaping - image_wrapped_3d = image_wrapped.reshape((1,) + image_wrapped.shape) - image_unwrapped_3d = unwrap_phase(image_wrapped_3d) - image_unwrapped_3d -= image_unwrapped_3d[0, 0, 0] # remove phase shift + with all_warnings(): # 1 dimension + shape = (1,) + image_wrapped.shape + image_wrapped_3d = image_wrapped.reshape(shape) + image_unwrapped_3d = unwrap_phase(image_wrapped_3d) + # remove phase shift + image_unwrapped_3d -= image_unwrapped_3d[0, 0, 0] assert_array_almost_equal_nulp(image_unwrapped_3d[:, :, -1], image[i, -1]) diff --git a/skimage/segmentation/tests/__init__.py b/skimage/segmentation/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/segmentation/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/segmentation/tests/test_random_walker.py b/skimage/segmentation/tests/test_random_walker.py index 9d30473b..0bb5b8d8 100644 --- a/skimage/segmentation/tests/test_random_walker.py +++ b/skimage/segmentation/tests/test_random_walker.py @@ -1,6 +1,7 @@ import numpy as np from skimage.segmentation import random_walker from skimage.transform import resize +from skimage._shared.utils import all_warnings def make_2d_syntheticdata(lx, ly=None): @@ -74,10 +75,12 @@ def test_2d_cg(): lx = 70 ly = 100 data, labels = make_2d_syntheticdata(lx, ly) - labels_cg = random_walker(data, labels, beta=90, mode='cg') + with all_warnings(): # cg mode + labels_cg = random_walker(data, labels, beta=90, mode='cg') assert (labels_cg[25:45, 40:60] == 2).all() assert data.shape == labels.shape - full_prob = random_walker(data, labels, beta=90, mode='cg', + with all_warnings(): # cg mode + full_prob = random_walker(data, labels, beta=90, mode='cg', return_full_prob=True) assert (full_prob[1, 25:45, 40:60] >= full_prob[0, 25:45, 40:60]).all() @@ -89,10 +92,12 @@ def test_2d_cg_mg(): lx = 70 ly = 100 data, labels = make_2d_syntheticdata(lx, ly) - labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') + with all_warnings(): # pyamg optional + labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') assert (labels_cg_mg[25:45, 40:60] == 2).all() assert data.shape == labels.shape - full_prob = random_walker(data, labels, beta=90, mode='cg_mg', + with all_warnings(): # pyamg optional + full_prob = random_walker(data, labels, beta=90, mode='cg_mg', return_full_prob=True) assert (full_prob[1, 25:45, 40:60] >= full_prob[0, 25:45, 40:60]).all() @@ -106,7 +111,8 @@ def test_types(): data, labels = make_2d_syntheticdata(lx, ly) data = 255 * (data - data.min()) // (data.max() - data.min()) data = data.astype(np.uint8) - labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') + with all_warnings(): # pyamg optional + labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') assert (labels_cg_mg[25:45, 40:60] == 2).all() assert data.shape == labels.shape return data, labels_cg_mg @@ -139,7 +145,8 @@ def test_3d(): n = 30 lx, ly, lz = n, n, n data, labels = make_3d_syntheticdata(lx, ly, lz) - labels = random_walker(data, labels, mode='cg') + with all_warnings(): # cg mode + labels = random_walker(data, labels, mode='cg') assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all() assert data.shape == labels.shape return data, labels @@ -152,7 +159,8 @@ def test_3d_inactive(): old_labels = np.copy(labels) labels[5:25, 26:29, 26:29] = -1 after_labels = np.copy(labels) - labels = random_walker(data, labels, mode='cg') + with all_warnings(): # cg mode + labels = random_walker(data, labels, mode='cg') assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all() assert data.shape == labels.shape return data, labels, old_labels, after_labels @@ -162,9 +170,12 @@ def test_multispectral_2d(): lx, ly = 70, 100 data, labels = make_2d_syntheticdata(lx, ly) data = data[..., np.newaxis].repeat(2, axis=-1) # Expect identical output - multi_labels = random_walker(data, labels, mode='cg', multichannel=True) + with all_warnings(): # cg mode + multi_labels = random_walker(data, labels, mode='cg', + multichannel=True) assert data[..., 0].shape == labels.shape - single_labels = random_walker(data[..., 0], labels, mode='cg') + with all_warnings(): # cg mode + single_labels = random_walker(data[..., 0], labels, mode='cg') assert (multi_labels.reshape(labels.shape)[25:45, 40:60] == 2).all() assert data[..., 0].shape == labels.shape return data, multi_labels, single_labels, labels @@ -175,9 +186,12 @@ def test_multispectral_3d(): lx, ly, lz = n, n, n data, labels = make_3d_syntheticdata(lx, ly, lz) data = data[..., np.newaxis].repeat(2, axis=-1) # Expect identical output - multi_labels = random_walker(data, labels, mode='cg', multichannel=True) + with all_warnings(): # cg mode + multi_labels = random_walker(data, labels, mode='cg', + multichannel=True) assert data[..., 0].shape == labels.shape - single_labels = random_walker(data[..., 0], labels, mode='cg') + with all_warnings(): # cg mode + single_labels = random_walker(data[..., 0], labels, mode='cg') assert (multi_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all() assert (single_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all() assert data[..., 0].shape == labels.shape @@ -203,7 +217,8 @@ def test_spacing_0(): lz // 4 - small_l // 8] = 2 # Test with `spacing` kwarg - labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg', + with all_warnings(): # cg mode + labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg', spacing=(1., 1., 0.5)) assert (labels_aniso[13:17, 13:17, 7:9] == 2).all() @@ -230,8 +245,9 @@ def test_spacing_1(): # Test with `spacing` kwarg # First, anisotropic along Y - labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg', - spacing=(1., 2., 1.)) + with all_warnings(): # using cd mode + labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg', + spacing=(1., 2., 1.)) assert (labels_aniso[13:17, 26:34, 13:17] == 2).all() # Rescale `data` along X axis @@ -249,9 +265,10 @@ def test_spacing_1(): lz // 2 - small_l // 4] = 2 # Anisotropic along X - labels_aniso2 = random_walker(data_aniso, - labels_aniso2, - mode='cg', spacing=(2., 1., 1.)) + with all_warnings(): # cg mode + labels_aniso2 = random_walker(data_aniso, + labels_aniso2, + mode='cg', spacing=(2., 1., 1.)) assert (labels_aniso2[26:34, 13:17, 13:17] == 2).all() @@ -259,14 +276,17 @@ def test_trivial_cases(): # When all voxels are labeled img = np.ones((10, 10)) labels = np.ones((10, 10)) - pass_through = random_walker(img, labels) + + with all_warnings(): # using provided labels + pass_through = random_walker(img, labels) np.testing.assert_array_equal(pass_through, labels) # When all voxels are labeled AND return_full_prob is True labels[:, :5] = 3 expected = np.concatenate(((labels == 1)[..., np.newaxis], (labels == 3)[..., np.newaxis]), axis=2) - test = random_walker(img, labels, return_full_prob=True) + with all_warnings(): # using provided labels + test = random_walker(img, labels, return_full_prob=True) np.testing.assert_array_equal(test, expected) diff --git a/skimage/transform/tests/__init__.py b/skimage/transform/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/transform/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/transform/tests/test_geometric.py b/skimage/transform/tests/test_geometric.py index 2d81a23d..b6e0597f 100644 --- a/skimage/transform/tests/test_geometric.py +++ b/skimage/transform/tests/test_geometric.py @@ -7,6 +7,7 @@ from skimage.transform import (estimate_transform, matrix_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) +from skimage._shared.utils import all_warnings SRC = np.array([ @@ -49,7 +50,7 @@ def test_estimate_transform(): def test_matrix_transform(): tform = AffineTransform(scale=(0.1, 0.5), rotation=2) - assert_equal(tform(SRC), matrix_transform(SRC, tform._matrix)) + assert_equal(tform(SRC), matrix_transform(SRC, tform.params)) def test_similarity_estimation(): @@ -209,13 +210,13 @@ def test_union(): tform2 = SimilarityTransform(scale=0.1, rotation=0.9) tform3 = SimilarityTransform(scale=0.1 ** 2, rotation=0.3 + 0.9) tform = tform1 + tform2 - assert_array_almost_equal(tform._matrix, tform3._matrix) + assert_array_almost_equal(tform.params, tform3.params) tform1 = AffineTransform(scale=(0.1, 0.1), rotation=0.3) tform2 = SimilarityTransform(scale=0.1, rotation=0.9) tform3 = SimilarityTransform(scale=0.1 ** 2, rotation=0.3 + 0.9) tform = tform1 + tform2 - assert_array_almost_equal(tform._matrix, tform3._matrix) + assert_array_almost_equal(tform.params, tform3.params) assert tform.__class__ == ProjectiveTransform tform = AffineTransform(scale=(0.1, 0.1), rotation=0.3) @@ -251,10 +252,12 @@ def test_invalid_input(): def test_deprecated_params_attributes(): for t in ('projective', 'affine', 'similarity'): tform = estimate_transform(t, SRC, DST) - assert_equal(tform._matrix, tform.params) + with all_warnings(): # _matrix is deprecated + assert_equal(tform._matrix, tform.params) tform = estimate_transform('polynomial', SRC, DST, order=3) - assert_equal(tform._params, tform.params) + with all_warnings(): # _params is deprecated + assert_equal(tform._params, tform.params) if __name__ == "__main__": diff --git a/skimage/transform/tests/test_hough_transform.py b/skimage/transform/tests/test_hough_transform.py index fb19d8c1..ae6e0cf6 100644 --- a/skimage/transform/tests/test_hough_transform.py +++ b/skimage/transform/tests/test_hough_transform.py @@ -3,6 +3,7 @@ from numpy.testing import assert_almost_equal, assert_equal import skimage.transform as tf from skimage.draw import line, circle_perimeter, ellipse_perimeter +from skimage._shared.utils import all_warnings def append_desc(func, description): @@ -67,7 +68,8 @@ def test_hough_line_peaks(): out, angles, d = tf.hough_line(img) - out, theta, dist = tf.hough_line_peaks(out, angles, d) + with all_warnings(): # _ccomp deprecation + out, theta, dist = tf.hough_line_peaks(out, angles, d) assert_equal(len(dist), 1) assert_almost_equal(dist[0], 80.723, 1) @@ -79,13 +81,19 @@ def test_hough_line_peaks_dist(): img[:, 30] = True img[:, 40] = True hspace, angles, dists = tf.hough_line(img) - assert len(tf.hough_line_peaks(hspace, angles, dists, - min_distance=5)[0]) == 2 - assert len(tf.hough_line_peaks(hspace, angles, dists, - min_distance=15)[0]) == 1 + with all_warnings(): # _ccomp deprecation + assert len(tf.hough_line_peaks(hspace, angles, dists, + min_distance=5)[0]) == 2 + assert len(tf.hough_line_peaks(hspace, angles, dists, + min_distance=15)[0]) == 1 def test_hough_line_peaks_angle(): + with all_warnings(): # _ccomp deprecation + check_hough_line_peaks_angle() + + +def check_hough_line_peaks_angle(): img = np.zeros((100, 100), dtype=np.bool_) img[:, 0] = True img[0, :] = True @@ -116,8 +124,9 @@ def test_hough_line_peaks_num(): img[:, 30] = True img[:, 40] = True hspace, angles, dists = tf.hough_line(img) - assert len(tf.hough_line_peaks(hspace, angles, dists, min_distance=0, - min_angle=0, num_peaks=1)[0]) == 1 + with all_warnings(): # _ccomp deprecation + assert len(tf.hough_line_peaks(hspace, angles, dists, min_distance=0, + min_angle=0, num_peaks=1)[0]) == 1 def test_hough_circle(): diff --git a/skimage/util/tests/__init__.py b/skimage/util/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/util/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/util/tests/test_dtype.py b/skimage/util/tests/test_dtype.py index ae26cd27..50ad3fc4 100644 --- a/skimage/util/tests/test_dtype.py +++ b/skimage/util/tests/test_dtype.py @@ -3,6 +3,7 @@ from numpy.testing import assert_equal, assert_raises from skimage import img_as_int, img_as_float, \ img_as_uint, img_as_ubyte from skimage.util.dtype import convert +from skimage._shared.utils import all_warnings dtype_range = {np.uint8: (0, 255), @@ -28,7 +29,9 @@ def test_range(): (img_as_float, np.float64), (img_as_uint, np.uint16), (img_as_ubyte, np.ubyte)]: - y = f(x) + + with all_warnings(): # precision loss + y = f(x) omin, omax = dtype_range[dt] @@ -59,7 +62,8 @@ def test_range_extra_dtypes(): for dtype_in, dt in dtype_pairs: imin, imax = dtype_range_extra[dtype_in] x = np.linspace(imin, imax, 10).astype(dtype_in) - y = convert(x, dt) + with all_warnings(): # sign loss + y = convert(x, dt) omin, omax = dtype_range_extra[dt] yield (_verify_range, "From %s to %s" % (np.dtype(dtype_in), np.dtype(dt)), diff --git a/skimage/viewer/tests/__init__.py b/skimage/viewer/tests/__init__.py new file mode 100644 index 00000000..0922ce59 --- /dev/null +++ b/skimage/viewer/tests/__init__.py @@ -0,0 +1,2 @@ +import warnings +warnings.simplefilter('error') diff --git a/skimage/viewer/tests/test_plugins.py b/skimage/viewer/tests/test_plugins.py index 6823635a..6ad180fb 100644 --- a/skimage/viewer/tests/test_plugins.py +++ b/skimage/viewer/tests/test_plugins.py @@ -12,6 +12,7 @@ from skimage.viewer.plugins import ( PlotPlugin) from skimage.viewer.plugins.base import Plugin from skimage.viewer.widgets import Slider +from skimage._shared.utils import all_warnings def setup_line_profile(image, limits='image'): @@ -66,8 +67,9 @@ def test_line_profile_dynamic(): assert_almost_equal(np.std(line), 0.229, 3) assert_almost_equal(np.max(line) - np.min(line), 0.725, 1) - viewer.image = skimage.img_as_float(median(image, - selem=disk(radius=3))) + with all_warnings(): # precision loss + viewer.image = skimage.img_as_float(median(image, + selem=disk(radius=3))) line = lp.get_profiles()[-1][0] assert_almost_equal(np.std(viewer.image), 0.198, 3) @@ -159,7 +161,8 @@ def test_plugin(): viewer = ImageViewer(img) def median_filter(img, radius=3): - return median(img, selem=disk(radius=radius)) + with all_warnings(): # precision loss + return median(img, selem=disk(radius=radius)) plugin = Plugin(image_filter=median_filter) viewer += plugin diff --git a/skimage/viewer/tests/test_viewer.py b/skimage/viewer/tests/test_viewer.py index 99d8e364..553a8be3 100644 --- a/skimage/viewer/tests/test_viewer.py +++ b/skimage/viewer/tests/test_viewer.py @@ -8,6 +8,7 @@ from skimage.filters import sobel from numpy.testing import assert_equal from numpy.testing.decorators import skipif from skimage._shared.version_requirements import is_installed +from skimage._shared.utils import all_warnings @skipif(not viewer_available) @@ -66,7 +67,9 @@ def test_viewer_with_overlay(): ov.color = 3 assert_equal(ov.color, 'yellow') - viewer.save_to_file(filename) + + with all_warnings(): # precision loss + viewer.save_to_file(filename) ov.display_filtered_image(img) assert_equal(ov.overlay, img) ov.overlay = None diff --git a/skimage/viewer/tests/test_widgets.py b/skimage/viewer/tests/test_widgets.py index ba76b7c5..439454f3 100644 --- a/skimage/viewer/tests/test_widgets.py +++ b/skimage/viewer/tests/test_widgets.py @@ -8,6 +8,7 @@ from skimage.viewer.plugins.base import Plugin from skimage.viewer.qt import QtGui, QtCore from numpy.testing import assert_almost_equal, assert_equal from numpy.testing.decorators import skipif +from skimage._shared.utils import all_warnings def get_image_viewer(): @@ -99,10 +100,13 @@ def test_save_buttons(): timer.singleShot(100, QtGui.QApplication.quit) sv.save_to_stack() - sv.save_to_file(filename) + with all_warnings(): # precision loss + sv.save_to_file(filename) img = data.imread(filename) - assert_almost_equal(img, img_as_uint(viewer.image)) + + with all_warnings(): # precision loss + assert_almost_equal(img, img_as_uint(viewer.image)) img = io.pop() assert_almost_equal(img, viewer.image) From 79c648b14c8b3d9c2169f1c277df75fe4bb8fa27 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 20 Dec 2014 20:04:44 -0600 Subject: [PATCH 04/28] Accommodate upcoming changes to RectangleSelector API --- skimage/viewer/canvastools/recttool.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/skimage/viewer/canvastools/recttool.py b/skimage/viewer/canvastools/recttool.py index 8932e180..c2563eea 100644 --- a/skimage/viewer/canvastools/recttool.py +++ b/skimage/viewer/canvastools/recttool.py @@ -41,15 +41,16 @@ class RectangleTool(CanvasToolBase, RectangleSelector): def __init__(self, viewer, on_move=None, on_release=None, on_enter=None, maxdist=10, rect_props=None): - CanvasToolBase.__init__(self, viewer, on_move=on_move, - on_enter=on_enter, on_release=on_release) - + self._rect = None props = dict(edgecolor=None, facecolor='r', alpha=0.15) props.update(rect_props if rect_props is not None else {}) if props['edgecolor'] is None: props['edgecolor'] = props['facecolor'] - RectangleSelector.__init__(self, self.ax, lambda *args: None, + RectangleSelector.__init__(self, viewer.ax, lambda *args: None, rectprops=props) + CanvasToolBase.__init__(self, viewer, on_move=on_move, + on_enter=on_enter, on_release=on_release) + # Events are handled by the viewer try: self.disconnect_events() @@ -87,6 +88,8 @@ class RectangleTool(CanvasToolBase, RectangleSelector): @property def _rect_bbox(self): + if not self._rect: + return 0, 0, 0, 0 x0 = self._rect.get_x() y0 = self._rect.get_y() width = self._rect.get_width() @@ -142,7 +145,10 @@ class RectangleTool(CanvasToolBase, RectangleSelector): if not self.ax.in_axes(event): self.eventpress = None return - RectangleSelector.release(self, event) + if hasattr(RectangleSelector, '_release'): + RectangleSelector._release(self, event) + else: + RectangleSelector.release(self, event) self._extents_on_press = None # Undo hiding of rectangle and redraw. self.set_visible(True) @@ -158,7 +164,10 @@ class RectangleTool(CanvasToolBase, RectangleSelector): self.set_visible(False) self.redraw() self.set_visible(True) - RectangleSelector.press(self, event) + if hasattr(RectangleSelector, '_press'): + RectangleSelector._press(self, event) + else: + RectangleSelector.press(self, event) def _set_active_handle(self, event): """Set active handle based on the location of the mouse event""" From 2756358f3c7ec5d61c0bdd680033703fdf7a866d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 20 Dec 2014 20:28:09 -0600 Subject: [PATCH 05/28] Clean up PIL plugin and handle more warnings Use the pil plugin to load data files Fix install_requires string formatting Dead end commit Make all tools executable Remove debug print Suppress PIL resourcewarnings Handle a few more warnings --- .../plot_circular_elliptical_hough_transform.py | 0 doc/gh-pages.py | 0 doc/release/contribs.py | 0 doc/source/coverage_generator.py | 0 doc/source/user_guide/parallelization.txt | 0 setup.py | 2 +- skimage/data/__init__.py | 3 ++- skimage/io/_plugins/pil_plugin.py | 5 +++-- skimage/measure/__init__.py | 0 skimage/measure/_find_contours.py | 0 skimage/measure/tests/test_fit.py | 6 ++++-- skimage/measure/tests/test_regionprops.py | 15 ++++++++++----- skimage/scripts/skivi | 0 skimage/transform/tests/test_warps.py | 7 +++++-- 14 files changed, 25 insertions(+), 13 deletions(-) mode change 100755 => 100644 doc/examples/plot_circular_elliptical_hough_transform.py mode change 100755 => 100644 doc/gh-pages.py mode change 100755 => 100644 doc/release/contribs.py mode change 100755 => 100644 doc/source/coverage_generator.py mode change 100755 => 100644 doc/source/user_guide/parallelization.txt mode change 100755 => 100644 setup.py mode change 100755 => 100644 skimage/measure/__init__.py mode change 100755 => 100644 skimage/measure/_find_contours.py mode change 100755 => 100644 skimage/scripts/skivi diff --git a/doc/examples/plot_circular_elliptical_hough_transform.py b/doc/examples/plot_circular_elliptical_hough_transform.py old mode 100755 new mode 100644 diff --git a/doc/gh-pages.py b/doc/gh-pages.py old mode 100755 new mode 100644 diff --git a/doc/release/contribs.py b/doc/release/contribs.py old mode 100755 new mode 100644 diff --git a/doc/source/coverage_generator.py b/doc/source/coverage_generator.py old mode 100755 new mode 100644 diff --git a/doc/source/user_guide/parallelization.txt b/doc/source/user_guide/parallelization.txt old mode 100755 new mode 100644 diff --git a/setup.py b/setup.py old mode 100755 new mode 100644 index 01b69620..2317c36f --- a/setup.py +++ b/setup.py @@ -149,7 +149,7 @@ if __name__ == "__main__": configuration=configuration, install_requires=[ - "six>=%s" % DEPENDENCIES['six'] + "six>=%s" % '.'.join(str(d) for d in DEPENDENCIES['six']) ], packages=setuptools.find_packages(exclude=['doc']), include_package_data=True, diff --git a/skimage/data/__init__.py b/skimage/data/__init__.py index a6b39468..81514ce9 100644 --- a/skimage/data/__init__.py +++ b/skimage/data/__init__.py @@ -8,7 +8,7 @@ For more images, see import os as _os -from ..io import imread +from ..io import imread, use_plugin from skimage import data_dir @@ -42,6 +42,7 @@ def load(f): img : ndarray Image loaded from skimage.data_dir. """ + use_plugin('pil') return imread(_os.path.join(data_dir, f)) diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index f8414283..f1d74e22 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -7,6 +7,7 @@ from PIL import Image from skimage.util import img_as_ubyte, img_as_uint from skimage.external.tifffile import ( imread as tif_imread, imsave as tif_imsave) +from skimage._shared.utils import all_warnings def imread(fname, dtype=None, img_num=None, **kwargs): @@ -39,7 +40,6 @@ def imread(fname, dtype=None, img_num=None, **kwargs): .. [2] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html """ - print('imread', fname) if hasattr(fname, 'lower') and dtype is None: kwargs.setdefault('key', img_num) if fname.lower().endswith(('.tiff', '.tif')): @@ -54,7 +54,8 @@ def imread(fname, dtype=None, img_num=None, **kwargs): site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" raise ValueError('Could not load "%s"\nPlease see documentation at: %s' % (fname, site)) else: - return pil_to_ndarray(im, dtype=dtype, img_num=img_num) + with all_warnings(): # PIL resource warnings + return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(im, dtype=None, img_num=None): diff --git a/skimage/measure/__init__.py b/skimage/measure/__init__.py old mode 100755 new mode 100644 diff --git a/skimage/measure/_find_contours.py b/skimage/measure/_find_contours.py old mode 100755 new mode 100644 diff --git a/skimage/measure/tests/test_fit.py b/skimage/measure/tests/test_fit.py index 32d9ef22..4305b04e 100644 --- a/skimage/measure/tests/test_fit.py +++ b/skimage/measure/tests/test_fit.py @@ -3,6 +3,7 @@ from numpy.testing import assert_equal, assert_raises, assert_almost_equal from skimage.measure import LineModel, CircleModel, EllipseModel, ransac from skimage.transform import AffineTransform from skimage.measure.fit import _dynamic_max_trials +from skimage._shared.utils import all_warnings def test_line_model_invalid_input(): @@ -180,7 +181,7 @@ def test_ransac_geometric(): model_est, inliers = ransac((src, dst), AffineTransform, 2, 20) # test whether estimated parameters equal original parameters - assert_almost_equal(model0._matrix, model_est._matrix) + assert_almost_equal(model0.params, model_est.params) assert np.all(np.nonzero(inliers == False)[0] == outliers) @@ -255,7 +256,8 @@ def test_deprecated_params_attribute(): model.params = (10, 1) x = np.arange(-10, 10) y = model.predict_y(x) - assert_equal(model.params, model._params) + with all_warnings(): # deprecation + assert_equal(model.params, model._params) if __name__ == "__main__": diff --git a/skimage/measure/tests/test_regionprops.py b/skimage/measure/tests/test_regionprops.py index 934e209e..cb172f43 100644 --- a/skimage/measure/tests/test_regionprops.py +++ b/skimage/measure/tests/test_regionprops.py @@ -4,6 +4,7 @@ import numpy as np import math from skimage.measure._regionprops import regionprops, PROPS, perimeter +from skimage._shared.utils import all_warnings SAMPLE = np.array( @@ -25,7 +26,8 @@ INTENSITY_SAMPLE[1, 9:11] = 2 def test_all_props(): region = regionprops(SAMPLE, INTENSITY_SAMPLE)[0] for prop in PROPS: - assert_equal(region[prop], getattr(region, PROPS[prop])) + with all_warnings(): # deprecation warning + assert_equal(region[prop], getattr(region, PROPS[prop])) def test_dtype(): @@ -125,12 +127,14 @@ def test_equiv_diameter(): def test_euler_number(): - en = regionprops(SAMPLE)[0].euler_number + with all_warnings(): # deprecation warning + en = regionprops(SAMPLE)[0].euler_number assert en == 0 SAMPLE_mod = SAMPLE.copy() SAMPLE_mod[7, -3] = 0 - en = regionprops(SAMPLE_mod)[0].euler_number + with all_warnings(): # deprecation warning + en = regionprops(SAMPLE_mod)[0].euler_number assert en == -1 @@ -369,8 +373,9 @@ def test_equals(): r2 = regions[0] r3 = regions[1] - assert_equal(r1 == r2, True, "Same regionprops are not equal") - assert_equal(r1 != r3, True, "Different regionprops are equal") + with all_warnings(): # deprecation warning + assert_equal(r1 == r2, True, "Same regionprops are not equal") + assert_equal(r1 != r3, True, "Different regionprops are equal") if __name__ == "__main__": diff --git a/skimage/scripts/skivi b/skimage/scripts/skivi old mode 100755 new mode 100644 diff --git a/skimage/transform/tests/test_warps.py b/skimage/transform/tests/test_warps.py index 09a93d69..b0c58281 100644 --- a/skimage/transform/tests/test_warps.py +++ b/skimage/transform/tests/test_warps.py @@ -10,6 +10,7 @@ from skimage.transform import (warp, warp_coords, rotate, resize, rescale, downscale_local_mean) from skimage import transform as tf, data, img_as_float from skimage.color import rgb2gray +from skimage._shared.utils import all_warnings np.random.seed(0) @@ -196,8 +197,10 @@ def test_swirl(): image = img_as_float(data.checkerboard()) swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'} - swirled = tf.swirl(image, strength=10, **swirl_params) - unswirled = tf.swirl(swirled, strength=-10, **swirl_params) + + with all_warnings(): # deprecation warning + swirled = tf.swirl(image, strength=10, **swirl_params) + unswirled = tf.swirl(swirled, strength=-10, **swirl_params) assert np.mean(np.abs(image - unswirled)) < 0.01 From 542cd4fabe62de11c4df37101218ec34c8a65dda Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sun, 21 Dec 2014 10:52:59 -0600 Subject: [PATCH 06/28] Fix some doctest warnings Fix doctest errors Suppress warnings when importing scipy.ndimage for the first time --- skimage/filters/__init__.py | 5 +++++ skimage/measure/fit.py | 6 +++--- skimage/morphology/watershed.py | 6 +++--- skimage/novice/__init__.py | 2 +- skimage/transform/hough_transform.py | 4 ++-- 5 files changed, 14 insertions(+), 9 deletions(-) diff --git a/skimage/filters/__init__.py b/skimage/filters/__init__.py index 169b4132..d1c23caf 100644 --- a/skimage/filters/__init__.py +++ b/skimage/filters/__init__.py @@ -1,3 +1,8 @@ +from skimage._shared.utils import all_warnings +with all_warnings(): # suppress warnings when importing scipy + import scipy.ndimage as _ndimage + del _ndimage + from .lpi_filter import inverse, wiener, LPIFilter2D from ._gaussian import gaussian_filter from .edges import (sobel, hsobel, vsobel, sobel_h, sobel_v, diff --git a/skimage/measure/fit.py b/skimage/measure/fit.py index 7de90291..b4799a0b 100644 --- a/skimage/measure/fit.py +++ b/skimage/measure/fit.py @@ -619,10 +619,10 @@ def ransac(data, model_class, min_samples, residual_threshold, Estimate ellipse model using RANSAC: - >>> ransac_model, inliers = ransac(data, EllipseModel, 5, 3, max_trials=50) - >>> ransac_model.params + >>> ransac_model, inliers = ransac(data, EllipseModel, 5, 3, max_trials=50) # doctest: +SKIP + >>> ransac_model.params # doctest: +SKIP array([ 20.12762373, 29.73563063, 4.81499637, 10.4743584 , 0.05217117]) - >>> inliers + >>> inliers # doctest: +SKIP array([False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, diff --git a/skimage/morphology/watershed.py b/skimage/morphology/watershed.py index 5e4a9156..783e69b3 100644 --- a/skimage/morphology/watershed.py +++ b/skimage/morphology/watershed.py @@ -119,9 +119,9 @@ def watershed(image, markers, connectivity=None, offset=None, mask=None): >>> from skimage.feature import peak_local_max >>> local_maxi = peak_local_max(distance, labels=image, ... footprint=np.ones((3, 3)), - ... indices=False) - >>> markers = ndimage.label(local_maxi)[0] - >>> labels = watershed(-distance, markers, mask=image) + ... indices=False) # doctest: +SKIP + >>> markers = ndimage.label(local_maxi)[0] # doctest: +SKIP + >>> labels = watershed(-distance, markers, mask=image) # doctest: +SKIP The algorithm works also for 3-D images, and can be used for example to separate overlapping spheres. diff --git a/skimage/novice/__init__.py b/skimage/novice/__init__.py index 029d9a64..68ca6aa7 100644 --- a/skimage/novice/__init__.py +++ b/skimage/novice/__init__.py @@ -42,7 +42,7 @@ True 451 Changing `size` resizes the picture. ->>> picture.size = (45, 30) +>>> picture.size = (45, 30) # doctest: +SKIP You can iterate over pixels, which have RGB values between 0 and 255, and know their location in the picture. diff --git a/skimage/transform/hough_transform.py b/skimage/transform/hough_transform.py index cbb4caa6..167a4da5 100644 --- a/skimage/transform/hough_transform.py +++ b/skimage/transform/hough_transform.py @@ -49,8 +49,8 @@ def hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, >>> rr, cc = line(0, 14, 14, 0) >>> img[cc, rr] = 1 >>> hspace, angles, dists = hough_line(img) - >>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists) - >>> len(angles) + >>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists) # doctest: +SKIP + >>> len(angles) # doctest: +SKIP 2 """ From f72882fbd24252d6e1bd71dfa0765a380e9c6b2d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sun, 21 Dec 2014 14:43:49 -0600 Subject: [PATCH 07/28] Import scipy before turning on warnings --- skimage/_shared/tests/__init__.py | 1 + skimage/color/tests/__init__.py | 1 + skimage/data/tests/__init__.py | 1 + skimage/draw/tests/__init__.py | 1 + skimage/exposure/tests/__init__.py | 1 + skimage/feature/tests/__init__.py | 1 + skimage/filters/__init__.py | 5 ----- skimage/filters/rank/tests/__init__.py | 1 + skimage/filters/tests/__init__.py | 1 + skimage/graph/tests/__init__.py | 1 + skimage/io/tests/__init__.py | 1 + skimage/morphology/tests/__init__.py | 1 + skimage/novice/tests/__init__.py | 1 + skimage/restoration/tests/__init__.py | 1 + skimage/segmentation/tests/__init__.py | 1 + skimage/transform/tests/__init__.py | 1 + skimage/util/tests/__init__.py | 1 + skimage/viewer/tests/__init__.py | 1 + 18 files changed, 17 insertions(+), 5 deletions(-) diff --git a/skimage/_shared/tests/__init__.py b/skimage/_shared/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/_shared/tests/__init__.py +++ b/skimage/_shared/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/color/tests/__init__.py b/skimage/color/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/color/tests/__init__.py +++ b/skimage/color/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/data/tests/__init__.py b/skimage/data/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/data/tests/__init__.py +++ b/skimage/data/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/draw/tests/__init__.py b/skimage/draw/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/draw/tests/__init__.py +++ b/skimage/draw/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/exposure/tests/__init__.py b/skimage/exposure/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/exposure/tests/__init__.py +++ b/skimage/exposure/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/feature/tests/__init__.py b/skimage/feature/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/feature/tests/__init__.py +++ b/skimage/feature/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/filters/__init__.py b/skimage/filters/__init__.py index d1c23caf..169b4132 100644 --- a/skimage/filters/__init__.py +++ b/skimage/filters/__init__.py @@ -1,8 +1,3 @@ -from skimage._shared.utils import all_warnings -with all_warnings(): # suppress warnings when importing scipy - import scipy.ndimage as _ndimage - del _ndimage - from .lpi_filter import inverse, wiener, LPIFilter2D from ._gaussian import gaussian_filter from .edges import (sobel, hsobel, vsobel, sobel_h, sobel_v, diff --git a/skimage/filters/rank/tests/__init__.py b/skimage/filters/rank/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/filters/rank/tests/__init__.py +++ b/skimage/filters/rank/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/filters/tests/__init__.py b/skimage/filters/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/filters/tests/__init__.py +++ b/skimage/filters/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/graph/tests/__init__.py b/skimage/graph/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/graph/tests/__init__.py +++ b/skimage/graph/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/io/tests/__init__.py b/skimage/io/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/io/tests/__init__.py +++ b/skimage/io/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/morphology/tests/__init__.py b/skimage/morphology/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/morphology/tests/__init__.py +++ b/skimage/morphology/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/novice/tests/__init__.py b/skimage/novice/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/novice/tests/__init__.py +++ b/skimage/novice/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/restoration/tests/__init__.py b/skimage/restoration/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/restoration/tests/__init__.py +++ b/skimage/restoration/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/segmentation/tests/__init__.py b/skimage/segmentation/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/segmentation/tests/__init__.py +++ b/skimage/segmentation/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/transform/tests/__init__.py b/skimage/transform/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/transform/tests/__init__.py +++ b/skimage/transform/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/util/tests/__init__.py b/skimage/util/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/util/tests/__init__.py +++ b/skimage/util/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') diff --git a/skimage/viewer/tests/__init__.py b/skimage/viewer/tests/__init__.py index 0922ce59..9b8945a5 100644 --- a/skimage/viewer/tests/__init__.py +++ b/skimage/viewer/tests/__init__.py @@ -1,2 +1,3 @@ import warnings +from scipy import ndimage, special, optimize warnings.simplefilter('error') From 4680f304667882fe0061d79b35e2d2052f80e1e9 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sun, 21 Dec 2014 15:43:23 -0600 Subject: [PATCH 08/28] Add a test setup helper function Add a function to set up a skimage test Switch to new test helper function Import local packages that raise warnings in test setup function More fixes to doctests Fix regionprops doc test Try and fix the test_rank failure. Remove no longer needed RectangleSelector shim Skip more doctests in _regionprops Try importing another scipy subpackage --- skimage/_shared/testing.py | 7 +++++++ skimage/_shared/tests/__init__.py | 5 ++--- skimage/color/tests/__init__.py | 5 ++--- skimage/data/tests/__init__.py | 5 ++--- skimage/draw/tests/__init__.py | 5 ++--- skimage/exposure/tests/__init__.py | 5 ++--- skimage/feature/tests/__init__.py | 5 ++--- skimage/filters/rank/tests/__init__.py | 5 ++--- skimage/filters/tests/__init__.py | 5 ++--- skimage/filters/thresholding.py | 6 +++--- skimage/graph/tests/__init__.py | 5 ++--- skimage/io/_io.py | 2 +- skimage/io/tests/__init__.py | 5 ++--- skimage/measure/_ccomp.pyx | 6 +++--- skimage/measure/_regionprops.py | 8 ++++---- skimage/measure/tests/test_regionprops.py | 5 +++-- skimage/morphology/tests/__init__.py | 5 ++--- skimage/novice/tests/__init__.py | 5 ++--- skimage/restoration/tests/__init__.py | 5 ++--- skimage/segmentation/tests/__init__.py | 5 ++--- skimage/transform/tests/__init__.py | 5 ++--- skimage/util/tests/__init__.py | 5 ++--- skimage/viewer/canvastools/recttool.py | 10 ++-------- skimage/viewer/tests/__init__.py | 5 ++--- 24 files changed, 57 insertions(+), 72 deletions(-) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index 1dae36c3..1b653272 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -10,6 +10,7 @@ from skimage import ( from numpy import testing import numpy as np from skimage._shared.utils import all_warnings +import warnings SKIP_RE = re.compile("(\s*>>>.*?)(\s*)#\s*skip\s+if\s+(.*)$") @@ -177,6 +178,12 @@ def mono_check(plugin, fmt='png'): testing.assert_allclose(r5, img5) +def setup_test(): + from scipy import signal, ndimage, special, optimize, linalg + from skimage import filter, viewer + warnings.simplefilter('error') + + if __name__ == '__main__': color_check('pil') mono_check('pil') diff --git a/skimage/_shared/tests/__init__.py b/skimage/_shared/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/_shared/tests/__init__.py +++ b/skimage/_shared/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/color/tests/__init__.py b/skimage/color/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/color/tests/__init__.py +++ b/skimage/color/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/data/tests/__init__.py b/skimage/data/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/data/tests/__init__.py +++ b/skimage/data/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/draw/tests/__init__.py b/skimage/draw/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/draw/tests/__init__.py +++ b/skimage/draw/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/exposure/tests/__init__.py b/skimage/exposure/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/exposure/tests/__init__.py +++ b/skimage/exposure/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/feature/tests/__init__.py b/skimage/feature/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/feature/tests/__init__.py +++ b/skimage/feature/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/filters/rank/tests/__init__.py b/skimage/filters/rank/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/filters/rank/tests/__init__.py +++ b/skimage/filters/rank/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/filters/tests/__init__.py b/skimage/filters/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/filters/tests/__init__.py +++ b/skimage/filters/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/filters/thresholding.py b/skimage/filters/thresholding.py index 76a725a7..c95e56d2 100644 --- a/skimage/filters/thresholding.py +++ b/skimage/filters/thresholding.py @@ -121,7 +121,7 @@ def threshold_otsu(image, nbins=256): >>> thresh = threshold_otsu(image) >>> binary = image <= thresh """ - hist, bin_centers = histogram(image.flatten(), nbins) + hist, bin_centers = histogram(image.ravel(), nbins) hist = hist.astype(float) # class probabilities for all possible thresholds @@ -176,7 +176,7 @@ def threshold_yen(image, nbins=256): >>> thresh = threshold_yen(image) >>> binary = image <= thresh """ - hist, bin_centers = histogram(image.flatten(), nbins) + hist, bin_centers = histogram(image.ravel(), nbins) # On blank images (e.g. filled with 0) with int dtype, `histogram()` # returns `bin_centers` containing only one value. Speed up with it. if bin_centers.size == 1: @@ -246,7 +246,7 @@ def threshold_isodata(image, nbins=256, return_all=False): >>> binary = image > thresh """ - hist, bin_centers = histogram(image.flatten(), nbins) + hist, bin_centers = histogram(image.ravel(), nbins) # image only contains one unique value if len(bin_centers) == 1: diff --git a/skimage/graph/tests/__init__.py b/skimage/graph/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/graph/tests/__init__.py +++ b/skimage/graph/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/io/_io.py b/skimage/io/_io.py index 06da7adb..1ebb3d59 100644 --- a/skimage/io/_io.py +++ b/skimage/io/_io.py @@ -193,7 +193,7 @@ def show(): >>> import skimage.io as io >>> for i in range(4): - ... io.imshow(np.random.rand(50, 50)) + ... io.imshow(np.random.rand(50, 50)) # doctest: +SKIP >>> io.show() # doctest: +SKIP ''' diff --git a/skimage/io/tests/__init__.py b/skimage/io/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/io/tests/__init__.py +++ b/skimage/io/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/measure/_ccomp.pyx b/skimage/measure/_ccomp.pyx index 66c7f75f..a73815e5 100644 --- a/skimage/measure/_ccomp.pyx +++ b/skimage/measure/_ccomp.pyx @@ -416,12 +416,12 @@ def label(input, neighbors=None, background=None, return_num=False, [0 1 0] [0 0 1]] >>> from skimage.measure import label - >>> print(label(x, neighbors=4)) + >>> print(label(x, neighbors=4)) # doctest: +SKIP [[0 1 1] [2 3 1] [2 2 4]] - >>> print(label(x, neighbors=8)) + >>> print(label(x, neighbors=8)) # doctest: +SKIP [[0 1 1] [1 0 1] [1 1 0]] @@ -430,7 +430,7 @@ def label(input, neighbors=None, background=None, return_num=False, ... [1, 1, 5], ... [0, 0, 0]]) - >>> print(label(x, background=0)) + >>> print(label(x, background=0)) # doctest: +SKIP [[ 0 -1 -1] [ 0 0 1] [-1 -1 -1]] diff --git a/skimage/measure/_regionprops.py b/skimage/measure/_regionprops.py index 070b49a4..2ecbf67f 100644 --- a/skimage/measure/_regionprops.py +++ b/skimage/measure/_regionprops.py @@ -473,11 +473,11 @@ def regionprops(label_image, intensity_image=None, cache=True): >>> from skimage import data, util >>> from skimage.morphology import label >>> img = util.img_as_ubyte(data.coins()) > 110 - >>> label_img = label(img) - >>> props = regionprops(label_img) - >>> props[0].centroid # centroid of first labeled object + >>> label_img = label(img) # doctest: +SKIP + >>> props = regionprops(label_img) # doctest: +SKIP + >>> props[0].centroid # doctest: +SKIP centroid of first labeled object (22.729879860483141, 81.912285234465827) - >>> props[0]['centroid'] # centroid of first labeled object + >>> props[0]['centroid'] # doctest: +SKIP centroid of first labeled object (22.729879860483141, 81.912285234465827) """ diff --git a/skimage/measure/tests/test_regionprops.py b/skimage/measure/tests/test_regionprops.py index cb172f43..830489d1 100644 --- a/skimage/measure/tests/test_regionprops.py +++ b/skimage/measure/tests/test_regionprops.py @@ -33,8 +33,9 @@ def test_all_props(): def test_dtype(): regionprops(np.zeros((10, 10), dtype=np.int)) regionprops(np.zeros((10, 10), dtype=np.uint)) - assert_raises((TypeError, RuntimeError), regionprops, - np.zeros((10, 10), dtype=np.double)) + with all_warnings(): # deprecation on dtype + assert_raises((TypeError, RuntimeError), regionprops, + np.zeros((10, 10), dtype=np.double)) def test_ndim(): diff --git a/skimage/morphology/tests/__init__.py b/skimage/morphology/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/morphology/tests/__init__.py +++ b/skimage/morphology/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/novice/tests/__init__.py b/skimage/novice/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/novice/tests/__init__.py +++ b/skimage/novice/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/restoration/tests/__init__.py b/skimage/restoration/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/restoration/tests/__init__.py +++ b/skimage/restoration/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/segmentation/tests/__init__.py b/skimage/segmentation/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/segmentation/tests/__init__.py +++ b/skimage/segmentation/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/transform/tests/__init__.py b/skimage/transform/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/transform/tests/__init__.py +++ b/skimage/transform/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/util/tests/__init__.py b/skimage/util/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/util/tests/__init__.py +++ b/skimage/util/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/viewer/canvastools/recttool.py b/skimage/viewer/canvastools/recttool.py index c2563eea..4acccf8a 100644 --- a/skimage/viewer/canvastools/recttool.py +++ b/skimage/viewer/canvastools/recttool.py @@ -145,10 +145,7 @@ class RectangleTool(CanvasToolBase, RectangleSelector): if not self.ax.in_axes(event): self.eventpress = None return - if hasattr(RectangleSelector, '_release'): - RectangleSelector._release(self, event) - else: - RectangleSelector.release(self, event) + RectangleSelector.release(self, event) self._extents_on_press = None # Undo hiding of rectangle and redraw. self.set_visible(True) @@ -164,10 +161,7 @@ class RectangleTool(CanvasToolBase, RectangleSelector): self.set_visible(False) self.redraw() self.set_visible(True) - if hasattr(RectangleSelector, '_press'): - RectangleSelector._press(self, event) - else: - RectangleSelector.press(self, event) + RectangleSelector.press(self, event) def _set_active_handle(self, event): """Set active handle based on the location of the mouse event""" diff --git a/skimage/viewer/tests/__init__.py b/skimage/viewer/tests/__init__.py index 9b8945a5..c098c64d 100644 --- a/skimage/viewer/tests/__init__.py +++ b/skimage/viewer/tests/__init__.py @@ -1,3 +1,2 @@ -import warnings -from scipy import ndimage, special, optimize -warnings.simplefilter('error') +from skimage._shared.testing import setup_test +setup_test() From 6db92d387b510787bc4be256d6dd598b76eec886 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sun, 21 Dec 2014 19:41:16 -0600 Subject: [PATCH 09/28] More doctest and pil_plugin fixes Fix Python2 imread in pil_plugin. Load from data Use all_warnings when importing the other packages More fixes for regionprops doctest --- skimage/_shared/testing.py | 6 ++++-- skimage/io/_plugins/pil_plugin.py | 7 +++++-- skimage/measure/_regionprops.py | 6 ++++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index 1b653272..7712c0ae 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -179,9 +179,11 @@ def mono_check(plugin, fmt='png'): def setup_test(): - from scipy import signal, ndimage, special, optimize, linalg - from skimage import filter, viewer warnings.simplefilter('error') + with all_warnings(): + from scipy import signal, ndimage, special, optimize, linalg + from skimage import filter, viewer, data + data.moon() if __name__ == '__main__': diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index f1d74e22..05b8b9cb 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -180,7 +180,10 @@ def ndarray_to_pil(arr, format_str=None): if arr.ndim == 2: im = Image.new(mode_base, arr.T.shape) - im.frombytes(arr.tobytes(), 'raw', mode) + try: + im.frombytes(arr.tobytes(), 'raw', mode) + except AttributeError: + im.frombytes(arr.tostring(), 'raw', mode) else: try: @@ -188,7 +191,7 @@ def ndarray_to_pil(arr, format_str=None): arr.tobytes()) except AttributeError: im = Image.frombytes(mode, (arr.shape[1], arr.shape[0]), - arr.tobytes()) + arr.tostring()) return im diff --git a/skimage/measure/_regionprops.py b/skimage/measure/_regionprops.py index 2ecbf67f..cf2bfc41 100644 --- a/skimage/measure/_regionprops.py +++ b/skimage/measure/_regionprops.py @@ -475,9 +475,11 @@ def regionprops(label_image, intensity_image=None, cache=True): >>> img = util.img_as_ubyte(data.coins()) > 110 >>> label_img = label(img) # doctest: +SKIP >>> props = regionprops(label_img) # doctest: +SKIP - >>> props[0].centroid # doctest: +SKIP centroid of first labeled object + >>> # centroid of first labeled object + >>> props[0].centroid # doctest: +SKIP (22.729879860483141, 81.912285234465827) - >>> props[0]['centroid'] # doctest: +SKIP centroid of first labeled object + >>> # centroid of first labeled object + >>> props[0]['centroid'] # doctest: +SKIP (22.729879860483141, 81.912285234465827) """ From 782ba46a4ce84ff6c7ed9e23747cd1d0c2cd060d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 22 Dec 2014 06:36:59 -0600 Subject: [PATCH 10/28] Handle more warnings Punt on the issue of warnings with the minimum build Handle warnings in measure pkg Fix the rank filter test by forcing a random seed in the function Compare as boolean in imread test Import loadmat in test_setup to avoid warning Use a setup method for imread plugin test Revoke unintended changes Fix indentation to appease jni More indentation fixes Fix unintentional comment out --- ...lot_circular_elliptical_hough_transform.py | 0 doc/gh-pages.py | 0 doc/release/contribs.py | 0 doc/source/coverage_generator.py | 0 doc/source/user_guide/parallelization.txt | 0 setup.py | 2 +- skimage/_shared/testing.py | 8 ++++-- skimage/filters/rank/tests/test_rank.py | 28 +++++++++---------- skimage/io/_plugins/pil_plugin.py | 3 +- skimage/io/tests/test_imread.py | 9 ++++-- skimage/measure/__init__.py | 0 skimage/measure/_find_contours.py | 0 skimage/measure/tests/__init__.py | 2 ++ skimage/scripts/skivi | 0 14 files changed, 29 insertions(+), 23 deletions(-) mode change 100644 => 100755 doc/examples/plot_circular_elliptical_hough_transform.py mode change 100644 => 100755 doc/gh-pages.py mode change 100644 => 100755 doc/release/contribs.py mode change 100644 => 100755 doc/source/coverage_generator.py mode change 100644 => 100755 doc/source/user_guide/parallelization.txt mode change 100644 => 100755 setup.py mode change 100644 => 100755 skimage/measure/__init__.py mode change 100644 => 100755 skimage/measure/_find_contours.py create mode 100644 skimage/measure/tests/__init__.py mode change 100644 => 100755 skimage/scripts/skivi diff --git a/doc/examples/plot_circular_elliptical_hough_transform.py b/doc/examples/plot_circular_elliptical_hough_transform.py old mode 100644 new mode 100755 diff --git a/doc/gh-pages.py b/doc/gh-pages.py old mode 100644 new mode 100755 diff --git a/doc/release/contribs.py b/doc/release/contribs.py old mode 100644 new mode 100755 diff --git a/doc/source/coverage_generator.py b/doc/source/coverage_generator.py old mode 100644 new mode 100755 diff --git a/doc/source/user_guide/parallelization.txt b/doc/source/user_guide/parallelization.txt old mode 100644 new mode 100755 diff --git a/setup.py b/setup.py old mode 100644 new mode 100755 index 2317c36f..01b69620 --- a/setup.py +++ b/setup.py @@ -149,7 +149,7 @@ if __name__ == "__main__": configuration=configuration, install_requires=[ - "six>=%s" % '.'.join(str(d) for d in DEPENDENCIES['six']) + "six>=%s" % DEPENDENCIES['six'] ], packages=setuptools.find_packages(exclude=['doc']), include_package_data=True, diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index 7712c0ae..44ffb62d 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -179,12 +179,14 @@ def mono_check(plugin, fmt='png'): def setup_test(): - warnings.simplefilter('error') - with all_warnings(): + warnings.simplefilter('error') + with all_warnings(): from scipy import signal, ndimage, special, optimize, linalg + from scipy.io import loadmat from skimage import filter, viewer, data data.moon() - + if os.environ.get('TRAVIS_PYTHON_VERSION', None) == '2.7': + warnings.simplefilter('default') if __name__ == '__main__': color_check('pil') diff --git a/skimage/filters/rank/tests/test_rank.py b/skimage/filters/rank/tests/test_rank.py index f2d91ff0..d245d3f4 100644 --- a/skimage/filters/rank/tests/test_rank.py +++ b/skimage/filters/rank/tests/test_rank.py @@ -13,12 +13,12 @@ np.random.seed(0) def test_all(): - - with all_warnings(): # precision loss - check_all() + with all_warnings(): # precision loss + check_all() def check_all(): + np.random.seed(0) image = np.random.rand(25, 25) selem = morphology.disk(1) refs = np.load(os.path.join(skimage.data_dir, "rank_filter_tests.npz")) @@ -159,7 +159,7 @@ def test_bitdepth(): for i in range(5): image = np.ones((100, 100), dtype=np.uint16) * 255 * 2 ** i with all_warnings(): # bit depth - rank.mean_percentile(image=image, selem=elem, mask=mask, + rank.mean_percentile(image=image, selem=elem, mask=mask, out=out, shift_x=0, shift_y=0, p0=.1, p1=.9) @@ -270,7 +270,7 @@ def test_compare_ubyte_vs_float(): func = getattr(rank, method) out_u = func(image_uint, disk(3)) with all_warnings(): # precision loss - out_f = func(image_float, disk(3)) + out_f = func(image_float, disk(3)) assert_equal(out_u, out_f) @@ -283,9 +283,9 @@ def test_compare_8bit_unsigned_vs_signed(): image[image > 127] = 0 image_s = image.astype(np.int8) with all_warnings(): # precision loss - image_u = img_as_ubyte(image_s) + image_u = img_as_ubyte(image_s) - assert_equal(image_u, img_as_ubyte(image_s)) + assert_equal(image_u, img_as_ubyte(image_s)) methods = ['autolevel', 'bottomhat', 'equalize', 'gradient', 'maximum', 'mean', 'subtract_mean', 'median', 'minimum', 'modal', @@ -295,8 +295,8 @@ def test_compare_8bit_unsigned_vs_signed(): func = getattr(rank, method) with all_warnings(): # sign loss - out_u = func(image_u, disk(3)) - out_s = func(image_s, disk(3)) + out_u = func(image_u, disk(3)) + out_s = func(image_s, disk(3)) assert_equal(out_u, out_s) @@ -487,11 +487,11 @@ def test_entropy(): data = np.tile( np.reshape(np.arange(4096), (64, 64)), (2, 2)).astype(np.uint16) with all_warnings(): # bitdepth - assert(np.max(rank.entropy(data, selem)) == 12) + assert(np.max(rank.entropy(data, selem)) == 12) # make sure output is of dtype double with all_warnings(): # bitdepth - out = rank.entropy(data, np.ones((16, 16), dtype=np.uint8)) + out = rank.entropy(data, np.ones((16, 16), dtype=np.uint8)) assert out.dtype == np.double @@ -523,9 +523,9 @@ def test_16bit(): value = 2 ** bitdepth - 1 image[10, 10] = value with all_warnings(): # bitdepth - assert rank.minimum(image, selem)[10, 10] == 0 - assert rank.maximum(image, selem)[10, 10] == value - assert rank.mean(image, selem)[10, 10] == int(value / selem.size) + assert rank.minimum(image, selem)[10, 10] == 0 + assert rank.maximum(image, selem)[10, 10] == value + assert rank.mean(image, selem)[10, 10] == int(value / selem.size) def test_bilateral(): diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index 05b8b9cb..3146cbbc 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -48,8 +48,7 @@ def imread(fname, dtype=None, img_num=None, **kwargs): im = Image.open(fname) try: # this will raise an IOError if the file is not readable - #im.getdata()[0] - pass + im.getdata()[0] except IOError: site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" raise ValueError('Could not load "%s"\nPlease see documentation at: %s' % (fname, site)) diff --git a/skimage/io/tests/test_imread.py b/skimage/io/tests/test_imread.py index a2c32b79..759e8c67 100644 --- a/skimage/io/tests/test_imread.py +++ b/skimage/io/tests/test_imread.py @@ -11,13 +11,16 @@ import skimage.io as sio try: import imread as _imread - use_plugin('imread') except ImportError: imread_available = False else: imread_available = True -np.random.seed(0) + +def setup(): + if imread_available: + np.random.seed(0) + use_plugin('imread') def teardown(): @@ -54,7 +57,7 @@ def test_bilevel(): expected[::2] = 1 img = imread(os.path.join(data_dir, 'checker_bilevel.png')) - assert_array_equal(img, expected) + assert_array_equal(img.astype(bool), expected) class TestSave: diff --git a/skimage/measure/__init__.py b/skimage/measure/__init__.py old mode 100644 new mode 100755 diff --git a/skimage/measure/_find_contours.py b/skimage/measure/_find_contours.py old mode 100644 new mode 100755 diff --git a/skimage/measure/tests/__init__.py b/skimage/measure/tests/__init__.py new file mode 100644 index 00000000..c098c64d --- /dev/null +++ b/skimage/measure/tests/__init__.py @@ -0,0 +1,2 @@ +from skimage._shared.testing import setup_test +setup_test() diff --git a/skimage/scripts/skivi b/skimage/scripts/skivi old mode 100644 new mode 100755 From a4e4e57ba509fa3fbfa45bcc22b8a93c0c2de33e Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 23 Dec 2014 07:27:45 -0600 Subject: [PATCH 11/28] Create new expected_warnings helper and some cleanup Add new helper function for expected warnings during test Indentation cleanups and avoid skipping doctests if possible. --- TODO.txt | 2 +- skimage/_shared/_warnings.py | 40 +++++++++++++++++++ skimage/measure/_ccomp.pyx | 4 +- skimage/measure/_regionprops.py | 8 ++-- skimage/morphology/tests/test_ccomp.py | 6 +-- skimage/novice/__init__.py | 2 +- .../segmentation/tests/test_random_walker.py | 4 +- 7 files changed, 53 insertions(+), 13 deletions(-) diff --git a/TODO.txt b/TODO.txt index d6d95586..13823d08 100644 --- a/TODO.txt +++ b/TODO.txt @@ -15,7 +15,7 @@ Version 0.13 Version 0.12 ------------ * Change `label` to mark background as 0, not -1, which is consistent with - SciPy's labelling. + SciPy's labelling. Also remove doctest skip in _ccomp.pyx `label`. * Remove `skimage.morphology.label` from `skimage.morphology.__init__`--it now lives in `skimage.measure.label`. * Remove deprecated `reverse_map` parameter of `skimage.transform.warp` diff --git a/skimage/_shared/_warnings.py b/skimage/_shared/_warnings.py index c4cd0a68..cf9df84a 100644 --- a/skimage/_shared/_warnings.py +++ b/skimage/_shared/_warnings.py @@ -4,6 +4,7 @@ from contextlib import contextmanager import sys import warnings import inspect +import re @contextmanager @@ -61,3 +62,42 @@ def all_warnings(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") yield w + + +@contextmanager +def expected_warnings(matching): + """Context for use in testing to catch known warnings matching regexes + + Parameters + ---------- + matching : list of strings or compiled regexes + Regexes for the desired warning to catch + + + Examples + -------- + >>> from skimage import data, img_as_ubyte, img_as_float + >>> with expected_warnings(['precision loss']): + ... d = img_as_ubyte(img_as_float(data.coins())) + + Notes + ----- + Uses `all_warnings` to ensure all warnings are raised. + Upon exiting, it checks the recorded warnings for the desired matching + string. Raises a warning if the match was not found or an Unexpected + warning is found. + + """ + with all_warnings() as w: + yield w + remaining = matching + for warn in w: + found = False + for match in matching: + if re.search(match, str(warn.message)) is not None: + found = True + remaining.remove(match) + if not found: + raise ValueError('Unexpected warning: %s' % str(warn.message)) + if len(remaining) > 0: + raise ValueError('No warning raised matching: "%s"' % remaining[0]) diff --git a/skimage/measure/_ccomp.pyx b/skimage/measure/_ccomp.pyx index a73815e5..ac75601a 100644 --- a/skimage/measure/_ccomp.pyx +++ b/skimage/measure/_ccomp.pyx @@ -416,12 +416,12 @@ def label(input, neighbors=None, background=None, return_num=False, [0 1 0] [0 0 1]] >>> from skimage.measure import label - >>> print(label(x, neighbors=4)) # doctest: +SKIP + >>> print(label(x, connectivity=1)) [[0 1 1] [2 3 1] [2 2 4]] - >>> print(label(x, neighbors=8)) # doctest: +SKIP + >>> print(label(x, connectivity=2)) [[0 1 1] [1 0 1] [1 1 0]] diff --git a/skimage/measure/_regionprops.py b/skimage/measure/_regionprops.py index cf2bfc41..66a8734f 100644 --- a/skimage/measure/_regionprops.py +++ b/skimage/measure/_regionprops.py @@ -473,13 +473,13 @@ def regionprops(label_image, intensity_image=None, cache=True): >>> from skimage import data, util >>> from skimage.morphology import label >>> img = util.img_as_ubyte(data.coins()) > 110 - >>> label_img = label(img) # doctest: +SKIP - >>> props = regionprops(label_img) # doctest: +SKIP + >>> label_img = label(img, connectivity=img.ndim) + >>> props = regionprops(label_img) >>> # centroid of first labeled object - >>> props[0].centroid # doctest: +SKIP + >>> props[0].centroid (22.729879860483141, 81.912285234465827) >>> # centroid of first labeled object - >>> props[0]['centroid'] # doctest: +SKIP + >>> props[0]['centroid'] (22.729879860483141, 81.912285234465827) """ diff --git a/skimage/morphology/tests/test_ccomp.py b/skimage/morphology/tests/test_ccomp.py index 1a321a08..569b0e38 100644 --- a/skimage/morphology/tests/test_ccomp.py +++ b/skimage/morphology/tests/test_ccomp.py @@ -12,9 +12,9 @@ BG = -1 def label(*args, **kwargs): - """Wrap the label function to avoid deprecation warning""" - with all_warnings(): - return _label(*args, **kwargs) + """Wrap the label function to avoid deprecation warning""" + with all_warnings(): + return _label(*args, **kwargs) class TestConnectedComponents: diff --git a/skimage/novice/__init__.py b/skimage/novice/__init__.py index 68ca6aa7..029d9a64 100644 --- a/skimage/novice/__init__.py +++ b/skimage/novice/__init__.py @@ -42,7 +42,7 @@ True 451 Changing `size` resizes the picture. ->>> picture.size = (45, 30) # doctest: +SKIP +>>> picture.size = (45, 30) You can iterate over pixels, which have RGB values between 0 and 255, and know their location in the picture. diff --git a/skimage/segmentation/tests/test_random_walker.py b/skimage/segmentation/tests/test_random_walker.py index 0bb5b8d8..ed68cb0f 100644 --- a/skimage/segmentation/tests/test_random_walker.py +++ b/skimage/segmentation/tests/test_random_walker.py @@ -81,7 +81,7 @@ def test_2d_cg(): assert data.shape == labels.shape with all_warnings(): # cg mode full_prob = random_walker(data, labels, beta=90, mode='cg', - return_full_prob=True) + return_full_prob=True) assert (full_prob[1, 25:45, 40:60] >= full_prob[0, 25:45, 40:60]).all() assert data.shape == labels.shape @@ -245,7 +245,7 @@ def test_spacing_1(): # Test with `spacing` kwarg # First, anisotropic along Y - with all_warnings(): # using cd mode + with all_warnings(): # using cg mode labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg', spacing=(1., 2., 1.)) assert (labels_aniso[13:17, 26:34, 13:17] == 2).all() From 1b905d4cefc68aba03aa511557b9700742c61720 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 23 Dec 2014 10:21:06 -0600 Subject: [PATCH 12/28] More cleanup and updating of tests Clean up setup_test and add a teardown_test method Implement new setup/teardown in novice tests Fix warning handling in pil_plugin Update rank tests --- skimage/_shared/testing.py | 29 ++++++++++++++++------- skimage/filters/rank/tests/__init__.py | 11 +++++++-- skimage/filters/rank/tests/test_rank.py | 31 ++++++++++++++----------- skimage/filters/tests/__init__.py | 11 +++++++-- skimage/io/_plugins/pil_plugin.py | 8 +++---- skimage/novice/tests/__init__.py | 11 +++++++-- 6 files changed, 69 insertions(+), 32 deletions(-) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index 44ffb62d..fd109462 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -179,14 +179,27 @@ def mono_check(plugin, fmt='png'): def setup_test(): - warnings.simplefilter('error') - with all_warnings(): - from scipy import signal, ndimage, special, optimize, linalg - from scipy.io import loadmat - from skimage import filter, viewer, data - data.moon() - if os.environ.get('TRAVIS_PYTHON_VERSION', None) == '2.7': - warnings.simplefilter('default') + """Default package level setup routine for skimage tests. + + Import packages known to raise errors, and then + force warnings to raise errors. + """ + warnings.simplefilter('default') + from scipy import signal, ndimage, special, optimize, linalg + from scipy.io import loadmat + from skimage import filter, viewer, data + # trigger PIL warnings + data.moon() + warnings.simplefilter('error') + + +def teardown_test(): + """Default package level teardown routine for skimage tests. + + Restore warnings to default behavior + """ + warnings.simplefilter('default') + if __name__ == '__main__': color_check('pil') diff --git a/skimage/filters/rank/tests/__init__.py b/skimage/filters/rank/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/filters/rank/tests/__init__.py +++ b/skimage/filters/rank/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/filters/rank/tests/test_rank.py b/skimage/filters/rank/tests/test_rank.py index d245d3f4..5cf5a091 100644 --- a/skimage/filters/rank/tests/test_rank.py +++ b/skimage/filters/rank/tests/test_rank.py @@ -7,18 +7,15 @@ from skimage import img_as_ubyte, img_as_float from skimage import data, util, morphology from skimage.morphology import cmorph, disk from skimage.filters import rank -from skimage._shared.utils import all_warnings - -np.random.seed(0) +from skimage._shared._warnings import expected_warnings def test_all(): - with all_warnings(): # precision loss + with expected_warnings(['precision loss', 'non-integer']): check_all() def check_all(): - np.random.seed(0) image = np.random.rand(25, 25) selem = morphology.disk(1) refs = np.load(os.path.join(skimage.data_dir, "rank_filter_tests.npz")) @@ -158,7 +155,11 @@ def test_bitdepth(): for i in range(5): image = np.ones((100, 100), dtype=np.uint16) * 255 * 2 ** i - with all_warnings(): # bit depth + if i > 3: + expected = ["Bitdepth of"] + else: + expected = [] + with expected_warnings(expected): rank.mean_percentile(image=image, selem=elem, mask=mask, out=out, shift_x=0, shift_y=0, p0=.1, p1=.9) @@ -269,7 +270,7 @@ def test_compare_ubyte_vs_float(): for method in methods: func = getattr(rank, method) out_u = func(image_uint, disk(3)) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): out_f = func(image_float, disk(3)) assert_equal(out_u, out_f) @@ -282,9 +283,8 @@ def test_compare_8bit_unsigned_vs_signed(): image = img_as_ubyte(data.camera()) image[image > 127] = 0 image_s = image.astype(np.int8) - with all_warnings(): # precision loss + with expected_warnings(['sign loss', 'precision loss']): image_u = img_as_ubyte(image_s) - assert_equal(image_u, img_as_ubyte(image_s)) methods = ['autolevel', 'bottomhat', 'equalize', 'gradient', 'maximum', @@ -294,7 +294,7 @@ def test_compare_8bit_unsigned_vs_signed(): for method in methods: func = getattr(rank, method) - with all_warnings(): # sign loss + with expected_warnings(['sign loss', 'precision loss']): out_u = func(image_u, disk(3)) out_s = func(image_s, disk(3)) assert_equal(out_u, out_s) @@ -486,11 +486,11 @@ def test_entropy(): selem = np.ones((64, 64), dtype=np.uint8) data = np.tile( np.reshape(np.arange(4096), (64, 64)), (2, 2)).astype(np.uint16) - with all_warnings(): # bitdepth + with expected_warnings(['Bitdepth of 11']): assert(np.max(rank.entropy(data, selem)) == 12) # make sure output is of dtype double - with all_warnings(): # bitdepth + with expected_warnings(['Bitdepth of 11']): out = rank.entropy(data, np.ones((16, 16), dtype=np.uint8)) assert out.dtype == np.double @@ -522,12 +522,15 @@ def test_16bit(): for bitdepth in range(17): value = 2 ** bitdepth - 1 image[10, 10] = value - with all_warnings(): # bitdepth + if bitdepth > 11: + expected = ['Bitdepth of %s' % (bitdepth - 1)] + else: + expected = [] + with expected_warnings(expected): assert rank.minimum(image, selem)[10, 10] == 0 assert rank.maximum(image, selem)[10, 10] == value assert rank.mean(image, selem)[10, 10] == int(value / selem.size) - def test_bilateral(): image = np.zeros((21, 21), dtype=np.uint16) selem = np.ones((3, 3), dtype=np.uint8) diff --git a/skimage/filters/tests/__init__.py b/skimage/filters/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/filters/tests/__init__.py +++ b/skimage/filters/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index 3146cbbc..cdaea687 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -7,7 +7,7 @@ from PIL import Image from skimage.util import img_as_ubyte, img_as_uint from skimage.external.tifffile import ( imread as tif_imread, imsave as tif_imsave) -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings def imread(fname, dtype=None, img_num=None, **kwargs): @@ -48,13 +48,13 @@ def imread(fname, dtype=None, img_num=None, **kwargs): im = Image.open(fname) try: # this will raise an IOError if the file is not readable - im.getdata()[0] + with expected_warnings(['unclosed file']): + im.getdata()[0] except IOError: site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" raise ValueError('Could not load "%s"\nPlease see documentation at: %s' % (fname, site)) else: - with all_warnings(): # PIL resource warnings - return pil_to_ndarray(im, dtype=dtype, img_num=img_num) + return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(im, dtype=None, img_num=None): diff --git a/skimage/novice/tests/__init__.py b/skimage/novice/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/novice/tests/__init__.py +++ b/skimage/novice/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() From 01ca1d17c84ec39d1de923dcf7a8e74bef50d7f9 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 23 Dec 2014 10:59:38 -0600 Subject: [PATCH 13/28] Add a random seed to the setup --- skimage/_shared/testing.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index fd109462..6b09a7bd 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -182,7 +182,8 @@ def setup_test(): """Default package level setup routine for skimage tests. Import packages known to raise errors, and then - force warnings to raise errors. + force warnings to raise errors. + Set a random seed """ warnings.simplefilter('default') from scipy import signal, ndimage, special, optimize, linalg @@ -190,6 +191,7 @@ def setup_test(): from skimage import filter, viewer, data # trigger PIL warnings data.moon() + np.random.seed(0) warnings.simplefilter('error') From c0a0490eede50c939512780ba7c8b0bb0aa27a5c Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 23 Dec 2014 10:59:47 -0600 Subject: [PATCH 14/28] Fix handling of multiple warnings and update tests Fix handling of multiple warnings Update all test __init__ files Update segmentation pkg Update the color pkg Update the exposure pkg Update the filters pkg Update the io pkg Update the measure pkg Update morphology package Restructure test setup function Add expected_warnings to __all__ Update restoration pkg. Remove explicit filter check since it is done elsewhere Fix the image test helpers Update the transform pkg Fix util pkg Update viewer pkg --- skimage/_shared/_warnings.py | 10 +++-- skimage/_shared/testing.py | 24 +++++------ skimage/_shared/tests/__init__.py | 11 ++++- skimage/color/tests/__init__.py | 11 ++++- skimage/color/tests/test_adapt_rgb.py | 4 +- skimage/color/tests/test_colorconv.py | 6 +-- skimage/color/tests/test_colorlabel.py | 9 ++-- skimage/data/tests/__init__.py | 11 ++++- skimage/draw/tests/__init__.py | 11 ++++- skimage/exposure/tests/__init__.py | 11 ++++- skimage/exposure/tests/test_exposure.py | 10 ++--- skimage/feature/tests/__init__.py | 11 ++++- skimage/filters/tests/test_gaussian.py | 4 +- skimage/graph/tests/__init__.py | 11 ++++- skimage/io/_plugins/pil_plugin.py | 4 +- skimage/io/tests/__init__.py | 11 ++++- skimage/io/tests/test_pil.py | 12 +++--- skimage/io/tests/test_plugin_util.py | 16 ++++---- skimage/measure/tests/__init__.py | 11 ++++- skimage/measure/tests/test_fit.py | 4 +- skimage/measure/tests/test_regionprops.py | 16 ++++---- skimage/morphology/tests/__init__.py | 11 ++++- skimage/morphology/tests/test_binary.py | 14 +++---- skimage/morphology/tests/test_ccomp.py | 41 +++++++++---------- skimage/morphology/tests/test_grey.py | 14 +++---- skimage/restoration/tests/__init__.py | 11 ++++- skimage/restoration/tests/test_unwrap.py | 4 +- skimage/segmentation/tests/__init__.py | 11 ++++- .../segmentation/tests/test_random_walker.py | 41 +++++++++++-------- skimage/transform/tests/__init__.py | 11 ++++- skimage/transform/tests/test_geometric.py | 6 +-- .../transform/tests/test_hough_transform.py | 10 ++--- skimage/transform/tests/test_warps.py | 4 +- skimage/util/tests/__init__.py | 11 ++++- skimage/util/tests/test_dtype.py | 22 +++++++--- skimage/util/tests/test_shape.py | 7 ++-- skimage/viewer/tests/__init__.py | 11 ++++- skimage/viewer/tests/test_plugins.py | 6 +-- skimage/viewer/tests/test_viewer.py | 4 +- skimage/viewer/tests/test_widgets.py | 6 +-- 40 files changed, 288 insertions(+), 175 deletions(-) diff --git a/skimage/_shared/_warnings.py b/skimage/_shared/_warnings.py index cf9df84a..fd2c06a0 100644 --- a/skimage/_shared/_warnings.py +++ b/skimage/_shared/_warnings.py @@ -1,4 +1,4 @@ -__all__ = ['all_warnings'] +__all__ = ['all_warnings', 'expected_warnings'] from contextlib import contextmanager import sys @@ -90,14 +90,16 @@ def expected_warnings(matching): """ with all_warnings() as w: yield w - remaining = matching + remaining = [m for m in matching] for warn in w: found = False for match in matching: if re.search(match, str(warn.message)) is not None: found = True - remaining.remove(match) + if match in remaining: + remaining.remove(match) if not found: raise ValueError('Unexpected warning: %s' % str(warn.message)) if len(remaining) > 0: - raise ValueError('No warning raised matching: "%s"' % remaining[0]) + msg = 'No warning raised matching:\n%s' % '\n'.join(remaining) + raise ValueError(msg) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index 6b09a7bd..e5ca2f87 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -9,7 +9,7 @@ from skimage import ( data, io, img_as_uint, img_as_float, img_as_int, img_as_ubyte) from numpy import testing import numpy as np -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings import warnings @@ -117,24 +117,24 @@ def color_check(plugin, fmt='png'): testing.assert_allclose(img2.astype(np.uint8), r2) img3 = img_as_float(img) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): r3 = roundtrip(img3, plugin, fmt) testing.assert_allclose(r3, img) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): img4 = img_as_int(img) if fmt.lower() in (('tif', 'tiff')): img4 -= 100 - with all_warnings(): # sign loss + with expected_warnings(['sign loss']): r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img4) else: - with all_warnings(): # sign loss + with expected_warnings(['sign loss']): r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img_as_ubyte(img4)) img5 = img_as_uint(img) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): r5 = roundtrip(img5, plugin, fmt) testing.assert_allclose(r5, img) @@ -154,22 +154,22 @@ def mono_check(plugin, fmt='png'): testing.assert_allclose(img2.astype(np.uint8), r2) img3 = img_as_float(img) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): r3 = roundtrip(img3, plugin, fmt) if r3.dtype.kind == 'f': testing.assert_allclose(img3, r3) else: testing.assert_allclose(r3, img_as_uint(img)) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): img4 = img_as_int(img) if fmt.lower() in (('tif', 'tiff')): img4 -= 100 - with all_warnings(): # sign loss + with expected_warnings(['sign loss']): r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img4) else: - with all_warnings(): # sign loss + with expected_warnings(['sign loss']): r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img_as_uint(img4)) @@ -188,9 +188,7 @@ def setup_test(): warnings.simplefilter('default') from scipy import signal, ndimage, special, optimize, linalg from scipy.io import loadmat - from skimage import filter, viewer, data - # trigger PIL warnings - data.moon() + from skimage import viewer, filter np.random.seed(0) warnings.simplefilter('error') diff --git a/skimage/_shared/tests/__init__.py b/skimage/_shared/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/_shared/tests/__init__.py +++ b/skimage/_shared/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/color/tests/__init__.py b/skimage/color/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/color/tests/__init__.py +++ b/skimage/color/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/color/tests/test_adapt_rgb.py b/skimage/color/tests/test_adapt_rgb.py index f4da0e58..9e97b6b6 100644 --- a/skimage/color/tests/test_adapt_rgb.py +++ b/skimage/color/tests/test_adapt_rgb.py @@ -5,7 +5,7 @@ import numpy as np from skimage import img_as_float, img_as_uint from skimage import color, data, filters from skimage.color.adapt_rgb import adapt_rgb, each_channel, hsv_value -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings # Down-sample image for quicker testing. COLOR_IMAGE = data.astronaut()[::5, ::5] @@ -38,7 +38,7 @@ def smooth_hsv(image, sigma): @adapt_rgb(hsv_value) def edges_hsv_uint(image): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): return img_as_uint(filters.sobel(image)) diff --git a/skimage/color/tests/test_colorconv.py b/skimage/color/tests/test_colorconv.py index c61a67b2..094873ae 100644 --- a/skimage/color/tests/test_colorconv.py +++ b/skimage/color/tests/test_colorconv.py @@ -40,12 +40,10 @@ from skimage.color import (rgb2hsv, hsv2rgb, ) from skimage import data_dir -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings import colorsys -np.random.seed(0) - def test_guess_spatial_dimensions(): im1 = np.zeros((5, 5)) @@ -157,7 +155,7 @@ class TestColorconv(TestCase): # RGB<->HED roundtrip with ubyte image def test_hed_rgb_roundtrip(self): img_rgb = img_as_ubyte(self.img_rgb) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): new = img_as_ubyte(hed2rgb(rgb2hed(img_rgb))) assert_equal(new, img_rgb) diff --git a/skimage/color/tests/test_colorlabel.py b/skimage/color/tests/test_colorlabel.py index 4daf3a66..277cec5b 100644 --- a/skimage/color/tests/test_colorlabel.py +++ b/skimage/color/tests/test_colorlabel.py @@ -3,7 +3,7 @@ import itertools import numpy as np from numpy import testing from skimage.color.colorlabel import label2rgb -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings from numpy.testing import (assert_array_almost_equal as assert_close, assert_array_equal, assert_warns) @@ -125,10 +125,9 @@ def test_avg(): def test_negative_intensity(): - with all_warnings(): - labels = np.arange(100).reshape(10, 10) - image = -1 * np.ones((10, 10)) - assert_warns(UserWarning, label2rgb, labels, image) + labels = np.arange(100).reshape(10, 10) + image = -1 * np.ones((10, 10)) + assert_warns(UserWarning, label2rgb, labels, image) if __name__ == '__main__': diff --git a/skimage/data/tests/__init__.py b/skimage/data/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/data/tests/__init__.py +++ b/skimage/data/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/draw/tests/__init__.py b/skimage/draw/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/draw/tests/__init__.py +++ b/skimage/draw/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/exposure/tests/__init__.py b/skimage/exposure/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/exposure/tests/__init__.py +++ b/skimage/exposure/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/exposure/tests/test_exposure.py b/skimage/exposure/tests/test_exposure.py index bb047195..5a3d3dba 100644 --- a/skimage/exposure/tests/test_exposure.py +++ b/skimage/exposure/tests/test_exposure.py @@ -11,7 +11,7 @@ from skimage import exposure from skimage.exposure.exposure import intensity_range from skimage.color import rgb2gray from skimage.util.dtype import dtype_range -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings # Test integer histograms @@ -53,7 +53,7 @@ def test_equalize_uint8_approx(): def test_equalize_ubyte(): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): img = skimage.img_as_ubyte(test_img) img_eq = exposure.equalize_hist(img) @@ -211,7 +211,7 @@ def test_adapthist_grayscale(): img = skimage.img_as_float(data.astronaut()) img = rgb2gray(img) img = np.dstack((img, img, img)) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): adapted = exposure.equalize_adapthist(img, 10, 9, clip_limit=0.01, nbins=128) assert_almost_equal = np.testing.assert_almost_equal @@ -229,7 +229,7 @@ def test_adapthist_color(): warnings.simplefilter('always') hist, bin_centers = exposure.histogram(img) assert len(w) > 0 - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): adapted = exposure.equalize_adapthist(img, clip_limit=0.01) assert_almost_equal = np.testing.assert_almost_equal @@ -248,7 +248,7 @@ def test_adapthist_alpha(): img = skimage.img_as_float(data.astronaut()) alpha = np.ones((img.shape[0], img.shape[1]), dtype=float) img = np.dstack((img, alpha)) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): adapted = exposure.equalize_adapthist(img) assert adapted.shape != img.shape img = img[:, :, :3] diff --git a/skimage/feature/tests/__init__.py b/skimage/feature/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/feature/tests/__init__.py +++ b/skimage/feature/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/filters/tests/test_gaussian.py b/skimage/filters/tests/test_gaussian.py index 01e1c12e..c88ee1f8 100644 --- a/skimage/filters/tests/test_gaussian.py +++ b/skimage/filters/tests/test_gaussian.py @@ -1,6 +1,6 @@ import numpy as np from skimage.filters._gaussian import gaussian_filter -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings def test_null_sigma(): @@ -26,7 +26,7 @@ def test_multichannel(): assert np.allclose([a[..., i].mean() for i in range(3)], [gaussian_rgb_a[..., i].mean() for i in range(3)]) # Test multichannel = None - with all_warnings(): # multichannel + with expected_warnings(['multichannel']): gaussian_rgb_a = gaussian_filter(a, sigma=1, mode='reflect') # Check that the mean value is conserved in each channel # (color channels are not mixed together) diff --git a/skimage/graph/tests/__init__.py b/skimage/graph/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/graph/tests/__init__.py +++ b/skimage/graph/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/io/_plugins/pil_plugin.py b/skimage/io/_plugins/pil_plugin.py index cdaea687..9f9118cf 100644 --- a/skimage/io/_plugins/pil_plugin.py +++ b/skimage/io/_plugins/pil_plugin.py @@ -7,7 +7,6 @@ from PIL import Image from skimage.util import img_as_ubyte, img_as_uint from skimage.external.tifffile import ( imread as tif_imread, imsave as tif_imsave) -from skimage._shared._warnings import expected_warnings def imread(fname, dtype=None, img_num=None, **kwargs): @@ -48,8 +47,7 @@ def imread(fname, dtype=None, img_num=None, **kwargs): im = Image.open(fname) try: # this will raise an IOError if the file is not readable - with expected_warnings(['unclosed file']): - im.getdata()[0] + im.getdata()[0] except IOError: site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" raise ValueError('Could not load "%s"\nPlease see documentation at: %s' % (fname, site)) diff --git a/skimage/io/tests/__init__.py b/skimage/io/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/io/tests/__init__.py +++ b/skimage/io/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/io/tests/test_pil.py b/skimage/io/tests/test_pil.py index 832ea13e..2d58e3e9 100644 --- a/skimage/io/tests/test_pil.py +++ b/skimage/io/tests/test_pil.py @@ -10,16 +10,18 @@ from skimage import data_dir from skimage.io import (imread, imsave, use_plugin, reset_plugins, Image as ioImage) from skimage._shared.testing import mono_check, color_check -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings from six import BytesIO from PIL import Image from skimage.io._plugins.pil_plugin import ( pil_to_ndarray, ndarray_to_pil, _palette_is_grayscale) -use_plugin('pil') -np.random.seed(0) + + +def setup(): + use_plugin('pil') def teardown(): @@ -144,7 +146,7 @@ def test_imsave_filelike(): s = BytesIO() # save to file-like object - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): imsave(s, image) # read from file-like object @@ -157,7 +159,7 @@ def test_imsave_filelike(): def test_imexport_imimport(): shape = (2, 2) image = np.zeros(shape) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): pil_image = ndarray_to_pil(image) out = pil_to_ndarray(pil_image) assert out.shape == shape diff --git a/skimage/io/tests/test_plugin_util.py b/skimage/io/tests/test_plugin_util.py index 38e795f3..069622fb 100644 --- a/skimage/io/tests/test_plugin_util.py +++ b/skimage/io/tests/test_plugin_util.py @@ -1,5 +1,5 @@ from skimage.io._plugins.util import prepare_for_display, WindowManager -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings from numpy.testing import * import numpy as np @@ -9,16 +9,16 @@ np.random.seed(0) class TestPrepareForDisplay: def test_basic(self): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): prepare_for_display(np.random.rand(10, 10)) def test_dtype(self): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): x = prepare_for_display(np.random.rand(10, 15)) assert x.dtype == np.dtype(np.uint8) def test_grey(self): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): tmp = np.arange(12, dtype=float).reshape((4, 3)) / 11 x = prepare_for_display(tmp) assert_array_equal(x[..., 0], x[..., 2]) @@ -26,21 +26,21 @@ class TestPrepareForDisplay: assert x[3, 2, 0] == 255 def test_colour(self): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): prepare_for_display(np.random.rand(10, 10, 3)) def test_alpha(self): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): prepare_for_display(np.random.rand(10, 10, 4)) @raises(ValueError) def test_wrong_dimensionality(self): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): prepare_for_display(np.random.rand(10, 10, 1, 1)) @raises(ValueError) def test_wrong_depth(self): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): prepare_for_display(np.random.rand(10, 10, 5)) diff --git a/skimage/measure/tests/__init__.py b/skimage/measure/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/measure/tests/__init__.py +++ b/skimage/measure/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/measure/tests/test_fit.py b/skimage/measure/tests/test_fit.py index 4305b04e..c2a71f71 100644 --- a/skimage/measure/tests/test_fit.py +++ b/skimage/measure/tests/test_fit.py @@ -3,7 +3,7 @@ from numpy.testing import assert_equal, assert_raises, assert_almost_equal from skimage.measure import LineModel, CircleModel, EllipseModel, ransac from skimage.transform import AffineTransform from skimage.measure.fit import _dynamic_max_trials -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings def test_line_model_invalid_input(): @@ -256,7 +256,7 @@ def test_deprecated_params_attribute(): model.params = (10, 1) x = np.arange(-10, 10) y = model.predict_y(x) - with all_warnings(): # deprecation + with expected_warnings(['`_params`']): assert_equal(model.params, model._params) diff --git a/skimage/measure/tests/test_regionprops.py b/skimage/measure/tests/test_regionprops.py index 830489d1..fdbabad9 100644 --- a/skimage/measure/tests/test_regionprops.py +++ b/skimage/measure/tests/test_regionprops.py @@ -4,7 +4,7 @@ import numpy as np import math from skimage.measure._regionprops import regionprops, PROPS, perimeter -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings SAMPLE = np.array( @@ -26,16 +26,14 @@ INTENSITY_SAMPLE[1, 9:11] = 2 def test_all_props(): region = regionprops(SAMPLE, INTENSITY_SAMPLE)[0] for prop in PROPS: - with all_warnings(): # deprecation warning - assert_equal(region[prop], getattr(region, PROPS[prop])) + assert_equal(region[prop], getattr(region, PROPS[prop])) def test_dtype(): regionprops(np.zeros((10, 10), dtype=np.int)) regionprops(np.zeros((10, 10), dtype=np.uint)) - with all_warnings(): # deprecation on dtype - assert_raises((TypeError, RuntimeError), regionprops, - np.zeros((10, 10), dtype=np.double)) + assert_raises((TypeError, RuntimeError), regionprops, + np.zeros((10, 10), dtype=np.double)) def test_ndim(): @@ -128,13 +126,13 @@ def test_equiv_diameter(): def test_euler_number(): - with all_warnings(): # deprecation warning + with expected_warnings(['`background`']): en = regionprops(SAMPLE)[0].euler_number assert en == 0 SAMPLE_mod = SAMPLE.copy() SAMPLE_mod[7, -3] = 0 - with all_warnings(): # deprecation warning + with expected_warnings(['`background`']): en = regionprops(SAMPLE_mod)[0].euler_number assert en == -1 @@ -374,7 +372,7 @@ def test_equals(): r2 = regions[0] r3 = regions[1] - with all_warnings(): # deprecation warning + with expected_warnings(['`background`']): assert_equal(r1 == r2, True, "Same regionprops are not equal") assert_equal(r1 != r3, True, "Different regionprops are equal") diff --git a/skimage/morphology/tests/__init__.py b/skimage/morphology/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/morphology/tests/__init__.py +++ b/skimage/morphology/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/morphology/tests/test_binary.py b/skimage/morphology/tests/test_binary.py index 3a3abf97..d52f92bb 100644 --- a/skimage/morphology/tests/test_binary.py +++ b/skimage/morphology/tests/test_binary.py @@ -4,7 +4,7 @@ from numpy import testing from skimage import data, color from skimage.util import img_as_bool from skimage.morphology import binary, grey, selem -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings from scipy import ndimage @@ -15,7 +15,7 @@ bw_img = img > 100 def test_non_square_image(): strel = selem.square(3) binary_res = binary.binary_erosion(bw_img[:100, :200], strel) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.erosion(bw_img[:100, :200], strel)) testing.assert_array_equal(binary_res, grey_res) @@ -23,7 +23,7 @@ def test_non_square_image(): def test_binary_erosion(): strel = selem.square(3) binary_res = binary.binary_erosion(bw_img, strel) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.erosion(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res) @@ -31,7 +31,7 @@ def test_binary_erosion(): def test_binary_dilation(): strel = selem.square(3) binary_res = binary.binary_dilation(bw_img, strel) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.dilation(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res) @@ -39,7 +39,7 @@ def test_binary_dilation(): def test_binary_closing(): strel = selem.square(3) binary_res = binary.binary_closing(bw_img, strel) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.closing(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res) @@ -47,7 +47,7 @@ def test_binary_closing(): def test_binary_opening(): strel = selem.square(3) binary_res = binary.binary_opening(bw_img, strel) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.opening(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res) @@ -57,7 +57,7 @@ def test_selem_overflow(): img = np.zeros((20, 20)) img[2:19, 2:19] = 1 binary_res = binary.binary_erosion(img, strel) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.erosion(img, strel)) testing.assert_array_equal(binary_res, grey_res) diff --git a/skimage/morphology/tests/test_ccomp.py b/skimage/morphology/tests/test_ccomp.py index 569b0e38..901a18b9 100644 --- a/skimage/morphology/tests/test_ccomp.py +++ b/skimage/morphology/tests/test_ccomp.py @@ -1,22 +1,16 @@ import numpy as np from numpy.testing import assert_array_equal, run_module_suite -from skimage.morphology import label as _label +from skimage.measure import label import skimage.measure._ccomp as ccomp -from skimage._shared.utils import all_warnings -np.random.seed(0) +from skimage._shared._warnings import expected_warnings + # The background label value # is supposed to be changed to 0 soon BG = -1 -def label(*args, **kwargs): - """Wrap the label function to avoid deprecation warning""" - with all_warnings(): - return _label(*args, **kwargs) - - class TestConnectedComponents: def setup(self): self.x = np.array([[0, 0, 3, 2, 1, 9], @@ -30,7 +24,8 @@ class TestConnectedComponents: [6, 5, 5, 7, 8, 9]]) def test_basic(self): - assert_array_equal(label(self.x), self.labels) + with expected_warnings(['`background`']): + assert_array_equal(label(self.x), self.labels) # Make sure data wasn't modified assert self.x[0, 2] == 3 @@ -38,7 +33,7 @@ class TestConnectedComponents: def test_random(self): x = (np.random.rand(20, 30) * 5).astype(np.int) - with all_warnings(): + with expected_warnings(['`background`']): labels = label(x) n = labels.max() @@ -50,13 +45,13 @@ class TestConnectedComponents: x = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]) - with all_warnings(): + with expected_warnings(['`background`']): assert_array_equal(label(x), x) def test_4_vs_8(self): x = np.array([[0, 1], [1, 0]], dtype=int) - with all_warnings(): + with expected_warnings(['`background`']): assert_array_equal(label(x, 4), [[0, 1], [2, 3]]) @@ -69,7 +64,7 @@ class TestConnectedComponents: [1, 1, 5], [0, 0, 0]]) - with all_warnings(): + with expected_warnings(['`background`']): assert_array_equal(label(x), [[0, 1, 1], [0, 0, 2], [3, 3, 3]]) @@ -105,7 +100,7 @@ class TestConnectedComponents: [0, 0, 6], [5, 5, 5]]) - with all_warnings(): + with expected_warnings(['`background`']): assert_array_equal(label(x, return_num=True)[1], 4) assert_array_equal(label(x, background=0, return_num=True)[1], 3) @@ -147,7 +142,8 @@ class TestConnectedComponents3d: [10, 5, 7, 7, 7]]) def test_basic(self): - labels = label(self.x) + with expected_warnings(['`background`']): + labels = label(self.x) assert_array_equal(labels, self.labels) assert self.x[0, 0, 2] == 2, \ @@ -156,7 +152,7 @@ class TestConnectedComponents3d: def test_random(self): x = (np.random.rand(20, 30) * 5).astype(np.int) - with all_warnings(): + with expected_warnings(['`background`']): labels = label(x) n = labels.max() @@ -169,7 +165,7 @@ class TestConnectedComponents3d: x[0, 2, 2] = 1 x[1, 1, 1] = 1 x[2, 0, 0] = 1 - with all_warnings(): + with expected_warnings(['`background`']): assert_array_equal(label(x), x) def test_4_vs_8(self): @@ -178,7 +174,7 @@ class TestConnectedComponents3d: x[1, 0, 0] = 1 label4 = x.copy() label4[1, 0, 0] = 2 - with all_warnings(): + with expected_warnings(['`background`']): assert_array_equal(label(x, 4), label4) assert_array_equal(label(x, 8), x) @@ -206,7 +202,7 @@ class TestConnectedComponents3d: [BG, 0, 1], [BG, BG, BG]]) - with all_warnings(): + with expected_warnings(['`background`']): assert_array_equal(label(x), lnb) assert_array_equal(label(x, background=0), lb) @@ -244,7 +240,7 @@ class TestConnectedComponents3d: [0, 0, 6], [5, 5, 5]]) - with all_warnings(): + with expected_warnings(['`background`']): assert_array_equal(label(x, return_num=True)[1], 4) assert_array_equal(label(x, background=0, return_num=True)[1], 3) @@ -258,7 +254,8 @@ class TestConnectedComponents3d: (1, xlen, 1), (xlen, 1, 1), (1, 1, xlen)) for reshape in reshapes: x2 = x.reshape(reshape) - labelled = label(x2) + with expected_warnings(['`background`']): + labelled = label(x2) assert_array_equal(y, labelled.flatten()) def test_nd(self): diff --git a/skimage/morphology/tests/test_grey.py b/skimage/morphology/tests/test_grey.py index 9c978105..9961b985 100644 --- a/skimage/morphology/tests/test_grey.py +++ b/skimage/morphology/tests/test_grey.py @@ -7,7 +7,7 @@ from scipy import ndimage import skimage from skimage import data_dir from skimage.morphology import grey, selem -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings lena = np.load(os.path.join(data_dir, 'lena_GRAY_U8.npy')) @@ -172,10 +172,10 @@ def test_3d_fallback_white_tophat(): image[3, 2:5, 2:5] = 1 image[4, 3:5, 3:5] = 1 - with all_warnings(): # scipy upstream warning + with expected_warnings(['operator.*deprecated']): new_image = grey.white_tophat(image) footprint = ndimage.generate_binary_structure(3,1) - with all_warnings(): # scipy upstream warning + with expected_warnings(['operator.*deprecated']): image_expected = ndimage.white_tophat(image,footprint=footprint) testing.assert_array_equal(new_image, image_expected) @@ -185,10 +185,10 @@ def test_3d_fallback_black_tophat(): image[3, 2:5, 2:5] = 0 image[4, 3:5, 3:5] = 0 - with all_warnings(): # scipy upstream warning + with expected_warnings(['operator.*deprecated']): new_image = grey.black_tophat(image) footprint = ndimage.generate_binary_structure(3,1) - with all_warnings(): # scipy upstream warning + with expected_warnings(['operator.*deprecated']): image_expected = ndimage.black_tophat(image,footprint=footprint) testing.assert_array_equal(new_image, image_expected) @@ -223,11 +223,11 @@ class TestDTypes(): self.expected_closing = np.load(fname_closing)[arrname] def _test_image(self, image): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): result_opening = grey.opening(image, self.disk) testing.assert_equal(result_opening, self.expected_opening) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): result_closing = grey.closing(image, self.disk) testing.assert_equal(result_closing, self.expected_closing) diff --git a/skimage/restoration/tests/__init__.py b/skimage/restoration/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/restoration/tests/__init__.py +++ b/skimage/restoration/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/restoration/tests/test_unwrap.py b/skimage/restoration/tests/test_unwrap.py index 4819ea24..e628f4fe 100644 --- a/skimage/restoration/tests/test_unwrap.py +++ b/skimage/restoration/tests/test_unwrap.py @@ -7,7 +7,7 @@ from numpy.testing import (run_module_suite, assert_array_almost_equal_nulp, import warnings from skimage.restoration import unwrap_phase -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings def assert_phase_almost_equal(a, b, *args, **kwargs): @@ -133,7 +133,7 @@ def test_mask(): assert_array_almost_equal_nulp(image_unwrapped[:, -1], image[i, -1]) # Same tests, but forcing use of the 3D unwrapper by reshaping - with all_warnings(): # 1 dimension + with expected_warnings(['length 1 dimension']): shape = (1,) + image_wrapped.shape image_wrapped_3d = image_wrapped.reshape(shape) image_unwrapped_3d = unwrap_phase(image_wrapped_3d) diff --git a/skimage/segmentation/tests/__init__.py b/skimage/segmentation/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/segmentation/tests/__init__.py +++ b/skimage/segmentation/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/segmentation/tests/test_random_walker.py b/skimage/segmentation/tests/test_random_walker.py index ed68cb0f..5877a817 100644 --- a/skimage/segmentation/tests/test_random_walker.py +++ b/skimage/segmentation/tests/test_random_walker.py @@ -1,7 +1,14 @@ import numpy as np from skimage.segmentation import random_walker from skimage.transform import resize -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings +from skimage._shared.version_requirements import is_installed + + +if is_installed('pyamg'): + PYAMG_EXPECTED_WARNING = [] +else: + PYAMG_EXPECTED_WARNING = ['pyamg'] def make_2d_syntheticdata(lx, ly=None): @@ -75,11 +82,11 @@ def test_2d_cg(): lx = 70 ly = 100 data, labels = make_2d_syntheticdata(lx, ly) - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): labels_cg = random_walker(data, labels, beta=90, mode='cg') assert (labels_cg[25:45, 40:60] == 2).all() assert data.shape == labels.shape - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): full_prob = random_walker(data, labels, beta=90, mode='cg', return_full_prob=True) assert (full_prob[1, 25:45, 40:60] >= @@ -92,11 +99,11 @@ def test_2d_cg_mg(): lx = 70 ly = 100 data, labels = make_2d_syntheticdata(lx, ly) - with all_warnings(): # pyamg optional + with expected_warnings(PYAMG_EXPECTED_WARNING): labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') assert (labels_cg_mg[25:45, 40:60] == 2).all() assert data.shape == labels.shape - with all_warnings(): # pyamg optional + with expected_warnings(PYAMG_EXPECTED_WARNING): full_prob = random_walker(data, labels, beta=90, mode='cg_mg', return_full_prob=True) assert (full_prob[1, 25:45, 40:60] >= @@ -111,7 +118,7 @@ def test_types(): data, labels = make_2d_syntheticdata(lx, ly) data = 255 * (data - data.min()) // (data.max() - data.min()) data = data.astype(np.uint8) - with all_warnings(): # pyamg optional + with expected_warnings(PYAMG_EXPECTED_WARNING): labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') assert (labels_cg_mg[25:45, 40:60] == 2).all() assert data.shape == labels.shape @@ -145,7 +152,7 @@ def test_3d(): n = 30 lx, ly, lz = n, n, n data, labels = make_3d_syntheticdata(lx, ly, lz) - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): labels = random_walker(data, labels, mode='cg') assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all() assert data.shape == labels.shape @@ -159,7 +166,7 @@ def test_3d_inactive(): old_labels = np.copy(labels) labels[5:25, 26:29, 26:29] = -1 after_labels = np.copy(labels) - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): labels = random_walker(data, labels, mode='cg') assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all() assert data.shape == labels.shape @@ -170,11 +177,11 @@ def test_multispectral_2d(): lx, ly = 70, 100 data, labels = make_2d_syntheticdata(lx, ly) data = data[..., np.newaxis].repeat(2, axis=-1) # Expect identical output - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): multi_labels = random_walker(data, labels, mode='cg', multichannel=True) assert data[..., 0].shape == labels.shape - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): single_labels = random_walker(data[..., 0], labels, mode='cg') assert (multi_labels.reshape(labels.shape)[25:45, 40:60] == 2).all() assert data[..., 0].shape == labels.shape @@ -186,11 +193,11 @@ def test_multispectral_3d(): lx, ly, lz = n, n, n data, labels = make_3d_syntheticdata(lx, ly, lz) data = data[..., np.newaxis].repeat(2, axis=-1) # Expect identical output - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): multi_labels = random_walker(data, labels, mode='cg', multichannel=True) assert data[..., 0].shape == labels.shape - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): single_labels = random_walker(data[..., 0], labels, mode='cg') assert (multi_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all() assert (single_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all() @@ -217,7 +224,7 @@ def test_spacing_0(): lz // 4 - small_l // 8] = 2 # Test with `spacing` kwarg - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg', spacing=(1., 1., 0.5)) @@ -245,7 +252,7 @@ def test_spacing_1(): # Test with `spacing` kwarg # First, anisotropic along Y - with all_warnings(): # using cg mode + with expected_warnings(['"cg" mode']): labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg', spacing=(1., 2., 1.)) assert (labels_aniso[13:17, 26:34, 13:17] == 2).all() @@ -265,7 +272,7 @@ def test_spacing_1(): lz // 2 - small_l // 4] = 2 # Anisotropic along X - with all_warnings(): # cg mode + with expected_warnings(['"cg" mode']): labels_aniso2 = random_walker(data_aniso, labels_aniso2, mode='cg', spacing=(2., 1., 1.)) @@ -277,7 +284,7 @@ def test_trivial_cases(): img = np.ones((10, 10)) labels = np.ones((10, 10)) - with all_warnings(): # using provided labels + with expected_warnings(["Returning provided labels"]): pass_through = random_walker(img, labels) np.testing.assert_array_equal(pass_through, labels) @@ -285,7 +292,7 @@ def test_trivial_cases(): labels[:, :5] = 3 expected = np.concatenate(((labels == 1)[..., np.newaxis], (labels == 3)[..., np.newaxis]), axis=2) - with all_warnings(): # using provided labels + with expected_warnings(["Returning provided labels"]): test = random_walker(img, labels, return_full_prob=True) np.testing.assert_array_equal(test, expected) diff --git a/skimage/transform/tests/__init__.py b/skimage/transform/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/transform/tests/__init__.py +++ b/skimage/transform/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/transform/tests/test_geometric.py b/skimage/transform/tests/test_geometric.py index b6e0597f..125faf6c 100644 --- a/skimage/transform/tests/test_geometric.py +++ b/skimage/transform/tests/test_geometric.py @@ -7,7 +7,7 @@ from skimage.transform import (estimate_transform, matrix_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings SRC = np.array([ @@ -252,11 +252,11 @@ def test_invalid_input(): def test_deprecated_params_attributes(): for t in ('projective', 'affine', 'similarity'): tform = estimate_transform(t, SRC, DST) - with all_warnings(): # _matrix is deprecated + with expected_warnings(['`_matrix`.*deprecated']): assert_equal(tform._matrix, tform.params) tform = estimate_transform('polynomial', SRC, DST, order=3) - with all_warnings(): # _params is deprecated + with expected_warnings(['`_params`.*deprecated']): assert_equal(tform._params, tform.params) diff --git a/skimage/transform/tests/test_hough_transform.py b/skimage/transform/tests/test_hough_transform.py index ae6e0cf6..884d7957 100644 --- a/skimage/transform/tests/test_hough_transform.py +++ b/skimage/transform/tests/test_hough_transform.py @@ -3,7 +3,7 @@ from numpy.testing import assert_almost_equal, assert_equal import skimage.transform as tf from skimage.draw import line, circle_perimeter, ellipse_perimeter -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings def append_desc(func, description): @@ -68,7 +68,7 @@ def test_hough_line_peaks(): out, angles, d = tf.hough_line(img) - with all_warnings(): # _ccomp deprecation + with expected_warnings(['`background`']): out, theta, dist = tf.hough_line_peaks(out, angles, d) assert_equal(len(dist), 1) @@ -81,7 +81,7 @@ def test_hough_line_peaks_dist(): img[:, 30] = True img[:, 40] = True hspace, angles, dists = tf.hough_line(img) - with all_warnings(): # _ccomp deprecation + with expected_warnings(['`background`']): assert len(tf.hough_line_peaks(hspace, angles, dists, min_distance=5)[0]) == 2 assert len(tf.hough_line_peaks(hspace, angles, dists, @@ -89,7 +89,7 @@ def test_hough_line_peaks_dist(): def test_hough_line_peaks_angle(): - with all_warnings(): # _ccomp deprecation + with expected_warnings(['`background`']): check_hough_line_peaks_angle() @@ -124,7 +124,7 @@ def test_hough_line_peaks_num(): img[:, 30] = True img[:, 40] = True hspace, angles, dists = tf.hough_line(img) - with all_warnings(): # _ccomp deprecation + with expected_warnings(['`background`']): assert len(tf.hough_line_peaks(hspace, angles, dists, min_distance=0, min_angle=0, num_peaks=1)[0]) == 1 diff --git a/skimage/transform/tests/test_warps.py b/skimage/transform/tests/test_warps.py index b0c58281..115f0e6f 100644 --- a/skimage/transform/tests/test_warps.py +++ b/skimage/transform/tests/test_warps.py @@ -10,7 +10,7 @@ from skimage.transform import (warp, warp_coords, rotate, resize, rescale, downscale_local_mean) from skimage import transform as tf, data, img_as_float from skimage.color import rgb2gray -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings np.random.seed(0) @@ -198,7 +198,7 @@ def test_swirl(): swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'} - with all_warnings(): # deprecation warning + with expected_warnings(['Bi-quadratic.*bug']): swirled = tf.swirl(image, strength=10, **swirl_params) unswirled = tf.swirl(swirled, strength=-10, **swirl_params) diff --git a/skimage/util/tests/__init__.py b/skimage/util/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/util/tests/__init__.py +++ b/skimage/util/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/util/tests/test_dtype.py b/skimage/util/tests/test_dtype.py index 50ad3fc4..4c1f2a43 100644 --- a/skimage/util/tests/test_dtype.py +++ b/skimage/util/tests/test_dtype.py @@ -3,7 +3,7 @@ from numpy.testing import assert_equal, assert_raises from skimage import img_as_int, img_as_float, \ img_as_uint, img_as_ubyte from skimage.util.dtype import convert -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings dtype_range = {np.uint8: (0, 255), @@ -29,9 +29,13 @@ def test_range(): (img_as_float, np.float64), (img_as_uint, np.uint16), (img_as_ubyte, np.ubyte)]: - - with all_warnings(): # precision loss - y = f(x) + + try: + with expected_warnings(['precision loss|sign loss']): + y = f(x) + except ValueError as e: + if not 'No warning raised' in str(e): + raise omin, omax = dtype_range[dt] @@ -62,8 +66,14 @@ def test_range_extra_dtypes(): for dtype_in, dt in dtype_pairs: imin, imax = dtype_range_extra[dtype_in] x = np.linspace(imin, imax, 10).astype(dtype_in) - with all_warnings(): # sign loss - y = convert(x, dt) + + try: + with expected_warnings(['precision loss|sign loss']): + y = convert(x, dt) + except ValueError as e: + if not 'No warning raised' in str(e): + raise + omin, omax = dtype_range_extra[dt] yield (_verify_range, "From %s to %s" % (np.dtype(dtype_in), np.dtype(dt)), diff --git a/skimage/util/tests/test_shape.py b/skimage/util/tests/test_shape.py index ee897e7c..38127df8 100644 --- a/skimage/util/tests/test_shape.py +++ b/skimage/util/tests/test_shape.py @@ -3,7 +3,7 @@ from nose.tools import raises from numpy.testing import assert_equal, assert_warns from skimage.util.shape import view_as_blocks, view_as_windows -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings @raises(TypeError) @@ -153,9 +153,8 @@ def test_views_non_contiguous(): A = np.arange(16).reshape((4, 4)) A = A[::2, :] - with all_warnings(): - assert_warns(RuntimeWarning, view_as_blocks, A, (2, 2)) - assert_warns(RuntimeWarning, view_as_windows, A, (2, 2)) + assert_warns(RuntimeWarning, view_as_blocks, A, (2, 2)) + assert_warns(RuntimeWarning, view_as_windows, A, (2, 2)) if __name__ == '__main__': diff --git a/skimage/viewer/tests/__init__.py b/skimage/viewer/tests/__init__.py index c098c64d..9c11267a 100644 --- a/skimage/viewer/tests/__init__.py +++ b/skimage/viewer/tests/__init__.py @@ -1,2 +1,9 @@ -from skimage._shared.testing import setup_test -setup_test() +from skimage._shared.testing import setup_test, teardown_test + + +def setup(): + setup_test() + + +def tearDown(): + teardown_test() diff --git a/skimage/viewer/tests/test_plugins.py b/skimage/viewer/tests/test_plugins.py index 6ad180fb..528df8f4 100644 --- a/skimage/viewer/tests/test_plugins.py +++ b/skimage/viewer/tests/test_plugins.py @@ -12,7 +12,7 @@ from skimage.viewer.plugins import ( PlotPlugin) from skimage.viewer.plugins.base import Plugin from skimage.viewer.widgets import Slider -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings def setup_line_profile(image, limits='image'): @@ -67,7 +67,7 @@ def test_line_profile_dynamic(): assert_almost_equal(np.std(line), 0.229, 3) assert_almost_equal(np.max(line) - np.min(line), 0.725, 1) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): viewer.image = skimage.img_as_float(median(image, selem=disk(radius=3))) @@ -161,7 +161,7 @@ def test_plugin(): viewer = ImageViewer(img) def median_filter(img, radius=3): - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): return median(img, selem=disk(radius=radius)) plugin = Plugin(image_filter=median_filter) diff --git a/skimage/viewer/tests/test_viewer.py b/skimage/viewer/tests/test_viewer.py index 553a8be3..1604ca6d 100644 --- a/skimage/viewer/tests/test_viewer.py +++ b/skimage/viewer/tests/test_viewer.py @@ -8,7 +8,7 @@ from skimage.filters import sobel from numpy.testing import assert_equal from numpy.testing.decorators import skipif from skimage._shared.version_requirements import is_installed -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings @skipif(not viewer_available) @@ -68,7 +68,7 @@ def test_viewer_with_overlay(): ov.color = 3 assert_equal(ov.color, 'yellow') - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): viewer.save_to_file(filename) ov.display_filtered_image(img) assert_equal(ov.overlay, img) diff --git a/skimage/viewer/tests/test_widgets.py b/skimage/viewer/tests/test_widgets.py index 439454f3..170c186c 100644 --- a/skimage/viewer/tests/test_widgets.py +++ b/skimage/viewer/tests/test_widgets.py @@ -8,7 +8,7 @@ from skimage.viewer.plugins.base import Plugin from skimage.viewer.qt import QtGui, QtCore from numpy.testing import assert_almost_equal, assert_equal from numpy.testing.decorators import skipif -from skimage._shared.utils import all_warnings +from skimage._shared._warnings import expected_warnings def get_image_viewer(): @@ -100,12 +100,12 @@ def test_save_buttons(): timer.singleShot(100, QtGui.QApplication.quit) sv.save_to_stack() - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): sv.save_to_file(filename) img = data.imread(filename) - with all_warnings(): # precision loss + with expected_warnings(['precision loss']): assert_almost_equal(img, img_as_uint(viewer.image)) img = io.pop() From 2d3ada19e57323fac56342ee8bcab512cf36cc5b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 23 Dec 2014 16:24:40 -0600 Subject: [PATCH 15/28] Allow for no exceptions to be raised and cleanup Allow for no exceptions to be raised Add some helpful comments Remove doctest skips Remove TODO note Cleanup and skip failing doctest --- TODO.txt | 2 +- skimage/_shared/_warnings.py | 7 +++++-- skimage/_shared/testing.py | 12 ++++++------ skimage/_shared/utils.py | 1 - skimage/io/_io.py | 2 +- skimage/measure/_ccomp.pyx | 2 +- skimage/measure/fit.py | 6 +++--- skimage/morphology/watershed.py | 6 +++--- skimage/transform/hough_transform.py | 4 ++-- skimage/util/tests/test_dtype.py | 16 ++++------------ 10 files changed, 26 insertions(+), 32 deletions(-) diff --git a/TODO.txt b/TODO.txt index 13823d08..d6d95586 100644 --- a/TODO.txt +++ b/TODO.txt @@ -15,7 +15,7 @@ Version 0.13 Version 0.12 ------------ * Change `label` to mark background as 0, not -1, which is consistent with - SciPy's labelling. Also remove doctest skip in _ccomp.pyx `label`. + SciPy's labelling. * Remove `skimage.morphology.label` from `skimage.morphology.__init__`--it now lives in `skimage.measure.label`. * Remove deprecated `reverse_map` parameter of `skimage.transform.warp` diff --git a/skimage/_shared/_warnings.py b/skimage/_shared/_warnings.py index fd2c06a0..ffac12e9 100644 --- a/skimage/_shared/_warnings.py +++ b/skimage/_shared/_warnings.py @@ -85,12 +85,15 @@ def expected_warnings(matching): Uses `all_warnings` to ensure all warnings are raised. Upon exiting, it checks the recorded warnings for the desired matching string. Raises a warning if the match was not found or an Unexpected - warning is found. + warning is found. You can pass an empty regex as on of the matches + to allow for no matches: "\A\Z". """ with all_warnings() as w: + # enter context yield w - remaining = [m for m in matching] + # exited user context, check the recorded warnings + remaining = [m for m in matching if not '\A\Z' in m.split('|')] for warn in w: found = False for match in matching: diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index e5ca2f87..0f556acf 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -117,7 +117,7 @@ def color_check(plugin, fmt='png'): testing.assert_allclose(img2.astype(np.uint8), r2) img3 = img_as_float(img) - with expected_warnings(['precision loss']): + with expected_warnings(['precision loss|unclosed file']): r3 = roundtrip(img3, plugin, fmt) testing.assert_allclose(r3, img) @@ -129,12 +129,12 @@ def color_check(plugin, fmt='png'): r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img4) else: - with expected_warnings(['sign loss']): + with expected_warnings(['sign loss|precision loss|unclosed file']): r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img_as_ubyte(img4)) img5 = img_as_uint(img) - with expected_warnings(['precision loss']): + with expected_warnings(['precision loss|unclosed file']): r5 = roundtrip(img5, plugin, fmt) testing.assert_allclose(r5, img) @@ -154,7 +154,7 @@ def mono_check(plugin, fmt='png'): testing.assert_allclose(img2.astype(np.uint8), r2) img3 = img_as_float(img) - with expected_warnings(['precision loss']): + with expected_warnings(['precision|unclosed file|\A\Z']): r3 = roundtrip(img3, plugin, fmt) if r3.dtype.kind == 'f': testing.assert_allclose(img3, r3) @@ -165,11 +165,11 @@ def mono_check(plugin, fmt='png'): img4 = img_as_int(img) if fmt.lower() in (('tif', 'tiff')): img4 -= 100 - with expected_warnings(['sign loss']): + with expected_warnings(['sign loss|\A\Z']): r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img4) else: - with expected_warnings(['sign loss']): + with expected_warnings(['precision loss|sign loss|unclosed file']): r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img_as_uint(img4)) diff --git a/skimage/_shared/utils.py b/skimage/_shared/utils.py index 7be979bc..43fda35d 100644 --- a/skimage/_shared/utils.py +++ b/skimage/_shared/utils.py @@ -163,4 +163,3 @@ def assert_nD(array, ndim, arg_name='image'): ndim = [ndim] if not array.ndim in ndim: raise ValueError(msg % (arg_name, '-or-'.join([str(n) for n in ndim]))) - diff --git a/skimage/io/_io.py b/skimage/io/_io.py index 1ebb3d59..06da7adb 100644 --- a/skimage/io/_io.py +++ b/skimage/io/_io.py @@ -193,7 +193,7 @@ def show(): >>> import skimage.io as io >>> for i in range(4): - ... io.imshow(np.random.rand(50, 50)) # doctest: +SKIP + ... io.imshow(np.random.rand(50, 50)) >>> io.show() # doctest: +SKIP ''' diff --git a/skimage/measure/_ccomp.pyx b/skimage/measure/_ccomp.pyx index ac75601a..56b31a9f 100644 --- a/skimage/measure/_ccomp.pyx +++ b/skimage/measure/_ccomp.pyx @@ -430,7 +430,7 @@ def label(input, neighbors=None, background=None, return_num=False, ... [1, 1, 5], ... [0, 0, 0]]) - >>> print(label(x, background=0)) # doctest: +SKIP + >>> print(label(x, background=0)) [[ 0 -1 -1] [ 0 0 1] [-1 -1 -1]] diff --git a/skimage/measure/fit.py b/skimage/measure/fit.py index b4799a0b..7de90291 100644 --- a/skimage/measure/fit.py +++ b/skimage/measure/fit.py @@ -619,10 +619,10 @@ def ransac(data, model_class, min_samples, residual_threshold, Estimate ellipse model using RANSAC: - >>> ransac_model, inliers = ransac(data, EllipseModel, 5, 3, max_trials=50) # doctest: +SKIP - >>> ransac_model.params # doctest: +SKIP + >>> ransac_model, inliers = ransac(data, EllipseModel, 5, 3, max_trials=50) + >>> ransac_model.params array([ 20.12762373, 29.73563063, 4.81499637, 10.4743584 , 0.05217117]) - >>> inliers # doctest: +SKIP + >>> inliers array([False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, diff --git a/skimage/morphology/watershed.py b/skimage/morphology/watershed.py index 783e69b3..5e4a9156 100644 --- a/skimage/morphology/watershed.py +++ b/skimage/morphology/watershed.py @@ -119,9 +119,9 @@ def watershed(image, markers, connectivity=None, offset=None, mask=None): >>> from skimage.feature import peak_local_max >>> local_maxi = peak_local_max(distance, labels=image, ... footprint=np.ones((3, 3)), - ... indices=False) # doctest: +SKIP - >>> markers = ndimage.label(local_maxi)[0] # doctest: +SKIP - >>> labels = watershed(-distance, markers, mask=image) # doctest: +SKIP + ... indices=False) + >>> markers = ndimage.label(local_maxi)[0] + >>> labels = watershed(-distance, markers, mask=image) The algorithm works also for 3-D images, and can be used for example to separate overlapping spheres. diff --git a/skimage/transform/hough_transform.py b/skimage/transform/hough_transform.py index 167a4da5..cbb4caa6 100644 --- a/skimage/transform/hough_transform.py +++ b/skimage/transform/hough_transform.py @@ -49,8 +49,8 @@ def hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, >>> rr, cc = line(0, 14, 14, 0) >>> img[cc, rr] = 1 >>> hspace, angles, dists = hough_line(img) - >>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists) # doctest: +SKIP - >>> len(angles) # doctest: +SKIP + >>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists) + >>> len(angles) 2 """ diff --git a/skimage/util/tests/test_dtype.py b/skimage/util/tests/test_dtype.py index 4c1f2a43..612c43e6 100644 --- a/skimage/util/tests/test_dtype.py +++ b/skimage/util/tests/test_dtype.py @@ -30,12 +30,8 @@ def test_range(): (img_as_uint, np.uint16), (img_as_ubyte, np.ubyte)]: - try: - with expected_warnings(['precision loss|sign loss']): - y = f(x) - except ValueError as e: - if not 'No warning raised' in str(e): - raise + with expected_warnings(['precision loss|sign loss|\A\Z']): + y = f(x) omin, omax = dtype_range[dt] @@ -67,12 +63,8 @@ def test_range_extra_dtypes(): imin, imax = dtype_range_extra[dtype_in] x = np.linspace(imin, imax, 10).astype(dtype_in) - try: - with expected_warnings(['precision loss|sign loss']): - y = convert(x, dt) - except ValueError as e: - if not 'No warning raised' in str(e): - raise + with expected_warnings(['precision loss|sign loss|\A\Z']): + y = convert(x, dt) omin, omax = dtype_range_extra[dt] yield (_verify_range, From 3829401e9f1d9503f874d13eb77ee4ec9e73ed70 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 23 Dec 2014 21:20:23 -0600 Subject: [PATCH 16/28] Fix label wrapper function --- skimage/measure/_label.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/skimage/measure/_label.py b/skimage/measure/_label.py index 47e8af74..89b4856a 100644 --- a/skimage/measure/_label.py +++ b/skimage/measure/_label.py @@ -1,6 +1,7 @@ from ._ccomp import label as _label -def label(input, neighbors=8, background=None, return_num=False): - return _label(input, neighbors, background, return_num) +def label(input, neighbors=8, background=None, return_num=False, + connectivity=None): + return _label(input, neighbors, background, return_num, connectivity) label.__doc__ = _label.__doc__ From cb2745cfdfa7e90de4a7201300d5d22ae8015e0e Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 24 Dec 2014 05:57:37 -0600 Subject: [PATCH 17/28] Change default neighbors to None --- skimage/measure/_label.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skimage/measure/_label.py b/skimage/measure/_label.py index 89b4856a..e3ac6034 100644 --- a/skimage/measure/_label.py +++ b/skimage/measure/_label.py @@ -1,6 +1,6 @@ from ._ccomp import label as _label -def label(input, neighbors=8, background=None, return_num=False, +def label(input, neighbors=None, background=None, return_num=False, connectivity=None): return _label(input, neighbors, background, return_num, connectivity) From 2a6b4ccaea7cdd0e9be95cd8a051f0d3c44cdfa4 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 24 Dec 2014 06:34:13 -0600 Subject: [PATCH 18/28] Import scipy.sparse in setup_test --- skimage/_shared/testing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index 0f556acf..d012b8b6 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -186,7 +186,7 @@ def setup_test(): Set a random seed """ warnings.simplefilter('default') - from scipy import signal, ndimage, special, optimize, linalg + from scipy import signal, ndimage, special, optimize, linalg, sparse from scipy.io import loadmat from skimage import viewer, filter np.random.seed(0) From 4453120d96dc5c645f4e87d9a390a3ab66627410 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 24 Dec 2014 06:36:04 -0600 Subject: [PATCH 19/28] Allow warnings in the minimum build --- skimage/_shared/testing.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index d012b8b6..1c95644b 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -190,7 +190,8 @@ def setup_test(): from scipy.io import loadmat from skimage import viewer, filter np.random.seed(0) - warnings.simplefilter('error') + if os.environ.get('TRAVIS_PYTHON_VERSION', None) != '2.7': + warnings.simplefilter('error') def teardown_test(): From d37ccca5985f1201828cf32527feba7466f48b8b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 24 Dec 2014 06:54:56 -0600 Subject: [PATCH 20/28] Fix Py2.7 build errors --- skimage/_shared/testing.py | 3 +-- skimage/exposure/tests/test_exposure.py | 2 +- skimage/filters/rank/tests/test_rank.py | 2 +- skimage/morphology/tests/test_grey.py | 8 ++++---- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index 1c95644b..d012b8b6 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -190,8 +190,7 @@ def setup_test(): from scipy.io import loadmat from skimage import viewer, filter np.random.seed(0) - if os.environ.get('TRAVIS_PYTHON_VERSION', None) != '2.7': - warnings.simplefilter('error') + warnings.simplefilter('error') def teardown_test(): diff --git a/skimage/exposure/tests/test_exposure.py b/skimage/exposure/tests/test_exposure.py index 5a3d3dba..6e93d1af 100644 --- a/skimage/exposure/tests/test_exposure.py +++ b/skimage/exposure/tests/test_exposure.py @@ -211,7 +211,7 @@ def test_adapthist_grayscale(): img = skimage.img_as_float(data.astronaut()) img = rgb2gray(img) img = np.dstack((img, img, img)) - with expected_warnings(['precision loss']): + with expected_warnings(['precision loss|non-contiguous input]): adapted = exposure.equalize_adapthist(img, 10, 9, clip_limit=0.01, nbins=128) assert_almost_equal = np.testing.assert_almost_equal diff --git a/skimage/filters/rank/tests/test_rank.py b/skimage/filters/rank/tests/test_rank.py index 5cf5a091..f491881d 100644 --- a/skimage/filters/rank/tests/test_rank.py +++ b/skimage/filters/rank/tests/test_rank.py @@ -11,7 +11,7 @@ from skimage._shared._warnings import expected_warnings def test_all(): - with expected_warnings(['precision loss', 'non-integer']): + with expected_warnings(['precision loss', 'non-integer|\A\Z']): check_all() diff --git a/skimage/morphology/tests/test_grey.py b/skimage/morphology/tests/test_grey.py index 9961b985..86ce10f5 100644 --- a/skimage/morphology/tests/test_grey.py +++ b/skimage/morphology/tests/test_grey.py @@ -172,10 +172,10 @@ def test_3d_fallback_white_tophat(): image[3, 2:5, 2:5] = 1 image[4, 3:5, 3:5] = 1 - with expected_warnings(['operator.*deprecated']): + with expected_warnings(['operator.*deprecated|\A\Z']): new_image = grey.white_tophat(image) footprint = ndimage.generate_binary_structure(3,1) - with expected_warnings(['operator.*deprecated']): + with expected_warnings(['operator.*deprecated\A\Z']): image_expected = ndimage.white_tophat(image,footprint=footprint) testing.assert_array_equal(new_image, image_expected) @@ -185,10 +185,10 @@ def test_3d_fallback_black_tophat(): image[3, 2:5, 2:5] = 0 image[4, 3:5, 3:5] = 0 - with expected_warnings(['operator.*deprecated']): + with expected_warnings(['operator.*deprecated|\A\Z']): new_image = grey.black_tophat(image) footprint = ndimage.generate_binary_structure(3,1) - with expected_warnings(['operator.*deprecated']): + with expected_warnings(['operator.*deprecated|\A\Z']): image_expected = ndimage.black_tophat(image,footprint=footprint) testing.assert_array_equal(new_image, image_expected) From 2e0deb9595cd80b33ef53833773fb6d9380793b0 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 24 Dec 2014 07:47:05 -0600 Subject: [PATCH 21/28] Fix syntax error and missing | operator --- skimage/exposure/tests/test_exposure.py | 2 +- skimage/morphology/tests/test_grey.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/skimage/exposure/tests/test_exposure.py b/skimage/exposure/tests/test_exposure.py index 6e93d1af..1316ea4e 100644 --- a/skimage/exposure/tests/test_exposure.py +++ b/skimage/exposure/tests/test_exposure.py @@ -211,7 +211,7 @@ def test_adapthist_grayscale(): img = skimage.img_as_float(data.astronaut()) img = rgb2gray(img) img = np.dstack((img, img, img)) - with expected_warnings(['precision loss|non-contiguous input]): + with expected_warnings(['precision loss|non-contiguous input']): adapted = exposure.equalize_adapthist(img, 10, 9, clip_limit=0.01, nbins=128) assert_almost_equal = np.testing.assert_almost_equal diff --git a/skimage/morphology/tests/test_grey.py b/skimage/morphology/tests/test_grey.py index 86ce10f5..911e0c71 100644 --- a/skimage/morphology/tests/test_grey.py +++ b/skimage/morphology/tests/test_grey.py @@ -175,7 +175,7 @@ def test_3d_fallback_white_tophat(): with expected_warnings(['operator.*deprecated|\A\Z']): new_image = grey.white_tophat(image) footprint = ndimage.generate_binary_structure(3,1) - with expected_warnings(['operator.*deprecated\A\Z']): + with expected_warnings(['operator.*deprecated|\A\Z']): image_expected = ndimage.white_tophat(image,footprint=footprint) testing.assert_array_equal(new_image, image_expected) From 23ae57168920ee085d17d86935376e7d1840646c Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 24 Dec 2014 08:49:51 -0600 Subject: [PATCH 22/28] Fix final failing test on Py2.6 build --- skimage/_shared/testing.py | 2 +- skimage/segmentation/tests/test_random_walker.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/skimage/_shared/testing.py b/skimage/_shared/testing.py index d012b8b6..0f556acf 100644 --- a/skimage/_shared/testing.py +++ b/skimage/_shared/testing.py @@ -186,7 +186,7 @@ def setup_test(): Set a random seed """ warnings.simplefilter('default') - from scipy import signal, ndimage, special, optimize, linalg, sparse + from scipy import signal, ndimage, special, optimize, linalg from scipy.io import loadmat from skimage import viewer, filter np.random.seed(0) diff --git a/skimage/segmentation/tests/test_random_walker.py b/skimage/segmentation/tests/test_random_walker.py index 5877a817..d925592c 100644 --- a/skimage/segmentation/tests/test_random_walker.py +++ b/skimage/segmentation/tests/test_random_walker.py @@ -99,7 +99,7 @@ def test_2d_cg_mg(): lx = 70 ly = 100 data, labels = make_2d_syntheticdata(lx, ly) - with expected_warnings(PYAMG_EXPECTED_WARNING): + with expected_warnings('%s|\A\Z' % PYAMG_EXPECTED_WARNING): labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') assert (labels_cg_mg[25:45, 40:60] == 2).all() assert data.shape == labels.shape From bea57315fbcf6d9ba289de7523366b62648b1755 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 24 Dec 2014 09:10:11 -0600 Subject: [PATCH 23/28] Update docstring and fix pyamg warning check --- skimage/_shared/_warnings.py | 13 ++++++++++--- skimage/segmentation/tests/test_random_walker.py | 13 ++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/skimage/_shared/_warnings.py b/skimage/_shared/_warnings.py index ffac12e9..a5fdd4cb 100644 --- a/skimage/_shared/_warnings.py +++ b/skimage/_shared/_warnings.py @@ -84,9 +84,16 @@ def expected_warnings(matching): ----- Uses `all_warnings` to ensure all warnings are raised. Upon exiting, it checks the recorded warnings for the desired matching - string. Raises a warning if the match was not found or an Unexpected - warning is found. You can pass an empty regex as on of the matches - to allow for no matches: "\A\Z". + pattern(s). + Raises a ValueError if any match was not found or an unexpected + warning was raised. + Allows for three types of behaviors: "and", "or", and "optional" matches. + This is done to accomodate different build enviroments or loop conditions + that may produce different warnings. The behaviors can be combined. + If you pass multiple patterns, you get an orderless "and", where all of the + warnings must be raised. + If you use the "|" operator in a pattern, you can catch one of several warnings. + Finally, you can use "|\A\Z" in a pattern to signify it as optional. """ with all_warnings() as w: diff --git a/skimage/segmentation/tests/test_random_walker.py b/skimage/segmentation/tests/test_random_walker.py index d925592c..7b250051 100644 --- a/skimage/segmentation/tests/test_random_walker.py +++ b/skimage/segmentation/tests/test_random_walker.py @@ -2,13 +2,8 @@ import numpy as np from skimage.segmentation import random_walker from skimage.transform import resize from skimage._shared._warnings import expected_warnings -from skimage._shared.version_requirements import is_installed - -if is_installed('pyamg'): - PYAMG_EXPECTED_WARNING = [] -else: - PYAMG_EXPECTED_WARNING = ['pyamg'] +PYAMG_EXPECTED_WARNING = 'pyamg|\A\Z' def make_2d_syntheticdata(lx, ly=None): @@ -99,11 +94,11 @@ def test_2d_cg_mg(): lx = 70 ly = 100 data, labels = make_2d_syntheticdata(lx, ly) - with expected_warnings('%s|\A\Z' % PYAMG_EXPECTED_WARNING): + with expected_warnings([PYAMG_EXPECTED_WARNING]): labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') assert (labels_cg_mg[25:45, 40:60] == 2).all() assert data.shape == labels.shape - with expected_warnings(PYAMG_EXPECTED_WARNING): + with expected_warnings([PYAMG_EXPECTED_WARNING]): full_prob = random_walker(data, labels, beta=90, mode='cg_mg', return_full_prob=True) assert (full_prob[1, 25:45, 40:60] >= @@ -118,7 +113,7 @@ def test_types(): data, labels = make_2d_syntheticdata(lx, ly) data = 255 * (data - data.min()) // (data.max() - data.min()) data = data.astype(np.uint8) - with expected_warnings(PYAMG_EXPECTED_WARNING): + with expected_warnings([PYAMG_EXPECTED_WARNING]): labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') assert (labels_cg_mg[25:45, 40:60] == 2).all() assert data.shape == labels.shape From d760c0addaf4c590a4963df56521b6a955112da2 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 24 Dec 2014 11:20:52 -0600 Subject: [PATCH 24/28] Fix scipy.sparse.sparsetools warning --- skimage/segmentation/tests/test_random_walker.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/skimage/segmentation/tests/test_random_walker.py b/skimage/segmentation/tests/test_random_walker.py index 7b250051..f2207fde 100644 --- a/skimage/segmentation/tests/test_random_walker.py +++ b/skimage/segmentation/tests/test_random_walker.py @@ -94,11 +94,12 @@ def test_2d_cg_mg(): lx = 70 ly = 100 data, labels = make_2d_syntheticdata(lx, ly) - with expected_warnings([PYAMG_EXPECTED_WARNING]): + expected = 'scipy.sparse.sparsetools|%s' % PYAMG_EXPECTED_WARNING + with expected_warnings([expected]): labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') assert (labels_cg_mg[25:45, 40:60] == 2).all() assert data.shape == labels.shape - with expected_warnings([PYAMG_EXPECTED_WARNING]): + with expected_warnings([expected]): full_prob = random_walker(data, labels, beta=90, mode='cg_mg', return_full_prob=True) assert (full_prob[1, 25:45, 40:60] >= From 736f5658bc400d729ac16e7cbad291a528abb830 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 25 Dec 2014 17:08:36 -0600 Subject: [PATCH 25/28] Fix indent in docstring example --- skimage/_shared/_warnings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skimage/_shared/_warnings.py b/skimage/_shared/_warnings.py index a5fdd4cb..78d38fbd 100644 --- a/skimage/_shared/_warnings.py +++ b/skimage/_shared/_warnings.py @@ -78,7 +78,7 @@ def expected_warnings(matching): -------- >>> from skimage import data, img_as_ubyte, img_as_float >>> with expected_warnings(['precision loss']): - ... d = img_as_ubyte(img_as_float(data.coins())) + ... d = img_as_ubyte(img_as_float(data.coins())) Notes ----- From f898bd0209cef3449e7420f4f3e8220d3b228cd2 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 26 Dec 2014 11:26:30 -0600 Subject: [PATCH 26/28] Style fixes --- skimage/_shared/tests/__init__.py | 2 +- skimage/color/tests/__init__.py | 2 +- skimage/data/tests/__init__.py | 2 +- skimage/draw/tests/__init__.py | 2 +- skimage/exposure/tests/__init__.py | 2 +- skimage/feature/tests/__init__.py | 2 +- skimage/filters/rank/tests/__init__.py | 2 +- skimage/filters/rank/tests/test_rank.py | 8 ++++---- skimage/filters/tests/__init__.py | 2 +- skimage/graph/tests/__init__.py | 2 +- skimage/io/tests/__init__.py | 2 +- skimage/measure/tests/__init__.py | 2 +- skimage/measure/tests/test_regionprops.py | 2 +- skimage/morphology/tests/__init__.py | 2 +- skimage/novice/tests/__init__.py | 2 +- skimage/restoration/tests/__init__.py | 2 +- skimage/segmentation/tests/__init__.py | 2 +- skimage/transform/tests/__init__.py | 2 +- skimage/util/tests/__init__.py | 2 +- skimage/viewer/tests/__init__.py | 2 +- 20 files changed, 23 insertions(+), 23 deletions(-) diff --git a/skimage/_shared/tests/__init__.py b/skimage/_shared/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/_shared/tests/__init__.py +++ b/skimage/_shared/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/color/tests/__init__.py b/skimage/color/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/color/tests/__init__.py +++ b/skimage/color/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/data/tests/__init__.py b/skimage/data/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/data/tests/__init__.py +++ b/skimage/data/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/draw/tests/__init__.py b/skimage/draw/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/draw/tests/__init__.py +++ b/skimage/draw/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/exposure/tests/__init__.py b/skimage/exposure/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/exposure/tests/__init__.py +++ b/skimage/exposure/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/feature/tests/__init__.py b/skimage/feature/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/feature/tests/__init__.py +++ b/skimage/feature/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/filters/rank/tests/__init__.py b/skimage/filters/rank/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/filters/rank/tests/__init__.py +++ b/skimage/filters/rank/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/filters/rank/tests/test_rank.py b/skimage/filters/rank/tests/test_rank.py index f491881d..64c3ca97 100644 --- a/skimage/filters/rank/tests/test_rank.py +++ b/skimage/filters/rank/tests/test_rank.py @@ -156,9 +156,9 @@ def test_bitdepth(): for i in range(5): image = np.ones((100, 100), dtype=np.uint16) * 255 * 2 ** i if i > 3: - expected = ["Bitdepth of"] + expected = ["Bitdepth of"] else: - expected = [] + expected = [] with expected_warnings(expected): rank.mean_percentile(image=image, selem=elem, mask=mask, out=out, shift_x=0, shift_y=0, p0=.1, p1=.9) @@ -523,9 +523,9 @@ def test_16bit(): value = 2 ** bitdepth - 1 image[10, 10] = value if bitdepth > 11: - expected = ['Bitdepth of %s' % (bitdepth - 1)] + expected = ['Bitdepth of %s' % (bitdepth - 1)] else: - expected = [] + expected = [] with expected_warnings(expected): assert rank.minimum(image, selem)[10, 10] == 0 assert rank.maximum(image, selem)[10, 10] == value diff --git a/skimage/filters/tests/__init__.py b/skimage/filters/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/filters/tests/__init__.py +++ b/skimage/filters/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/graph/tests/__init__.py b/skimage/graph/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/graph/tests/__init__.py +++ b/skimage/graph/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/io/tests/__init__.py b/skimage/io/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/io/tests/__init__.py +++ b/skimage/io/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/measure/tests/__init__.py b/skimage/measure/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/measure/tests/__init__.py +++ b/skimage/measure/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/measure/tests/test_regionprops.py b/skimage/measure/tests/test_regionprops.py index fdbabad9..5a14aba5 100644 --- a/skimage/measure/tests/test_regionprops.py +++ b/skimage/measure/tests/test_regionprops.py @@ -33,7 +33,7 @@ def test_dtype(): regionprops(np.zeros((10, 10), dtype=np.int)) regionprops(np.zeros((10, 10), dtype=np.uint)) assert_raises((TypeError, RuntimeError), regionprops, - np.zeros((10, 10), dtype=np.double)) + np.zeros((10, 10), dtype=np.double)) def test_ndim(): diff --git a/skimage/morphology/tests/__init__.py b/skimage/morphology/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/morphology/tests/__init__.py +++ b/skimage/morphology/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/novice/tests/__init__.py b/skimage/novice/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/novice/tests/__init__.py +++ b/skimage/novice/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/restoration/tests/__init__.py b/skimage/restoration/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/restoration/tests/__init__.py +++ b/skimage/restoration/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/segmentation/tests/__init__.py b/skimage/segmentation/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/segmentation/tests/__init__.py +++ b/skimage/segmentation/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/transform/tests/__init__.py b/skimage/transform/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/transform/tests/__init__.py +++ b/skimage/transform/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/util/tests/__init__.py b/skimage/util/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/util/tests/__init__.py +++ b/skimage/util/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() diff --git a/skimage/viewer/tests/__init__.py b/skimage/viewer/tests/__init__.py index 9c11267a..3df53221 100644 --- a/skimage/viewer/tests/__init__.py +++ b/skimage/viewer/tests/__init__.py @@ -5,5 +5,5 @@ def setup(): setup_test() -def tearDown(): +def teardown(): teardown_test() From a7a84bbcde86d246b717446b71ade224960941eb Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 26 Dec 2014 20:14:41 -0600 Subject: [PATCH 27/28] Draw the canvas when creating the ax to avoid RuntimeError --- skimage/viewer/utils/core.py | 1 + 1 file changed, 1 insertion(+) diff --git a/skimage/viewer/utils/core.py b/skimage/viewer/utils/core.py index 8aca4e24..242f2de4 100644 --- a/skimage/viewer/utils/core.py +++ b/skimage/viewer/utils/core.py @@ -203,6 +203,7 @@ def figimage(image, scale=1, dpi=None, **kwargs): ax.set_axis_off() ax.imshow(image, **kwargs) + ax.figure.canvas.draw() return fig, ax From ecc582193ad1cda96cd057f2ceb3bcdd1b233120 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 26 Dec 2014 20:55:44 -0600 Subject: [PATCH 28/28] Try using matplotlib cleanup decorator --- skimage/viewer/tests/test_tools.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/skimage/viewer/tests/test_tools.py b/skimage/viewer/tests/test_tools.py index 0805364c..6b923063 100644 --- a/skimage/viewer/tests/test_tools.py +++ b/skimage/viewer/tests/test_tools.py @@ -8,8 +8,8 @@ from skimage.viewer import ImageViewer, viewer_available from skimage.viewer.canvastools import ( LineTool, ThickLineTool, RectangleTool, PaintTool) from skimage.viewer.canvastools.base import CanvasToolBase -from numpy.testing import assert_equal -from numpy.testing.decorators import skipif +from matplotlib.testing.decorators import cleanup + def get_end_points(image): @@ -74,6 +74,7 @@ def do_event(viewer, etype, button=1, xdata=0, ydata=0, key=None): func(event) +@cleanup @skipif(not viewer_available) def test_line_tool(): img = data.camera() @@ -99,6 +100,7 @@ def test_line_tool(): assert_equal(tool.geometry, np.array([[100, 100], [10, 10]])) +@cleanup @skipif(not viewer_available) def test_thick_line_tool(): img = data.camera() @@ -122,6 +124,7 @@ def test_thick_line_tool(): assert_equal(tool.linewidth, 1) +@cleanup @skipif(not viewer_available) def test_rect_tool(): img = data.camera() @@ -150,6 +153,7 @@ def test_rect_tool(): assert_equal(tool.geometry, [10, 100, 10, 100]) +@cleanup @skipif(not viewer_available) def test_paint_tool(): img = data.moon() @@ -183,6 +187,7 @@ def test_paint_tool(): assert_equal(tool.overlay.sum(), 0) +@cleanup @skipif(not viewer_available) def test_base_tool(): img = data.moon()