def test_saturation_warning(): rgb_img = np.random.uniform(size=(10, 10, 3)) labels = np.ones((10, 10), dtype=np.int64) with expected_warnings(["saturation must be in range"]): label2rgb(labels, image=rgb_img, bg_label=0, saturation=2) with expected_warnings(["saturation must be in range"]): label2rgb(labels, image=rgb_img, bg_label=0, saturation=-1)
def test_inpaint_biharmonic_2d_color_deprecated(): img = img_as_float(data.astronaut()[:64, :64]) mask = np.zeros(img.shape[:2], dtype=bool) mask[8:16, :16] = 1 img_defect = img * ~mask[..., np.newaxis] mse_defect = mean_squared_error(img, img_defect) # providing multichannel argument positionally also warns channel_warning = "`multichannel` is a deprecated argument" matrix_warning = "the matrix subclass is not the recommended way" with expected_warnings([channel_warning + '|' + matrix_warning]): img_restored = inpaint.inpaint_biharmonic(img_defect, mask, multichannel=True) mse_restored = mean_squared_error(img, img_restored) assert mse_restored < 0.01 * mse_defect # providing multichannel argument positionally also warns channel_warning = "Providing the `multichannel` argument" with expected_warnings([channel_warning + '|' + matrix_warning]): img_restored = inpaint.inpaint_biharmonic(img_defect, mask, True) mse_restored = mean_squared_error(img, img_restored) assert mse_restored < 0.01 * mse_defect
def test_gray_2d_deprecated_multichannel(): rnd = np.random.default_rng(0) img = np.zeros((20, 21)) img[:10, :10] = 0.33 img[10:, :10] = 0.67 img[10:, 10:] = 1.00 img += 0.0033 * rnd.normal(size=img.shape) img[img > 1] = 1 img[img < 0] = 0 with expected_warnings(["`multichannel` is a deprecated argument"]): seg = slic(img, sigma=0, n_segments=4, compactness=1, multichannel=False, convert2lab=False, start_label=0) assert_equal(len(np.unique(seg)), 4) assert_equal(seg.shape, img.shape) assert_equal(seg[:10, :10], 0) assert_equal(seg[10:, :10], 2) assert_equal(seg[:10, 10:], 1) assert_equal(seg[10:, 10:], 3) with expected_warnings(["Providing the `multichannel` argument"]): seg = slic(img, 4, 1, 10, 0, None, False, convert2lab=False, start_label=0)
def test_imageio_flatten(): # a color image is flattened (as_gray in .16) with expected_warnings(['`flatten` has been deprecated']): img = imread(os.path.join(data_dir, 'color.png'), flatten=True) assert img.ndim == 2 assert img.dtype == np.float64 with expected_warnings(['`flatten` has been deprecated']): img = imread(os.path.join(data_dir, 'camera.png'), flatten=True) # check that flattening does not occur for an image that is grey already. assert np.sctype2char(img.dtype) in np.typecodes['AllInteger']
def test_rescale_multichannel_deprecated_multiscale(): x = np.zeros((5, 5, 3), dtype=np.float64) with expected_warnings(["`multichannel` is a deprecated argument"]): scaled = rescale(x, (2, 1), order=0, multichannel=True, anti_aliasing=False, mode='constant') assert scaled.shape == (10, 5, 3) # repeat prior test, but check for positional multichannel _warnings with expected_warnings(["Providing the `multichannel` argument"]): scaled = rescale(x, (2, 1), 0, 'constant', 0, True, False, True, anti_aliasing=False) assert scaled.shape == (10, 5, 3)
def test_greycomatrix_and_greycoprops_deprecations(self): expected = graycomatrix(self.image, [1], [0, np.pi / 2], 4, normed=True, symmetric=True) with expected_warnings(["Function ``greycomatrix``"]): result = greycomatrix(self.image, [1], [0, np.pi / 2], 4, normed=True, symmetric=True) np.testing.assert_array_equal(expected, result) result = np.round(result, 3) dissimilarity_expected = graycoprops(result, 'dissimilarity') with expected_warnings(["Function ``greycoprops``"]): dissimilarity_result = greycoprops(result, 'dissimilarity') np.testing.assert_array_equal( dissimilarity_expected, dissimilarity_result )
def test_returns_empty_labels_and_white_image_when_cannot_fit_shape(): # The circle will never fit this. with expected_warnings(['Could not fit']): image, labels = random_shapes( (10000, 10000), max_shapes=1, min_size=10000, shape='circle') assert len(labels) == 0 assert (image == 255).all()
def test_bool_array_warnings(): img = np.zeros((10, 10), dtype=bool) with expected_warnings(['Input image dtype is bool']): rescale(img, 0.5, anti_aliasing=True) with expected_warnings(['Input image dtype is bool']): resize(img, (5, 5), anti_aliasing=True) with expected_warnings(['Input image dtype is bool']): rescale(img, 0.5, order=1) with expected_warnings(['Input image dtype is bool']): resize(img, (5, 5), order=1) with expected_warnings(['Input image dtype is bool']): warp(img, np.eye(3), order=1)
def test_detrecated_masked_register_translation(): reference_image, moving_image, _ = stereo_motorcycle() ref_mask = np.random.choice( [True, False], reference_image.shape, p=[3 / 4, 1 / 4]) with expected_warnings(["Function ``masked_register_translation``"]): assert_equal(_deprecated(reference_image, moving_image, ref_mask), phase_cross_correlation(reference_image, moving_image, reference_mask=ref_mask))
def test_returns_empty_labels_and_white_image_when_cannot_fit_shape(): # The circle will never fit this. with expected_warnings(['Could not fit']): image, labels = random_shapes((10000, 10000), max_shapes=1, min_size=10000, shape='circle') assert len(labels) == 0 assert (image == 255).all()
def test_save_with_alpha_channel(): # create an image with an alpha channel pic = novice.Picture(array=np.zeros((3, 3, 4))) fd, filename = tempfile.mkstemp(suffix=".png") os.close(fd) with expected_warnings(['is a low contrast']): pic.save(filename) os.unlink(filename)
def test_downsize_anti_aliasing_invalid_stddev(): x = np.zeros((10, 10), dtype=np.float64) with pytest.raises(ValueError): resize(x, (5, 5), order=0, anti_aliasing=True, anti_aliasing_sigma=-1, mode='constant') with expected_warnings(["Anti-aliasing standard deviation greater"]): resize(x, (5, 15), order=0, anti_aliasing=True, anti_aliasing_sigma=(1, 1), mode="reflect") resize(x, (5, 15), order=0, anti_aliasing=True, anti_aliasing_sigma=(0, 1), mode="reflect")
def test_invariant_denoise_color_deprecated(): with expected_warnings(["`multichannel` is a deprecated argument"]): denoised_img_color = _invariant_denoise( noisy_img_color, _denoise_wavelet, denoiser_kwargs=dict(multichannel=True)) denoised_mse = mse(denoised_img_color, test_img_color) original_mse = mse(noisy_img_color, test_img_color) assert_(denoised_mse < original_mse)
def test_shape_index(): square = np.zeros((5, 5)) square[2, 2] = 4 with expected_warnings(['divide by zero', 'invalid value']): s = shape_index(square, sigma=0.1) assert_almost_equal( s, np.array([[np.nan, np.nan, -0.5, np.nan, np.nan], [np.nan, 0, np.nan, 0, np.nan], [-0.5, np.nan, -1, np.nan, -0.5], [np.nan, 0, np.nan, 0, np.nan], [np.nan, np.nan, -0.5, np.nan, np.nan]]))
def test_swirl(dtype): image = img_as_float(checkerboard()).astype(dtype, copy=False) float_dtype = _supported_float_type(dtype) swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'} with expected_warnings(['Bi-quadratic.*bug']): swirled = swirl(image, strength=10, **swirl_params) unswirled = swirl(swirled, strength=-10, **swirl_params) assert swirled.dtype == unswirled.dtype == float_dtype assert np.mean(np.abs(image - unswirled)) < 0.01 swirl_params.pop('mode') with expected_warnings(['Bi-quadratic.*bug']): swirled = swirl(image, strength=10, **swirl_params) unswirled = swirl(swirled, strength=-10, **swirl_params) assert swirled.dtype == unswirled.dtype == float_dtype assert np.mean(np.abs(image[1:-1, 1:-1] - unswirled[1:-1, 1:-1])) < 0.01
def test_list_sigma(): rnd = np.random.default_rng(0) img = np.array([[1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1]], float) img += 0.1 * rnd.normal(size=img.shape) result_sigma = np.array([[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1]], int) with expected_warnings(["Input image is 2D: sigma number of " "elements must be 2"]): seg_sigma = slic(img, n_segments=2, sigma=[1, 50, 1], channel_axis=None, start_label=0) assert_equal(seg_sigma, result_sigma)
def test_multiscale_basic_features(edges, texture): img = np.zeros((20, 20, 3)) img[:10] = 1 img += 0.05 * np.random.randn(*img.shape) with expected_warnings(["`multichannel` is a deprecated argument"]): features = multiscale_basic_features(img, edges=edges, texture=texture, multichannel=True) n_sigmas = 6 intensity = True assert features.shape[-1] == 3 * n_sigmas * (int(intensity) + int(edges) + 2 * int(texture)) assert features.shape[:-1] == img.shape[:-1]
def test_multiscale_basic_features_deprecated_multichannel(): img = np.zeros((10, 10, 5)) img[:10] = 1 img += 0.05 * np.random.randn(*img.shape) n_sigmas = 2 with expected_warnings(["`multichannel` is a deprecated argument"]): features = multiscale_basic_features(img, sigma_min=1, sigma_max=2, multichannel=True) assert features.shape[-1] == 5 * n_sigmas * 4 assert features.shape[:-1] == img.shape[:-1] # repeat prior test, but check for positional multichannel warning with expected_warnings(["Providing the `multichannel` argument"]): multiscale_basic_features(img, True, sigma_min=1, sigma_max=2) assert features.shape[-1] == 5 * n_sigmas * 4 assert features.shape[:-1] == img.shape[:-1] # Consider last axis as spatial dimension features = multiscale_basic_features(img, sigma_min=1, sigma_max=2) assert features.shape[-1] == n_sigmas * 5 assert features.shape[:-1] == img.shape
def test_shape_index(): square = np.zeros((5, 5)) square[2, 2] = 4 with expected_warnings(['divide by zero', 'invalid value']): s = shape_index(square, sigma=0.1) assert_almost_equal( s, np.array([[ np.nan, np.nan, -0.5, np.nan, np.nan], [ np.nan, 0, np.nan, 0, np.nan], [ -0.5, np.nan, -1, np.nan, -0.5], [ np.nan, 0, np.nan, 0, np.nan], [ np.nan, np.nan, -0.5, np.nan, np.nan]]) )
def test_shape_index(): # software floating point arm doesn't raise a warning on divide by zero # https://github.com/scikit-image/scikit-image/issues/3335 square = np.zeros((5, 5)) square[2, 2] = 4 with expected_warnings([r'divide by zero|\A\Z', r'invalid value|\A\Z']): s = shape_index(square, sigma=0.1) assert_almost_equal( s, np.array([[ np.nan, np.nan, -0.5, np.nan, np.nan], [ np.nan, 0, np.nan, 0, np.nan], [ -0.5, np.nan, -1, np.nan, -0.5], [ np.nan, 0, np.nan, 0, np.nan], [ np.nan, np.nan, -0.5, np.nan, np.nan]]) )
def test_shape_index(): # software floating point arm doesn't raise a warning on divide by zero # https://github.com/scikit-image/scikit-image/issues/3335 square = np.zeros((5, 5)) square[2, 2] = 4 with expected_warnings([r'divide by zero|\A\Z', r'invalid value|\A\Z']): s = shape_index(square, sigma=0.1) assert_almost_equal( s, np.array([[np.nan, np.nan, -0.5, np.nan, np.nan], [np.nan, 0, np.nan, 0, np.nan], [-0.5, np.nan, -1, np.nan, -0.5], [np.nan, 0, np.nan, 0, np.nan], [np.nan, np.nan, -0.5, np.nan, np.nan]]))
def test_apply_parallel_rgb(depth, chunks, dtype): cat = data.chelsea().astype(dtype) / 255. func = color.rgb2ycbcr cat_ycbcr_expected = func(cat) with expected_warnings(["`multichannel` is a deprecated argument"]): cat_ycbcr = apply_parallel(func, cat, chunks=chunks, depth=depth, dtype=dtype, multichannel=True) assert_equal(cat_ycbcr.dtype, cat.dtype) assert_array_almost_equal(cat_ycbcr_expected, cat_ycbcr)
def test_inplace_int_deprecated(): """This test is deprecated and will be removed in version 0.19.0. See #4248. """ image = np.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 2, 2, 0], [0, 1, 1, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3], [0, 1, 1, 1, 3, 3, 4]]) with expected_warnings(['The `inplace`']): flood_fill(image, (0, 0), 5, inplace=True) expected = np.array([[5, 5, 5, 5, 5, 5, 5], [5, 1, 1, 5, 2, 2, 5], [5, 1, 1, 5, 2, 2, 5], [1, 5, 5, 5, 5, 5, 3], [5, 1, 1, 1, 3, 3, 4]]) np.testing.assert_array_equal(image, expected)
def test_warp_clip_cval_outside_input_range(order): # Test that clipping behavior considers cval part of the input range x = np.ones((15, 15), dtype=np.float64) # Specify a cval that is outside the input range to check clipping with expected_warnings(['Bi-quadratic.*bug'] if order == 2 else None): outx = rotate(x, 45, order=order, cval=2, resize=True, clip=True) # The corners should be cval for all interpolation orders assert_array_almost_equal([outx[0, 0], outx[0, -1], outx[-1, 0], outx[-1, -1]], 2) # For all interpolation orders other than nearest-neighbor, the clipped # output should have some pixels with values between the input (1) and # cval (2) (i.e., clipping should not set them to 1) if order > 0: assert np.sum(np.less(1, outx) * np.less(outx, 2)) > 0
def test_inplace_float_deprecated(): """This test is deprecated and will be removed in version 0.19.0. See #4248. """ image = np.array( [[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 2, 2, 0], [0, 1, 1, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3], [0, 1, 1, 1, 3, 3, 4]], dtype=np.float32) with expected_warnings(['The `inplace`']): flood_fill(image, (0, 0), 5, inplace=True) expected = np.array( [[5., 5., 5., 5., 5., 5., 5.], [5., 1., 1., 5., 2., 2., 5.], [5., 1., 1., 5., 2., 2., 5.], [1., 5., 5., 5., 5., 5., 3.], [5., 1., 1., 1., 3., 3., 4.]], dtype=np.float32) np.testing.assert_allclose(image, expected)
def test_warp_clip_cval_not_used(order): # Test that clipping does not consider cval part of the input range if it # is not used in the output image x = np.ones((15, 15), dtype=np.float64) x[5:-5, 5:-5] = 2 # Transform the image by stretching it out by one pixel on each side so # that cval will not actually be used transform = AffineTransform(scale=15/(15+2), translation=(1, 1)) with expected_warnings(['Bi-quadratic.*bug'] if order == 2 else None): outx = warp(x, transform, mode='constant', order=order, cval=0, clip=True) # At higher orders of interpolation, the transformed image has overshoots # beyond the input range that should be clipped to the range 1 to 2. Even # though cval=0, the minimum value of the clipped output image should be # 1 and not affected by the unused cval. assert_array_almost_equal(outx.min(), 1)
def test_h_minima_float_h(self): """specific tests for h-minima float h parameter""" data = np.array([[4, 4, 4, 4, 4], [4, 1, 1, 1, 4], [4, 1, 0, 1, 4], [4, 1, 1, 1, 4], [4, 4, 4, 4, 4]], dtype=np.uint8) h_vals = np.linspace(1.0, 2.0, 100) failures = 0 for h in h_vals: if h % 1 != 0: msgs = ['possible precision loss converting image'] else: msgs = [] with expected_warnings(msgs): minima = extrema.h_minima(data, h) if (minima[2, 2] == 0): failures += 1 assert (failures == 0)
def test_match_histograms(self, image, reference, multichannel): """Assert that pdf of matched image is close to the reference's pdf for all channels and all values of matched""" with expected_warnings(["`multichannel` is a deprecated argument"]): matched = exposure.match_histograms(image, reference, multichannel=multichannel) matched_pdf = self._calculate_image_empirical_pdf(matched) reference_pdf = self._calculate_image_empirical_pdf(reference) for channel in range(len(matched_pdf)): reference_values, reference_quantiles = reference_pdf[channel] matched_values, matched_quantiles = matched_pdf[channel] for i, matched_value in enumerate(matched_values): closest_id = ( np.abs(reference_values - matched_value) ).argmin() assert_almost_equal(matched_quantiles[i], reference_quantiles[closest_id], decimal=1)
def test_empty_image(): image = np.zeros((6, 6), dtype=bool) with expected_warnings(['entirely zero']): assert_array_equal(convex_hull_image(image), image)
def test_selem_kwarg_deprecation(function): img = np.zeros((16, 16)) args = (20,) if function.startswith('h_') else () with expected_warnings(["`selem` is a deprecated argument name"]): getattr(extrema, function)(img, *args, selem=np.ones((3, 3)))
def test_max_iter_kwarg_deprecation(): img = np.zeros((20, 21, 3)) with expected_warnings(["`max_iter` is a deprecated argument"]): slic(img, max_iter=10, start_label=0)
def test_deprecated_import(): msg = "Importing from skimage.morphology.greyreconstruct is deprecated." with testing.expected_warnings([msg]): from skimage.morphology.greyreconstruct import reconstruction
def montage2d(*args, **kwargs): with expected_warnings(['deprecated']): return montage2d_deprecated(*args, **kwargs)
def test_border_warning(func): img = rgb2gray(cp.asarray(retina()[300:500, 700:900])) with expected_warnings(["implicitly used 'constant' as the border mode"]): func(img, sigmas=[1])