def test_wavelet_denoising_levels(): rstate = np.random.RandomState(1234) ndim = 2 N = 256 wavelet = 'db1' # Generate a very simple test image img = 0.2*np.ones((N, )*ndim) img[[slice(5, 13), ] * ndim] = 0.8 sigma = 0.1 noisy = img + sigma * rstate.randn(*(img.shape)) noisy = np.clip(noisy, 0, 1) denoised = restoration.denoise_wavelet(noisy, wavelet=wavelet) denoised_1 = restoration.denoise_wavelet(noisy, wavelet=wavelet, wavelet_levels=1) psnr_noisy = compare_psnr(img, noisy) psnr_denoised = compare_psnr(img, denoised) psnr_denoised_1 = compare_psnr(img, denoised_1) # multi-level case should outperform single level case assert_(psnr_denoised > psnr_denoised_1 > psnr_noisy) # invalid number of wavelet levels results in a ValueError max_level = pywt.dwt_max_level(np.min(img.shape), pywt.Wavelet(wavelet).dec_len) with testing.raises(ValueError): restoration.denoise_wavelet( noisy, wavelet=wavelet, wavelet_levels=max_level+1) with testing.raises(ValueError): restoration.denoise_wavelet( noisy, wavelet=wavelet, wavelet_levels=-1)
def test_throws_when_intensity_range_out_of_range(): with testing.raises(ValueError): random_shapes((1000, 1234), max_shapes=1, multichannel=False, intensity_range=(0, 256)) with testing.raises(ValueError): random_shapes((2, 2), max_shapes=1, intensity_range=((-1, 255),))
def test_chan_vese_incorrect_level_set(): img = np.zeros((10, 10)) ls = np.zeros((10, 9)) with testing.raises(ValueError): chan_vese(img, mu=0.0, init_level_set=ls) with testing.raises(ValueError): chan_vese(img, mu=0.0, init_level_set="a")
def test_dtype(): regionprops(np.zeros((10, 10), dtype=np.int)) regionprops(np.zeros((10, 10), dtype=np.uint)) with testing.raises(TypeError): regionprops(np.zeros((10, 10), dtype=np.float)) with testing.raises(TypeError): regionprops(np.zeros((10, 10), dtype=np.double))
def test_invalid_block_size(): image = np.arange(4 * 6).reshape(4, 6) with testing.raises(ValueError): block_reduce(image, [1, 2, 3]) with testing.raises(ValueError): block_reduce(image, [1, 0.5])
def test_localvar(): seed = 42 data = np.zeros((128, 128)) + 0.5 local_vars = np.zeros((128, 128)) + 0.001 local_vars[:64, 64:] = 0.1 local_vars[64:, :64] = 0.25 local_vars[64:, 64:] = 0.45 data_gaussian = random_noise(data, mode='localvar', seed=seed, local_vars=local_vars, clip=False) assert 0. < data_gaussian[:64, :64].var() < 0.002 assert 0.095 < data_gaussian[:64, 64:].var() < 0.105 assert 0.245 < data_gaussian[64:, :64].var() < 0.255 assert 0.445 < data_gaussian[64:, 64:].var() < 0.455 # Ensure local variance bounds checking works properly bad_local_vars = np.zeros_like(data) with testing.raises(ValueError): random_noise(data, mode='localvar', seed=seed, local_vars=bad_local_vars) bad_local_vars += 0.1 bad_local_vars[0, 0] = -1 with testing.raises(ValueError): random_noise(data, mode='localvar', seed=seed, local_vars=bad_local_vars)
def test_subdivide_polygon(): new_square1 = square new_square2 = square[:-1] new_square3 = square[:-1] # test iterative subdvision for _ in range(10): square1, square2, square3 = new_square1, new_square2, new_square3 # test different B-Spline degrees for degree in range(1, 7): mask_len = len(_SUBDIVISION_MASKS[degree][0]) # test circular new_square1 = subdivide_polygon(square1, degree) assert_array_equal(new_square1[-1], new_square1[0]) assert_equal(new_square1.shape[0], 2 * square1.shape[0] - 1) # test non-circular new_square2 = subdivide_polygon(square2, degree) assert_equal(new_square2.shape[0], 2 * (square2.shape[0] - mask_len + 1)) # test non-circular, preserve_ends new_square3 = subdivide_polygon(square3, degree, True) assert_equal(new_square3[0], square3[0]) assert_equal(new_square3[-1], square3[-1]) assert_equal(new_square3.shape[0], 2 * (square3.shape[0] - mask_len + 2)) # not supported B-Spline degree with testing.raises(ValueError): subdivide_polygon(square, 0) with testing.raises(ValueError): subdivide_polygon(square, 8)
def test_float_out_of_range(): too_high = np.array([2], dtype=np.float32) with testing.raises(ValueError): img_as_int(too_high) too_low = np.array([-2], dtype=np.float32) with testing.raises(ValueError): img_as_int(too_low)
def test_NRMSE_errors(): x = np.ones(4) # shape mismatch with testing.raises(ValueError): compare_nrmse(x[:-1], x) # invalid normalization name with testing.raises(ValueError): compare_nrmse(x, x, 'foo')
def test_rescale_invalid_scale(): x = np.zeros((10, 10, 3)) with testing.raises(ValueError): rescale(x, (2, 2), multichannel=False, anti_aliasing=False, mode='constant') with testing.raises(ValueError): rescale(x, (2, 2, 2), multichannel=True, anti_aliasing=False, mode='constant')
def test_geometric_tform(): tform = GeometricTransform() with testing.raises(NotImplementedError): tform(0) with testing.raises(NotImplementedError): tform.inverse(0) with testing.raises(NotImplementedError): tform.__add__(0)
def test_imsave_incorrect_dimension(): with temporary_file(suffix='.png') as fname: with testing.raises(ValueError): with expected_warnings([fname + ' is a low contrast image']): imsave(fname, np.zeros((2, 3, 3, 1))) with testing.raises(ValueError): with expected_warnings([fname + ' is a low contrast image']): imsave(fname, np.zeros((2, 3, 2)))
def test_morphsnakes_incorrect_ndim(): img = np.zeros((4, 4, 4, 4)) ls = np.zeros((4, 4, 4, 4)) with testing.raises(ValueError): morphological_chan_vese(img, iterations=1, init_level_set=ls) with testing.raises(ValueError): morphological_geodesic_active_contour(img, iterations=1, init_level_set=ls)
def test_invalid_seed(): seed = np.ones((5, 5)) mask = np.ones((5, 5)) with testing.raises(ValueError): reconstruction(seed * 2, mask, method='dilation') with testing.raises(ValueError): reconstruction(seed * 0.5, mask, method='erosion')
def test_bad_input(): img = np.zeros((10, 10)) x = np.linspace(5, 424, 100) y = np.linspace(136, 50, 100) init = np.array([x, y]).T with testing.raises(ValueError): active_contour(img, init, bc='wrong') with testing.raises(ValueError): active_contour(img, init, max_iterations=-15)
def test_invalid_input(): with testing.raises(ValueError): unwrap_phase(np.zeros([])) with testing.raises(ValueError): unwrap_phase(np.zeros((1, 1, 1, 1))) with testing.raises(ValueError): unwrap_phase(np.zeros((1, 1)), 3 * [False]) with testing.raises(ValueError): unwrap_phase(np.zeros((1, 1)), 'False')
def test_unwrap_1d(): image = np.linspace(0, 10 * np.pi, 100) check_unwrap(image) # Masked arrays are not allowed in 1D with testing.raises(ValueError): check_unwrap(image, True) # wrap_around is not allowed in 1D with testing.raises(ValueError): unwrap_phase(image, True, seed=0)
def test_negative_sigma(): a = np.zeros((3, 3)) a[1, 1] = 1. with testing.raises(ValueError): gaussian(a, sigma=-1.0) with testing.raises(ValueError): gaussian(a, sigma=[-1.0, 1.0]) with testing.raises(ValueError): gaussian(a, sigma=np.asarray([-1.0, 1.0]))
def test_prepare_grayscale_input_2D(): with testing.raises(ValueError): _prepare_grayscale_input_2D(np.zeros((3, 3, 3))) with testing.raises(ValueError): _prepare_grayscale_input_2D(np.zeros((3, 1))) with testing.raises(ValueError): _prepare_grayscale_input_2D(np.zeros((3, 1, 1))) img = _prepare_grayscale_input_2D(np.zeros((3, 3))) img = _prepare_grayscale_input_2D(np.zeros((3, 3, 1))) img = _prepare_grayscale_input_2D(np.zeros((1, 3, 3)))
def test_ransac_invalid_input(): with testing.raises(ValueError): ransac(np.zeros((10, 2)), None, min_samples=2, residual_threshold=0, max_trials=-1) with testing.raises(ValueError): ransac(np.zeros((10, 2)), None, min_samples=2, residual_threshold=0, stop_probability=-1) with testing.raises(ValueError): ransac(np.zeros((10, 2)), None, min_samples=2, residual_threshold=0, stop_probability=1.01)
def test_invalid_selem(): seed = np.ones((5, 5)) mask = np.ones((5, 5)) with testing.raises(ValueError): reconstruction(seed, mask, selem=np.ones((4, 4))) with testing.raises(ValueError): reconstruction(seed, mask, selem=np.ones((3, 4))) reconstruction(seed, mask, selem=np.ones((3, 3)))
def test_wrong_input(): # Dimensionality mismatch image = np.ones((5, 5, 1)) template = np.ones((5, 5)) with testing.raises(ValueError): register_translation(template, image) # Size mismatch image = np.ones((5, 5)) template = np.ones((4, 4)) with testing.raises(ValueError): register_translation(template, image)
def test_getitem(self): num = len(self.images) for i in range(-num, num): assert type(self.images[i]) is np.ndarray assert_allclose(self.images[0], self.images[-num]) def return_img(n): return self.images[n] with testing.raises(IndexError): return_img(num) with testing.raises(IndexError): return_img(-num - 1)
def test_zero_image_size(): with testing.raises(ValueError): warp(np.zeros(0), SimilarityTransform()) with testing.raises(ValueError): warp(np.zeros((0, 10)), SimilarityTransform()) with testing.raises(ValueError): warp(np.zeros((10, 0)), SimilarityTransform()) with testing.raises(ValueError): warp(np.zeros((10, 10, 0)), SimilarityTransform())
def test_invalid_input(): img, mask = np.zeros([]), np.zeros([]) with testing.raises(ValueError): inpaint.inpaint_biharmonic(img, mask) img, mask = np.zeros((2, 2)), np.zeros((4, 1)) with testing.raises(ValueError): inpaint.inpaint_biharmonic(img, mask) img = np.ma.array(np.zeros((2, 2)), mask=[[0, 0], [0, 0]]) mask = np.zeros((2, 2)) with testing.raises(TypeError): inpaint.inpaint_biharmonic(img, mask)
def test_line_model_nd_invalid_input(): with testing.raises(AssertionError): LineModelND().predict_x(np.zeros(1)) with testing.raises(AssertionError): LineModelND().predict_y(np.zeros(1)) with testing.raises(ValueError): LineModelND().predict_x(np.zeros(1), np.zeros(1)) with testing.raises(AssertionError): LineModelND().predict_y(np.zeros(1)) with testing.raises(ValueError): LineModelND().predict_y(np.zeros(1), np.zeros(1)) with testing.raises(ValueError): LineModelND().estimate(np.empty((1, 3))) with testing.raises(AssertionError): LineModelND().residuals(np.empty((1, 3))) data = np.empty((1, 2)) with testing.raises(ValueError): LineModelND().estimate(data)
def test_wrong_input(): image = np.ones((5, 5, 1)) template = np.ones((3, 3)) with testing.raises(ValueError): match_template(template, image) image = np.ones((5, 5)) template = np.ones((3, 3, 2)) with testing.raises(ValueError): match_template(template, image) image = np.ones((5, 5, 3, 3)) template = np.ones((3, 3, 2)) with testing.raises(ValueError): match_template(template, image)
def test_getitem(self): for img in self.imgs: num = len(img) for i in range(-num, num): assert type(img[i]) is np.ndarray assert_allclose(img[0], img[-num]) with testing.raises(AssertionError): assert_allclose(img[0], img[1]) with testing.raises(IndexError): img[num] with testing.raises(IndexError): img[-num - 1]
def test_ssim_multichannel(): N = 100 X = (np.random.rand(N, N) * 255).astype(np.uint8) Y = (np.random.rand(N, N) * 255).astype(np.uint8) S1 = ssim(X, Y, win_size=3) # replicate across three channels. should get identical value Xc = np.tile(X[..., np.newaxis], (1, 1, 3)) Yc = np.tile(Y[..., np.newaxis], (1, 1, 3)) S2 = ssim(Xc, Yc, multichannel=True, win_size=3) assert_almost_equal(S1, S2) # full case should return an image as well m, S3 = ssim(Xc, Yc, multichannel=True, full=True) assert_equal(S3.shape, Xc.shape) # gradient case m, grad = ssim(Xc, Yc, multichannel=True, gradient=True) assert_equal(grad.shape, Xc.shape) # full and gradient case m, grad, S3 = ssim(Xc, Yc, multichannel=True, full=True, gradient=True) assert_equal(grad.shape, Xc.shape) assert_equal(S3.shape, Xc.shape) # fail if win_size exceeds any non-channel dimension with testing.raises(ValueError): ssim(Xc, Yc, win_size=7, multichannel=False)
def test_invalid_input(): # size mismatch X = np.zeros((9, 9), dtype=np.double) Y = np.zeros((8, 8), dtype=np.double) with testing.raises(ValueError): ssim(X, Y) # win_size exceeds image extent with testing.raises(ValueError): ssim(X, X, win_size=X.shape[0] + 1) # some kwarg inputs must be non-negative with testing.raises(ValueError): ssim(X, X, K1=-0.1) with testing.raises(ValueError): ssim(X, X, K2=-0.1) with testing.raises(ValueError): ssim(X, X, sigma=-1.0)
def test_check_nD(): z = np.random.random(200**2).reshape((200, 200)) x = z[10:30, 30:10] with testing.raises(ValueError): check_nD(x, 2)
def test_mode_not_set(self): arr = np.arange(30).reshape(5, 6) with testing.raises(TypeError): pad(arr, 4)
def test_float(self): arr = np.arange(30) with testing.raises(TypeError): pad(arr, ((-2.1, 3), (3, 2))) with testing.raises(TypeError): pad(arr, np.array(((-2.1, 3), (3, 2))))
def test_no_descriptors_extracted_orb(): img = np.ones((128, 128)) detector_extractor = ORB() with testing.raises(RuntimeError): detector_extractor.detect_and_extract(img)
def test_invalid(): with testing.raises(ValueError): warp(np.ones((4, 3, 3, 3)), SimilarityTransform())
def test_color_image_unsupported_error(): """Brief descriptors can be evaluated on gray-scale images only.""" img = np.zeros((20, 20, 3)) keypoints = np.asarray([[7, 5], [11, 13]]) with testing.raises(ValueError): BRIEF().extract(img, keypoints)
def test_li_negative_inital_guess(): coins = data.coins() with testing.raises(ValueError): result = threshold_li(coins, initial_guess=-5)
def test_window_invalid_shape(): with raises(ValueError): window(10, shape=(-5, 10)) with raises(ValueError): window(10, shape=(1.3, 2.0))
def test_unsupported_mode(): with testing.raises(ValueError): BRIEF(mode='foobar')
def test_throws_when_min_pixel_intensity_out_of_range(): with testing.raises(ValueError): random_shapes((1000, 1234), max_shapes=1, min_pixel_intensity=256) with testing.raises(ValueError): random_shapes((2, 2), max_shapes=1, min_pixel_intensity=-1)
def test_bad_mode(): data = np.zeros((64, 64)) with testing.raises(KeyError): random_noise(data, 'perlin')
def test_invalid_input(): with testing.raises(ValueError): find_contours(r, 0.5, 'foo', 'bar') with testing.raises(ValueError): find_contours(r[..., None], 0.5)
def test_nd(self): x = np.ones((1, 2, 3, 4)) with testing.raises(NotImplementedError): label(x)
def test_moments_normalized_invalid(): with testing.raises(ValueError): moments_normalized(np.zeros((3, 3)), 3) with testing.raises(ValueError): moments_normalized(np.zeros((3, 3)), 4)
def test_otsu_one_color_image(): img = np.ones((10, 10), dtype=np.uint8) with testing.raises(ValueError): threshold_otsu(img)
def test_stack_non_array(): with testing.raises(ValueError): io.push([[1, 2, 3]])
def test_rescale_invalid_scale(): x = np.zeros((10, 10, 3)) with testing.raises(ValueError): rescale(x, (2, 2), multichannel=False) with testing.raises(ValueError): rescale(x, (2, 2, 2), multichannel=True)
def test_complex(self): arr = np.arange(30) with testing.raises(TypeError): pad(arr, complex(1, -1)) with testing.raises(TypeError): pad(arr, np.array(complex(1, -1)))
sigma = 25. noisy = x + sigma * rstate.randn(*x.shape) noisy = np.clip(noisy, x.min(), x.max()) noisy = noisy.astype(x.dtype) multichannel = x.shape[-1] == 3 if estimate_sigma: sigma_est = restoration.estimate_sigma(noisy, multichannel=multichannel) else: sigma_est = None if convert2ycbcr and not multichannel: # YCbCr requires multichannel == True with testing.raises(ValueError): denoised = restoration.denoise_wavelet(noisy, sigma=sigma_est, wavelet='sym4', multichannel=multichannel, convert2ycbcr=convert2ycbcr, rescale_sigma=True) return denoised = restoration.denoise_wavelet(noisy, sigma=sigma_est, wavelet='sym4', multichannel=multichannel, convert2ycbcr=convert2ycbcr, rescale_sigma=True)
def test_conserve_memory_property(imgs): for img in imgs: assert isinstance(img.conserve_memory, bool) with testing.raises(AttributeError): img.conserve_memory = True
def test_check_wrong_pad_amount(self): arr = np.arange(30) arr = np.reshape(arr, (6, 5)) kwargs = dict(mode='mean', stat_length=(3, )) with testing.raises(TypeError): pad(arr, ((2, 3, 4), (3, 2)), **kwargs)
def test_denoise_bilateral_3d_grayscale(): img = np.ones((50, 50, 3)) with testing.raises(ValueError): restoration.denoise_bilateral(img, multichannel=False)
def test_str(self): arr = np.arange(30) with testing.raises(TypeError): pad(arr, 'foo') with testing.raises(TypeError): pad(arr, np.array('foo'))
def test_denoise_bilateral_multidimensional(): img = np.ones((10, 10, 10, 10)) with testing.raises(ValueError): restoration.denoise_bilateral(img, multichannel=False) with testing.raises(ValueError): restoration.denoise_bilateral(img, multichannel=True)
def test_malformed_pad_amount2(self): arr = np.arange(30).reshape(5, 6) with testing.raises(ValueError): pad(arr, ((3, 4, 5), (0, 1, 2)), mode='constant')
def test_denoise_nl_means_wrong_dimension(): img = np.zeros((5, 5, 5, 5)) with testing.raises(NotImplementedError): restoration.denoise_nl_means(img, multichannel=True)
def test_wavelet_invalid_method(): with testing.raises(ValueError): restoration.denoise_wavelet(np.ones(16), method='Unimplemented', rescale_sigma=True)
def test_cycle_spinning_multichannel(rescale_sigma): sigma = 0.1 rstate = np.random.RandomState(1234) for multichannel in True, False: if multichannel: img = astro # can either omit or be 0 along the channels axis valid_shifts = [1, (0, 1), (1, 0), (1, 1), (1, 1, 0)] # can either omit or be 1 on channels axis. valid_steps = [1, 2, (1, 2), (1, 2, 1)] # too few or too many shifts or non-zero shift on channels invalid_shifts = [(1, 1, 2), (1, ), (1, 1, 0, 1)] # too few or too many shifts or any shifts <= 0 invalid_steps = [(1, ), (1, 1, 1, 1), (0, 1), (-1, -1)] else: img = astro_gray valid_shifts = [1, (0, 1), (1, 0), (1, 1)] valid_steps = [1, 2, (1, 2)] invalid_shifts = [(1, 1, 2), (1, )] invalid_steps = [(1, ), (1, 1, 1), (0, 1), (-1, -1)] noisy = img.copy() + 0.1 * rstate.randn(*(img.shape)) denoise_func = restoration.denoise_wavelet func_kw = dict(sigma=sigma, multichannel=multichannel, rescale_sigma=rescale_sigma) # max_shifts=0 is equivalent to just calling denoise_func with expected_warnings( [PYWAVELET_ND_INDEXING_WARNING, DASK_NOT_INSTALLED_WARNING]): dn_cc = restoration.cycle_spin(noisy, denoise_func, max_shifts=0, func_kw=func_kw, multichannel=multichannel) dn = denoise_func(noisy, **func_kw) assert_equal(dn, dn_cc) # denoising with cycle spinning will give better PSNR than without for max_shifts in valid_shifts: with expected_warnings( [PYWAVELET_ND_INDEXING_WARNING, DASK_NOT_INSTALLED_WARNING]): dn_cc = restoration.cycle_spin(noisy, denoise_func, max_shifts=max_shifts, func_kw=func_kw, multichannel=multichannel) psnr = peak_signal_noise_ratio(img, dn) psnr_cc = peak_signal_noise_ratio(img, dn_cc) assert_(psnr_cc > psnr) for shift_steps in valid_steps: with expected_warnings( [PYWAVELET_ND_INDEXING_WARNING, DASK_NOT_INSTALLED_WARNING]): dn_cc = restoration.cycle_spin(noisy, denoise_func, max_shifts=2, shift_steps=shift_steps, func_kw=func_kw, multichannel=multichannel) psnr = peak_signal_noise_ratio(img, dn) psnr_cc = peak_signal_noise_ratio(img, dn_cc) assert_(psnr_cc > psnr) for max_shifts in invalid_shifts: with testing.raises(ValueError): dn_cc = restoration.cycle_spin(noisy, denoise_func, max_shifts=max_shifts, func_kw=func_kw, multichannel=multichannel) for shift_steps in invalid_steps: with testing.raises(ValueError): dn_cc = restoration.cycle_spin(noisy, denoise_func, max_shifts=2, shift_steps=shift_steps, func_kw=func_kw, multichannel=multichannel)
def test_shape_mismatch(): image = np.ones((3, 3)) label = np.ones((2, 2)) with testing.raises(ValueError): label2rgb(image, label)
def test_imageio_truncated_jpg(): # imageio>2.0 uses Pillow / PIL to try and load the file. # Oddly, PIL explicitly raises a SyntaxError when the file read fails. with testing.raises(SyntaxError): imread(os.path.join(data_dir, 'truncated.jpg'))