def test_multi_page_gif(): img = imread(fetch('data/no_time_for_that_tiny.gif')) assert img.shape == (24, 25, 14, 3), img.shape img2 = imread(fetch('data/no_time_for_that_tiny.gif'), img_num=5) assert img2.shape == (25, 14, 3) assert_allclose(img[5], img2)
def test_cmyk(): ref = imread(fetch('data/color.png')) img = Image.open(fetch('data/color.png')) img = img.convert('CMYK') f = NamedTemporaryFile(suffix='.jpg') fname = f.name f.close() img.save(fname) try: img.close() except AttributeError: # `close` not available on PIL pass new = imread(fname) ref_lab = rgb2lab(ref) new_lab = rgb2lab(new) for i in range(3): newi = np.ascontiguousarray(new_lab[:, :, i]) refi = np.ascontiguousarray(ref_lab[:, :, i]) sim = structural_similarity(refi, newi, data_range=refi.max() - refi.min()) assert sim > 0.99
def test_lab2xyz(self): assert_array_almost_equal(lab2xyz(self.lab_array), self.xyz_array, decimal=3) # Test the conversion with the rest of the illuminants. for I in ["A", "B", "C", "d50", "d55", "d65"]: I = I.lower() for obs in ["2", "10", "R"]: obs = obs.lower() fname = f'color/tests/data/lab_array_{I}_{obs}.npy' lab_array_I_obs = np.load(fetch(fname)) assert_array_almost_equal(lab2xyz(lab_array_I_obs, I, obs), self.xyz_array, decimal=3) for I in ["d75", "e"]: fname = f'color/tests/data/lab_array_{I}_2.npy' lab_array_I_obs = np.load(fetch(fname)) assert_array_almost_equal(lab2xyz(lab_array_I_obs, I, "2"), self.xyz_array, decimal=3) # And we include a call to test the exception handling in the code. with pytest.raises(ValueError): lab2xyz(lab_array_I_obs, "NaI", "2") # Not an illuminant with pytest.raises(ValueError): lab2xyz(lab_array_I_obs, "d50", "42") # Not a degree
def test_imread_as_gray(): img = imread(fetch('data/color.png'), as_gray=True) assert img.ndim == 2 assert img.dtype == np.float64 img = imread(fetch('data/camera.png'), as_gray=True) # check that conversion does not happen for a gray image assert np.sctype2char(img.dtype) in np.typecodes['AllInteger']
def test_luv2xyz(self): assert_array_almost_equal(luv2xyz(self.luv_array), self.xyz_array, decimal=3) # Test the conversion with the rest of the illuminants. for I in ["d50", "d55", "d65", "d75"]: for obs in ["2", "10"]: if have_fetch: fname = "color/tests/data/luv_array_{0}_{1}.npy".format( I, obs) luv_array_I_obs = np.load(fetch(fname)) else: fname = "luv_array_{0}_{1}.npy".format(I, obs) luv_array_I_obs = np.load( os.path.join(os.path.dirname(__file__), "data", fname)) assert_array_almost_equal(luv2xyz(luv_array_I_obs, I, obs), self.xyz_array, decimal=3) for I in ["a", "e"]: if have_fetch: fname = "color/tests/data/luv_array_{0}_2.npy".format(I) luv_array_I_obs = np.load(fetch(fname)) else: fname = "luv_array_{0}_2.npy".format(I) luv_array_I_obs = np.load( os.path.join(os.path.dirname(__file__), "data", fname)) assert_array_almost_equal(luv2xyz(luv_array_I_obs, I, "2"), self.xyz_array, decimal=3)
def test_lab2xyz(self): assert_array_almost_equal(lab2xyz(self.lab_array), self.xyz_array, decimal=3) # Test the conversion with the rest of the illuminants. for I in ["d50", "d55", "d65", "d75"]: for obs in ["2", "10"]: fname = "color/tests/data/lab_array_{0}_{1}.npy".format(I, obs) lab_array_I_obs = np.load(fetch(fname)) assert_array_almost_equal(lab2xyz(lab_array_I_obs, I, obs), self.xyz_array, decimal=3) for I in ["a", "e"]: fname = "lab_array_{0}_2.npy".format(I, obs) lab_array_I_obs = np.load(fetch('color/tests/data/' + fname)) assert_array_almost_equal(lab2xyz(lab_array_I_obs, I, "2"), self.xyz_array, decimal=3) # And we include a call to test the exception handling in the code. try: xs = lab2xyz(lab_array_I_obs, "NaI", "2") # Not an illuminant except ValueError: pass try: xs = lab2xyz(lab_array_I_obs, "d50", "42") # Not a degree except ValueError: pass
def test_masked_registration_padfield_data(): """ Masked translation registration should behave like in the original publication """ # Test translated from MATLABimplementation `MaskedFFTRegistrationTest` # file. You can find the source code here: # http://www.dirkpadfield.com/Home/MaskedFFTRegistrationCode.zip shifts = [(75, 75), (-130, 130), (130, 130)] for xi, yi in shifts: fixed_image = imread( fetch('registration/tests/data/OriginalX{:d}Y{:d}.png' ''.format(xi, yi))) moving_image = imread( fetch('registration/tests/data/TransformedX{:d}Y{:d}.png' ''.format(xi, yi))) # Valid pixels are 1 fixed_mask = (fixed_image != 0) moving_mask = (moving_image != 0) # Note that shifts in x and y and shifts in cols and rows shift_y, shift_x = masked_register_translation( fixed_image, moving_image, reference_mask=fixed_mask, moving_mask=moving_mask, overlap_ratio=0.1) # Note: by looking at the test code from Padfield's # MaskedFFTRegistrationCode repository, the # shifts were not xi and yi, but xi and -yi assert_equal((shift_x, shift_y), (-xi, yi))
def test_kidney_3d_multichannel(): """Test that 3D multichannel image of kidney tissue can be loaded. Needs internet connection. """ fetch('data/kidney.tif') kidney = data.kidney() assert kidney.shape == (16, 512, 512, 3)
def test_lily_multichannel(): """Test that microscopy image of lily of the valley can be loaded. Needs internet connection. """ fetch('data/lily.tif') lily = data.lily() assert lily.shape == (922, 922, 4)
def test_eagle(): """ Test that "eagle" image can be loaded. """ # Fetching the data through the testing module will # cause the test to skip if pooch isn't installed. fetch('data/eagle.png') eagle = data.eagle() assert_equal(eagle.ndim, 2) assert_equal(eagle.dtype, np.dtype('uint8'))
def test_skeletonize_output(self): im = imread(fetch("data/bw_text.png"), as_gray=True) # make black the foreground im = (im == 0) result = skeletonize(im) expected = np.load(fetch("data/bw_text_skeleton.npy")) assert_array_equal(result, expected)
def test_failed_temporary_file(monkeypatch, error_class): fetch('data/camera.png') # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = f'file:///{data_path}/camera.png' with monkeypatch.context(): monkeypatch.setattr(tempfile, 'NamedTemporaryFile', _named_tempfile_func(error_class)) with pytest.raises(error_class): io.imread(image_url)
def setup(self): np.random.seed(0) # This image is used along with @test_parallel # to ensure that the same seed is used for each thread. self.image = np.random.rand(25, 25) np.random.seed(0) self.volume = np.random.rand(10, 10, 10) # Set again the seed for the other tests. np.random.seed(0) self.selem = morphology.disk(1) self.selem_3d = morphology.ball(1) self.refs = np.load(fetch('data/rank_filter_tests.npz')) self.refs_3d = np.load(fetch('data/rank_filters_tests_3d.npz'))
def test_wiener(): psf = np.ones((5, 5)) / 25 data = convolve2d(test_img.get(), psf, "same") np.random.seed(0) data += 0.1 * data.std() * np.random.standard_normal(data.shape) psf = cp.asarray(psf) data = cp.asarray(data) deconvolved = restoration.wiener(data, psf, 0.05) if have_fetch: path = fetch("restoration/tests/camera_wiener.npy") else: path = pjoin(dirname(abspath(__file__)), "camera_wiener.npy") cp.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3) _, laplacian = uft.laplacian(2, data.shape) otf = uft.ir2tf(psf, data.shape, is_real=False) deconvolved = restoration.wiener(data, otf, 0.05, reg=laplacian, is_real=False) cp.testing.assert_allclose(cp.real(deconvolved), np.load(path), rtol=1e-3)
def test_imread_file_url(): # tweak data path so that file URI works on both unix and windows. data_path = str(fetch('data/camera.png')) data_path = data_path.replace(os.path.sep, '/') image_url = f'file:///{data_path}' image = io.imread(image_url) assert image.shape == (512, 512)
def test_wiener(dtype): psf = np.ones((5, 5), dtype=dtype) / 25 data = convolve2d(test_img, psf, 'same') np.random.seed(0) data += 0.1 * data.std() * np.random.standard_normal(data.shape) data = data.astype(dtype, copy=False) deconvolved = restoration.wiener(data, psf, 0.05) assert deconvolved.dtype == _supported_float_type(dtype) rtol, atol = _get_rtol_atol(dtype) path = fetch('restoration/tests/camera_wiener.npy') np.testing.assert_allclose(deconvolved, np.load(path), rtol=rtol, atol=atol) _, laplacian = uft.laplacian(2, data.shape) otf = uft.ir2tf(psf, data.shape, is_real=False) assert otf.real.dtype == _supported_float_type(dtype) deconvolved = restoration.wiener(data, otf, 0.05, reg=laplacian, is_real=False) assert deconvolved.real.dtype == _supported_float_type(dtype) np.testing.assert_allclose(np.real(deconvolved), np.load(path), rtol=rtol, atol=atol)
def load_ciede2000_data(): dtype = [ ('pair', int), ('1', int), ('L1', float), ('a1', float), ('b1', float), ('a1_prime', float), ('C1_prime', float), ('h1_prime', float), ('hbar_prime', float), ('G', float), ('T', float), ('SL', float), ('SC', float), ('SH', float), ('RT', float), ('dE', float), ('2', int), ('L2', float), ('a2', float), ('b2', float), ('a2_prime', float), ('C2_prime', float), ('h2_prime', float), ] # note: ciede_test_data.txt contains several intermediate quantities path = fetch('color/tests/ciede2000_test_data.txt') return np.loadtxt(path, dtype=dtype)
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. # The exception type changed from SyntaxError to OSError in PIL 8.2.0, so # allow for either to be raised. with testing.raises((OSError, SyntaxError)): imread(fetch('data/truncated.jpg'))
def load_ciede2000_data(): dtype = [ ("pair", int), ("1", int), ("L1", float), ("a1", float), ("b1", float), ("a1_prime", float), ("C1_prime", float), ("h1_prime", float), ("hbar_prime", float), ("G", float), ("T", float), ("SL", float), ("SC", float), ("SH", float), ("RT", float), ("dE", float), ("2", int), ("L2", float), ("a2", float), ("b2", float), ("a2_prime", float), ("C2_prime", float), ("h2_prime", float), ] # note: ciede_test_data.txt contains several intermediate quantities if have_fetch: path = fetch("color/tests/ciede2000_test_data.txt") else: path = pjoin(dirname(abspath(__file__)), "ciede2000_test_data.txt") return np.loadtxt(path, dtype=dtype)
def test_tifffile_kwarg_passthrough(): img = imread(fetch('data/multipage.tif'), key=[1], multifile=False, multifile_close=True, fastij=True, is_ome=True) assert img.shape == (15, 10), img.shape
def imgs(): use_plugin('pil') paths = [ testing.fetch('data/multipage_rgb.tif'), testing.fetch('data/no_time_for_that_tiny.gif') ] imgs = [ MultiImage(paths[0]), MultiImage(paths[0], conserve_memory=False), MultiImage(paths[1]), MultiImage(paths[1], conserve_memory=False), MultiImage(os.pathsep.join(paths)) ] yield imgs reset_plugins()
def test_gray_morphology(self): if have_fetch: expected = dict(np.load(fetch("data/gray_morph_output.npz"))) else: expected = dict( np.load(os.path.join(data_dir, "gray_morph_output.npz"))) calculated = self._build_expected_output() for k, v in calculated.items(): cp.testing.assert_array_equal(expected[k], v)
def test_xyz2luv(self): assert_array_almost_equal(xyz2luv(self.xyz_array), self.luv_array, decimal=3) # Test the conversion with the rest of the illuminants. for I in ["d50", "d55", "d65", "d75"]: for obs in ["2", "10"]: fname = "color/tests/data/luv_array_{0}_{1}.npy".format(I, obs) luv_array_I_obs = np.load(fetch(fname)) assert_array_almost_equal(luv_array_I_obs, xyz2luv(self.xyz_array, I, obs), decimal=2) for I in ["a", "e"]: fname = "color/tests/data/luv_array_{0}_2.npy".format(I) luv_array_I_obs = np.load(fetch(fname)) assert_array_almost_equal(luv_array_I_obs, xyz2luv(self.xyz_array, I, "2"), decimal=2)
def test_jpg_quality_arg(): chessboard = np.load(fetch('data/chessboard_GRAY_U8.npy')) with temporary_file(suffix='.jpg') as jpg: imsave(jpg, chessboard, quality=95) im = imread(jpg) sim = structural_similarity( chessboard, im, data_range=chessboard.max() - chessboard.min()) assert sim > 0.99
def test_richardson_lucy(): psf = np.ones((5, 5)) / 25 data = convolve2d(test_img, psf, 'same') np.random.seed(0) data += 0.1 * data.std() * np.random.standard_normal(data.shape) deconvolved = restoration.richardson_lucy(data, psf, 5) path = fetch('restoration/tests/camera_rl.npy') np.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3)
def test_3d_vs_fiji(): # generate an image with blobs and compate its skeleton to # the skeleton generated by FIJI img = binary_blobs(32, 0.05, n_dim=3, seed=1234) img = img[:-2, ...] img = img.astype(np.uint8) * 255 img_s = skeletonize(img) img_f = io.imread(fetch("data/_blobs_3d_fiji_skeleton.tif")) assert_equal(img_s, img_f)
def strel_worker(self, fn, func): matlab_masks = np.load(fetch(fn)) k = 0 for arrname in sorted(matlab_masks): expected_mask = matlab_masks[arrname] actual_mask = func(k) if expected_mask.shape == (1,): expected_mask = expected_mask[:, np.newaxis] assert_equal(expected_mask, actual_mask) k = k + 1
def test_unsupervised_wiener(dtype): psf = np.ones((5, 5), dtype=dtype) / 25 data = convolve2d(test_img, psf, 'same') seed = 16829302 # keep old-style RandomState here for compatibility with previously stored # reference data in camera_unsup.npy and camera_unsup2.npy rng = np.random.RandomState(seed) data += 0.1 * data.std() * rng.standard_normal(data.shape) data = data.astype(dtype, copy=False) deconvolved, _ = restoration.unsupervised_wiener(data, psf, random_state=seed) float_type = _supported_float_type(dtype) assert deconvolved.dtype == float_type rtol, atol = _get_rtol_atol(dtype) path = fetch('restoration/tests/camera_unsup.npy') np.testing.assert_allclose(deconvolved, np.load(path), rtol=rtol, atol=atol) _, laplacian = uft.laplacian(2, data.shape) otf = uft.ir2tf(psf, data.shape, is_real=False) assert otf.real.dtype == _supported_float_type(dtype) deconvolved2 = restoration.unsupervised_wiener(data, otf, reg=laplacian, is_real=False, user_params={ "callback": lambda x: None, "max_num_iter": 200, "min_num_iter": 30, }, random_state=seed)[0] assert deconvolved2.real.dtype == float_type path = fetch('restoration/tests/camera_unsup2.npy') np.testing.assert_allclose(np.real(deconvolved2), np.load(path), rtol=rtol, atol=atol)
def test_unsupervised_wiener(): psf = np.ones((5, 5)) / 25 data = convolve2d(test_img, psf, 'same') np.random.seed(0) data += 0.1 * data.std() * np.random.standard_normal(data.shape) deconvolved, _ = restoration.unsupervised_wiener(data, psf) path = fetch('restoration/tests/camera_unsup.npy') np.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3) _, laplacian = uft.laplacian(2, data.shape) otf = uft.ir2tf(psf, data.shape, is_real=False) np.random.seed(0) deconvolved = restoration.unsupervised_wiener( data, otf, reg=laplacian, is_real=False, user_params={"callback": lambda x: None})[0] path = fetch('restoration/tests/camera_unsup2.npy') np.testing.assert_allclose(np.real(deconvolved), np.load(path), rtol=1e-3)
def test_luv2xyz(self): assert_array_almost_equal(luv2xyz(self.luv_array), self.xyz_array, decimal=3) # Test the conversion with the rest of the illuminants. for I in ["A", "B", "C", "d50", "d55", "d65"]: I = I.lower() for obs in ["2", "10", "R"]: obs = obs.lower() fname = f'color/tests/data/luv_array_{I}_{obs}.npy' luv_array_I_obs = np.load(fetch(fname)) assert_array_almost_equal(luv2xyz(luv_array_I_obs, I, obs), self.xyz_array, decimal=3) for I in ["d75", "e"]: fname = f'color/tests/data/luv_array_{I}_2.npy' luv_array_I_obs = np.load(fetch(fname)) assert_array_almost_equal(luv2xyz(luv_array_I_obs, I, "2"), self.xyz_array, decimal=3)