using for loop to install conda package

This commit is contained in:
ton
2023-04-16 11:03:27 +07:00
parent 49da9f29c1
commit 0c2b34d6f8
12168 changed files with 2656238 additions and 1 deletions

View File

@@ -0,0 +1,154 @@
import os
import numpy as np
import imageio
from skimage import data_dir
from skimage.io.collection import ImageCollection, MultiImage, alphanumeric_key
from skimage.io import reset_plugins
from skimage._shared import testing
from skimage._shared.testing import assert_equal, assert_allclose, fetch
import pytest
try:
has_pooch = True
except ModuleNotFoundError:
has_pooch = False
def test_string_split():
test_string = 'z23a'
test_str_result = ['z', 23, 'a']
assert_equal(alphanumeric_key(test_string), test_str_result)
def test_string_sort():
filenames = ['f9.10.png', 'f9.9.png', 'f10.10.png', 'f10.9.png',
'e9.png', 'e10.png', 'em.png']
expected_filenames = ['e9.png', 'e10.png', 'em.png', 'f9.9.png',
'f9.10.png', 'f10.9.png', 'f10.10.png']
sorted_filenames = sorted(filenames, key=alphanumeric_key)
assert_equal(expected_filenames, sorted_filenames)
def test_imagecollection_input():
"""Test function for ImageCollection. The new behavior (implemented
in 0.16) allows the `pattern` argument to accept a list of strings
as the input.
Notes
-----
If correct, `images` will receive three images.
"""
# Ensure that these images are part of the legacy datasets
# this means they will always be available in the user's install
# regardless of the availability of pooch
pattern = [os.path.join(data_dir, pic)
for pic in ['coffee.png',
'chessboard_GRAY.png',
'rocket.jpg']]
images = ImageCollection(pattern)
assert len(images) == 3
class TestImageCollection():
pattern = [os.path.join(data_dir, pic)
for pic in ['brick.png', 'color.png']]
pattern_matched = [os.path.join(data_dir, pic)
for pic in ['brick.png', 'moon.png']]
def setup_method(self):
reset_plugins()
# Generic image collection with images of different shapes.
self.images = ImageCollection(self.pattern)
# Image collection with images having shapes that match.
self.images_matched = ImageCollection(self.pattern_matched)
# Same images as a collection of frames
self.frames_matched = MultiImage(self.pattern_matched)
def test_len(self):
assert len(self.images) == 2
def test_getitem(self):
num = len(self.images)
for i in range(-num, num):
assert isinstance(self.images[i], 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_slicing(self):
assert type(self.images[:]) is ImageCollection
assert len(self.images[:]) == 2
assert len(self.images[:1]) == 1
assert len(self.images[1:]) == 1
assert_allclose(self.images[0], self.images[:1][0])
assert_allclose(self.images[1], self.images[1:][0])
assert_allclose(self.images[1], self.images[::-1][0])
assert_allclose(self.images[0], self.images[::-1][1])
def test_files_property(self):
assert isinstance(self.images.files, list)
def set_files(f):
self.images.files = f
with testing.raises(AttributeError):
set_files('newfiles')
@pytest.mark.skipif(not has_pooch, reason="needs pooch to download data")
def test_custom_load_func_sequence(self):
filename = fetch('data/no_time_for_that_tiny.gif')
def reader(frameno):
vid = imageio.get_reader(filename)
return vid.get_data(frameno)
ic = ImageCollection(range(24), load_func=reader)
# the length of ic should be that of the given load_pattern sequence
assert len(ic) == 24
# GIF file has frames of size 25x14 with 4 channels (RGBA)
assert ic[0].shape == (25, 14, 4)
@pytest.mark.skipif(not has_pooch, reason="needs pooch to download data")
def test_custom_load_func_w_kwarg(self):
load_pattern = fetch('data/no_time_for_that_tiny.gif')
def load_fn(f, step):
vid = imageio.get_reader(f)
seq = [v for v in vid.iter_data()]
return seq[::step]
ic = ImageCollection(load_pattern, load_func=load_fn, step=3)
# Each file should map to one image (array).
assert len(ic) == 1
# GIF file has 24 frames, so 24 / 3 equals 8.
assert len(ic[0]) == 8
def test_custom_load_func(self):
def load_fn(x):
return x
ic = ImageCollection(os.pathsep.join(self.pattern), load_func=load_fn)
assert_equal(ic[0], self.pattern[0])
def test_concatenate(self):
array = self.images_matched.concatenate()
expected_shape = (len(self.images_matched),) + self.images[0].shape
assert_equal(array.shape, expected_shape)
def test_concatenate_mismatched_image_shapes(self):
with testing.raises(ValueError):
self.images.concatenate()
def test_multiimage_imagecollection(self):
assert_equal(self.images_matched[0], self.frames_matched[0])
assert_equal(self.images_matched[1], self.frames_matched[1])

View File

@@ -0,0 +1,32 @@
import numpy as np
import skimage.io as io
from skimage._shared import testing
testing.pytest.importorskip('astropy')
def test_fits_plugin_import():
# Make sure we get an import exception if Astropy isn't there
# (not sure how useful this is, but it ensures there isn't some other
# error when trying to load the plugin)
try:
io.use_plugin('fits')
except ImportError:
raise()
def teardown():
io.reset_plugins()
def _same_ImageCollection(collection1, collection2):
"""
Ancillary function to compare two ImageCollection objects, checking that
their constituent arrays are equal.
"""
if len(collection1) != len(collection2):
return False
for ext1, ext2 in zip(collection1, collection2):
if not np.all(ext1 == ext2):
return False
return True

View File

@@ -0,0 +1,25 @@
import numpy as np
from skimage.io._plugins._histograms import histograms
from skimage._shared.testing import assert_array_equal, assert_equal, TestCase
class TestHistogram(TestCase):
def test_basic(self):
img = np.ones((50, 50, 3), dtype=np.uint8)
r, g, b, v = histograms(img, 255)
for band in (r, g, b, v):
yield assert_equal, band.sum(), 50 * 50
def test_counts(self):
channel = np.arange(255).reshape(51, 5)
img = np.empty((51, 5, 3), dtype='uint8')
img[:, :, 0] = channel
img[:, :, 1] = channel
img[:, :, 2] = channel
r, g, b, v = histograms(img, 255)
assert_array_equal(r, g)
assert_array_equal(r, b)
assert_array_equal(r, v)
assert_array_equal(r, np.ones(255))

View File

@@ -0,0 +1,80 @@
from tempfile import NamedTemporaryFile
import numpy as np
from skimage.io import imread, imsave, use_plugin, reset_plugins
from skimage._shared import testing
from skimage._shared.testing import assert_array_almost_equal, TestCase, fetch
from skimage._shared._warnings import expected_warnings
def setup():
use_plugin('imageio')
def teardown():
reset_plugins()
def test_imageio_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_imageio_palette():
img = imread(fetch('data/palette_color.png'))
assert img.ndim == 3
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'))
class TestSave(TestCase):
def roundtrip(self, x, scaling=1):
with NamedTemporaryFile(suffix='.png') as f:
fname = f.name
imsave(fname, x)
y = imread(fname)
assert_array_almost_equal((x * scaling).astype(np.int32), y)
def test_imsave_roundtrip(self):
dtype = np.uint8
np.random.seed(0)
for shape in [(10, 10), (10, 10, 3), (10, 10, 4)]:
x = np.ones(shape, dtype=dtype) * np.random.rand(*shape)
if np.issubdtype(dtype, np.floating):
yield self.roundtrip, x, 255
else:
x = (x * 255).astype(dtype)
yield self.roundtrip, x
def test_bool_array_save(self):
with NamedTemporaryFile(suffix='.png') as f:
fname = f.name
with expected_warnings(['.* is a boolean image']):
a = np.zeros((5, 5), bool)
a[2, 2] = True
imsave(fname, a)
def test_return_class():
testing.assert_equal(
type(imread(fetch('data/color.png'))),
np.ndarray
)

View File

@@ -0,0 +1,70 @@
from tempfile import NamedTemporaryFile
import numpy as np
from skimage import io
from skimage.io import imread, imsave, use_plugin, reset_plugins
from skimage._shared import testing
from skimage._shared.testing import (TestCase, assert_array_equal,
assert_array_almost_equal, fetch)
from pytest import importorskip
importorskip('imread')
def setup():
use_plugin('imread')
def teardown():
reset_plugins()
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_imread_palette():
img = imread(fetch('data/palette_color.png'))
assert img.ndim == 3
def test_imread_truncated_jpg():
with testing.raises(RuntimeError):
io.imread(fetch('data/truncated.jpg'))
def test_bilevel():
expected = np.zeros((10, 10), bool)
expected[::2] = 1
img = imread(fetch('data/checker_bilevel.png'))
assert_array_equal(img.astype(bool), expected)
class TestSave(TestCase):
def roundtrip(self, x, scaling=1):
with NamedTemporaryFile(suffix='.png') as f:
fname = f.name
imsave(fname, x)
y = imread(fname)
assert_array_almost_equal((x * scaling).astype(np.int32), y)
def test_imsave_roundtrip(self):
dtype = np.uint8
np.random.seed(0)
for shape in [(10, 10), (10, 10, 3), (10, 10, 4)]:
x = np.ones(shape, dtype=dtype) * np.random.rand(*shape)
if np.issubdtype(dtype, np.floating):
yield self.roundtrip, x, 255
else:
x = (x * 255).astype(dtype)
yield self.roundtrip, x

View File

@@ -0,0 +1,120 @@
import os
import pathlib
import tempfile
import numpy as np
import pytest
from skimage import io
from skimage._shared.testing import assert_array_equal, fetch
from skimage.data import data_dir
one_by_one_jpeg = (
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01'
b'\x00\x01\x00\x00\xff\xdb\x00C\x00\x03\x02\x02\x02\x02'
b'\x02\x03\x02\x02\x02\x03\x03\x03\x03\x04\x06\x04\x04'
b'\x04\x04\x04\x08\x06\x06\x05\x06\t\x08\n\n\t\x08\t\t'
b'\n\x0c\x0f\x0c\n\x0b\x0e\x0b\t\t\r\x11\r\x0e\x0f\x10'
b'\x10\x11\x10\n\x0c\x12\x13\x12\x10\x13\x0f\x10\x10'
b'\x10\xff\xc0\x00\x0b\x08\x00\x01\x00\x01\x01\x01\x11'
b'\x00\xff\xc4\x00\x14\x00\x01\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\t\xff\xc4\x00'
b'\x14\x10\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\xff\xda\x00\x08\x01\x01\x00'
b'\x00?\x00*\x9f\xff\xd9'
)
def test_stack_basic():
x = np.arange(12).reshape(3, 4)
io.push(x)
assert_array_equal(io.pop(), x)
def test_stack_non_array():
with pytest.raises(ValueError):
io.push([[1, 2, 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_imread_http_url(httpserver):
# httpserver is a fixture provided by pytest-localserver
# https://bitbucket.org/pytest-dev/pytest-localserver/
httpserver.serve_content(one_by_one_jpeg)
# it will serve anything you provide to it on its url.
# we add a /test.jpg so that we can identify the content
# by extension
image = io.imread(httpserver.url + '/test.jpg' + '?' + 's' * 266)
assert image.shape == (1, 1)
def test_imread_pathlib_tiff():
"""Tests reading from Path object (issue gh-5545)."""
# read via fetch
expected = io.imread(fetch('data/multipage.tif'))
# read by passing in a pathlib.Path object
fname = os.path.join(data_dir, 'multipage.tif')
path = pathlib.Path(fname)
img = io.imread(path)
assert img.shape == (2, 15, 10)
assert_array_equal(expected, img)
def _named_tempfile_func(error_class):
"""Create a mock function for NamedTemporaryFile that always raises.
Parameters
----------
error_class : exception class
The error that should be raised when asking for a NamedTemporaryFile.
Returns
-------
named_temp_file : callable
A function that always raises the desired error.
Notes
-----
Although this function has general utility for raising errors, it is
expected to be used to raise errors that ``tempfile.NamedTemporaryFile``
from the Python standard library could raise. As of this writing, these
are ``FileNotFoundError``, ``FileExistsError``, ``PermissionError``, and
``BaseException``. See
`this comment <https://github.com/scikit-image/scikit-image/issues/3785#issuecomment-486598307>`__ # noqa
for more information.
"""
def named_temp_file(*args, **kwargs):
raise error_class()
return named_temp_file
@pytest.mark.parametrize(
'error_class', [
FileNotFoundError, FileExistsError, PermissionError, BaseException
]
)
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)

View File

@@ -0,0 +1,133 @@
import numpy as np
import pytest
from skimage import io
from skimage._shared._warnings import expected_warnings
plt = pytest.importorskip("matplotlib.pyplot")
def setup():
io.reset_plugins()
# test images. Note that they don't have their full range for their dtype,
# but we still expect the display range to equal the full dtype range.
im8 = np.array([[0, 64], [128, 240]], np.uint8)
im16 = im8.astype(np.uint16) * 256
im64 = im8.astype(np.uint64)
imf = im8 / 255
im_lo = imf / 1000
im_hi = imf + 10
imshow_expected_warnings = [
r"tight_layout : falling back to Agg|\A\Z",
r"tight_layout: falling back to Agg|\A\Z", # formatting change in mpl
# Maptlotlib 2.2.3 seems to use np.asscalar which issues a warning
# with numpy 1.16
# Matplotlib 2.2.3 is the last supported version for python 2.7
r"np.asscalar|\A\Z"
]
def n_subplots(ax_im):
"""Return the number of subplots in the figure containing an ``AxesImage``.
Parameters
----------
ax_im : matplotlib.pyplot.AxesImage object
The input ``AxesImage``.
Returns
-------
n : int
The number of subplots in the corresponding figure.
Notes
-----
This function is intended to check whether a colorbar was drawn, in
which case two subplots are expected. For standard imshows, one
subplot is expected.
"""
return len(ax_im.get_figure().get_axes())
def test_uint8():
plt.figure()
with expected_warnings(imshow_expected_warnings +
[r"CObject type is marked|\A\Z"]):
ax_im = io.imshow(im8)
assert ax_im.cmap.name == 'gray'
assert ax_im.get_clim() == (0, 255)
assert n_subplots(ax_im) == 1
assert ax_im.colorbar is None
def test_uint16():
plt.figure()
with expected_warnings(imshow_expected_warnings +
[r"CObject type is marked|\A\Z"]):
ax_im = io.imshow(im16)
assert ax_im.cmap.name == 'gray'
assert ax_im.get_clim() == (0, 65535)
assert n_subplots(ax_im) == 1
assert ax_im.colorbar is None
def test_float():
plt.figure()
with expected_warnings(imshow_expected_warnings +
[r"CObject type is marked|\A\Z"]):
ax_im = io.imshow(imf)
assert ax_im.cmap.name == 'gray'
assert ax_im.get_clim() == (0, 1)
assert n_subplots(ax_im) == 1
assert ax_im.colorbar is None
def test_low_data_range():
with expected_warnings(imshow_expected_warnings +
["Low image data range|CObject type is marked"]):
ax_im = io.imshow(im_lo)
assert ax_im.get_clim() == (im_lo.min(), im_lo.max())
# check that a colorbar was created
assert ax_im.colorbar is not None
def test_outside_standard_range():
plt.figure()
# Warning raised by matplotlib on Windows:
# "The CObject type is marked Pending Deprecation in Python 2.7.
# Please use capsule objects instead."
# Ref: https://docs.python.org/2/c-api/cobject.html
with expected_warnings(imshow_expected_warnings +
["out of standard range|CObject type is marked"]):
ax_im = io.imshow(im_hi)
assert ax_im.get_clim() == (im_hi.min(), im_hi.max())
assert n_subplots(ax_im) == 2
assert ax_im.colorbar is not None
def test_nonstandard_type():
plt.figure()
# Warning raised by matplotlib on Windows:
# "The CObject type is marked Pending Deprecation in Python 2.7.
# Please use capsule objects instead."
# Ref: https://docs.python.org/2/c-api/cobject.html
with expected_warnings(imshow_expected_warnings +
["Low image data range|CObject type is marked"]):
ax_im = io.imshow(im64)
assert ax_im.get_clim() == (im64.min(), im64.max())
assert n_subplots(ax_im) == 2
assert ax_im.colorbar is not None
def test_signed_image():
plt.figure()
im_signed = np.array([[-0.5, -0.2], [0.1, 0.4]])
with expected_warnings(imshow_expected_warnings +
[r"CObject type is marked|\A\Z"]):
ax_im = io.imshow(im_signed)
assert ax_im.get_clim() == (-0.5, 0.5)
assert n_subplots(ax_im) == 2
assert ax_im.colorbar is not None

View File

@@ -0,0 +1,88 @@
import os
import numpy as np
from skimage.io import use_plugin, reset_plugins
from skimage.io.collection import MultiImage
from skimage._shared import testing
from skimage._shared.testing import assert_equal, assert_allclose
from pytest import fixture
@fixture
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_shapes(imgs):
imgs = imgs[-1]
assert imgs[0][0].shape == imgs[0][1].shape
assert imgs[0][0].shape == (10, 10, 3)
def test_len(imgs):
assert len(imgs[0][0]) == len(imgs[1][0]) == 2
assert len(imgs[2][0]) == len(imgs[3][0]) == 24
assert len(imgs[-1]) == 2, len(imgs[-1])
def test_slicing(imgs):
img = imgs[-1]
assert type(img[:]) is MultiImage
assert len(img[0][:]) + len(img[1][:]) == 26, len(img[:])
assert len(img[0][:1]) == 1
assert len(img[1][1:]) == 23
assert_allclose(img[0], img[:1][0])
assert_allclose(img[1], img[1:][0])
assert_allclose(img[-1], img[::-1][0])
assert_allclose(img[0], img[::-1][-1])
def test_getitem(imgs):
for img in imgs[0]:
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_files_property(imgs):
for img in imgs:
if isinstance(img, MultiImage):
continue
assert isinstance(img.filename, str)
with testing.raises(AttributeError):
img.filename = "newfile"
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_concatenate(imgs):
for img in imgs:
if img[0].shape != img[-1].shape:
with testing.raises(ValueError):
img.concatenate()
continue
array = img.concatenate()
assert_equal(array.shape, (len(img),) + img[0].shape)

View File

@@ -0,0 +1,304 @@
import os
from io import BytesIO
from tempfile import NamedTemporaryFile
import numpy as np
import pytest
from PIL import Image
from skimage._shared import testing
from skimage._shared._tempfile import temporary_file
from skimage._shared._warnings import expected_warnings
from skimage._shared.testing import (assert_allclose,
assert_array_almost_equal,
assert_array_equal, assert_equal,
color_check, fetch, mono_check)
from skimage.metrics import structural_similarity
from ... import img_as_float
from ...color import rgb2lab
from .. import imread, imsave, reset_plugins, use_plugin
from .._plugins.pil_plugin import (_palette_is_grayscale, ndarray_to_pil,
pil_to_ndarray)
def setup():
use_plugin('pil')
def teardown():
reset_plugins()
def setup_module(self):
"""The effect of the `plugin.use` call may be overridden by later imports.
Call `use_plugin` directly before the tests to ensure that PIL is used.
"""
try:
use_plugin('pil')
except ImportError:
pass
def test_png_round_trip():
with NamedTemporaryFile(suffix='.png') as f:
fname = f.name
I = np.eye(3)
imsave(fname, I)
Ip = img_as_float(imread(fname))
os.remove(fname)
assert np.sum(np.abs(Ip-I)) < 1e-3
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']
@pytest.mark.parametrize('explicit_kwargs', [False, True])
def test_imread_separate_channels(explicit_kwargs):
# Test that imread returns RGB(A) values contiguously even when they are
# stored in separate planes.
x = np.random.rand(3, 16, 8)
with NamedTemporaryFile(suffix='.tif') as f:
fname = f.name
# Tifffile is used as backend whenever suffix is .tif or .tiff
# To avoid pending changes to tifffile defaults, we must specify this is an
# RGB image with separate planes (i.e., channel_axis=0).
if explicit_kwargs:
pass
else:
pass
imsave(fname, x)
img = imread(fname)
os.remove(fname)
assert img.shape == (16, 8, 3), img.shape
def test_imread_multipage_rgb_tif():
img = imread(fetch('data/multipage_rgb.tif'))
assert img.shape == (2, 10, 10, 3), img.shape
def test_imread_palette():
img = imread(fetch('data/palette_gray.png'))
assert img.ndim == 2
img = imread(fetch('data/palette_color.png'))
assert img.ndim == 3
def test_imread_index_png_with_alpha():
# The file `foo3x5x4indexed.png` was created with this array
# (3x5 is (height)x(width)):
dfoo = np.array([[[127, 0, 255, 255],
[127, 0, 255, 255],
[127, 0, 255, 255],
[127, 0, 255, 255],
[127, 0, 255, 255]],
[[192, 192, 255, 0],
[192, 192, 255, 0],
[0, 0, 255, 0],
[0, 0, 255, 0],
[0, 0, 255, 0]],
[[0, 31, 255, 255],
[0, 31, 255, 255],
[0, 31, 255, 255],
[0, 31, 255, 255],
[0, 31, 255, 255]]], dtype=np.uint8)
img = imread(fetch('data/foo3x5x4indexed.png'))
assert_array_equal(img, dfoo)
def test_palette_is_gray():
gray = Image.open(fetch('data/palette_gray.png'))
assert _palette_is_grayscale(gray)
color = Image.open(fetch('data/palette_color.png'))
assert not _palette_is_grayscale(color)
def test_bilevel():
expected = np.zeros((10, 10))
expected[::2] = 255
img = imread(fetch('data/checker_bilevel.png'))
assert_array_equal(img, expected)
def test_imread_uint16():
expected = np.load(fetch('data/chessboard_GRAY_U8.npy'))
img = imread(fetch('data/chessboard_GRAY_U16.tif'))
assert np.issubdtype(img.dtype, np.uint16)
assert_array_almost_equal(img, expected)
def test_imread_truncated_jpg():
with testing.raises(IOError):
imread(fetch('data/truncated.jpg'))
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_imread_uint16_big_endian():
expected = np.load(fetch('data/chessboard_GRAY_U8.npy'))
img = imread(fetch('data/chessboard_GRAY_U16B.tif'))
assert img.dtype == np.uint16
assert_array_almost_equal(img, expected)
class TestSave:
def roundtrip_file(self, x):
with temporary_file(suffix='.png') as fname:
imsave(fname, x)
y = imread(fname)
return y
def roundtrip_pil_image(self, x):
pil_image = ndarray_to_pil(x)
y = pil_to_ndarray(pil_image)
return y
def verify_roundtrip(self, dtype, x, y, scaling=1):
assert_array_almost_equal((x * scaling).astype(np.int32), y)
def verify_imsave_roundtrip(self, roundtrip_function):
for shape in [(10, 10), (10, 10, 3), (10, 10, 4)]:
for dtype in (np.uint8, np.uint16, np.float32, np.float64):
x = np.ones(shape, dtype=dtype) * np.random.rand(*shape)
if np.issubdtype(dtype, np.floating):
yield (self.verify_roundtrip, dtype, x,
roundtrip_function(x), 255)
else:
x = (x * 255).astype(dtype)
yield (self.verify_roundtrip, dtype, x,
roundtrip_function(x))
def test_imsave_roundtrip_file(self):
self.verify_imsave_roundtrip(self.roundtrip_file)
def test_imsave_roundtrip_pil_image(self):
self.verify_imsave_roundtrip(self.roundtrip_pil_image)
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)))
# test that low contrast check is ignored
with testing.raises(ValueError):
with expected_warnings([]):
imsave(fname, np.zeros((2, 3, 2)), check_contrast=False)
def test_imsave_filelike():
shape = (2, 2)
image = np.zeros(shape)
s = BytesIO()
# save to file-like object
with expected_warnings(['is a low contrast image']):
imsave(s, image)
# read from file-like object
s.seek(0)
out = imread(s)
assert_equal(out.shape, shape)
assert_allclose(out, image)
def test_imsave_boolean_input():
shape = (2, 2)
image = np.eye(*shape, dtype=bool)
s = BytesIO()
# save to file-like object
with expected_warnings(
['is a boolean image: setting True to 255 and False to 0']):
imsave(s, image)
# read from file-like object
s.seek(0)
out = imread(s)
assert_equal(out.shape, shape)
assert_allclose(out.astype(bool), image)
def test_imexport_imimport():
shape = (2, 2)
image = np.zeros(shape)
pil_image = ndarray_to_pil(image)
out = pil_to_ndarray(pil_image)
assert_equal(out.shape, shape)
def test_all_color():
with expected_warnings(['.* is a boolean image']):
color_check('pil')
with expected_warnings(['.* is a boolean image']):
color_check('pil', 'bmp')
def test_all_mono():
with expected_warnings(['.* is a boolean image']):
mono_check('pil')
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')
with NamedTemporaryFile(suffix='.jpg') as f:
fname = f.name
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_extreme_palette():
img = imread(fetch('data/green_palette.png'))
assert_equal(img.ndim, 3)

View File

@@ -0,0 +1,74 @@
from contextlib import contextmanager
import numpy as np
import pytest
from skimage._shared._dependency_checks import has_mpl
from skimage import io
from skimage.io import manage_plugins
priority_plugin = 'pil'
def setup():
io.use_plugin('pil')
def teardown_module():
io.reset_plugins()
@contextmanager
def protect_preferred_plugins():
"""Contexts where `preferred_plugins` can be modified w/o side-effects."""
preferred_plugins = manage_plugins.preferred_plugins.copy()
try:
yield
finally:
manage_plugins.preferred_plugins = preferred_plugins
def test_failed_use():
with pytest.raises(ValueError):
manage_plugins.use_plugin('asd')
@pytest.mark.skipif(not has_mpl, reason="matplotlib not installed")
def test_use_priority():
manage_plugins.use_plugin(priority_plugin)
plug, func = manage_plugins.plugin_store['imread'][0]
np.testing.assert_equal(plug, priority_plugin)
manage_plugins.use_plugin('matplotlib')
plug, func = manage_plugins.plugin_store['imread'][0]
np.testing.assert_equal(plug, 'matplotlib')
@pytest.mark.skipif(not has_mpl, reason="matplotlib not installed")
def test_load_preferred_plugins_all():
from skimage.io._plugins import pil_plugin, matplotlib_plugin
with protect_preferred_plugins():
manage_plugins.preferred_plugins = {'all': ['pil'],
'imshow': ['matplotlib']}
manage_plugins.reset_plugins()
for plugin_type in ('imread', 'imsave'):
plug, func = manage_plugins.plugin_store[plugin_type][0]
assert func == getattr(pil_plugin, plugin_type)
plug, func = manage_plugins.plugin_store['imshow'][0]
assert func == getattr(matplotlib_plugin, 'imshow')
@pytest.mark.skipif(not has_mpl, reason="matplotlib not installed")
def test_load_preferred_plugins_imread():
from skimage.io._plugins import pil_plugin, matplotlib_plugin
with protect_preferred_plugins():
manage_plugins.preferred_plugins['imread'] = ['pil']
manage_plugins.reset_plugins()
plug, func = manage_plugins.plugin_store['imread'][0]
assert func == pil_plugin.imread
plug, func = manage_plugins.plugin_store['imshow'][0]
assert func == matplotlib_plugin.imshow, func.__module__

View File

@@ -0,0 +1,66 @@
import os
from tempfile import NamedTemporaryFile
from skimage.io import load_sift, load_surf
from skimage._shared.testing import assert_equal
def test_load_sift():
with NamedTemporaryFile(delete=False) as f:
fname = f.name
with open(fname, 'wb') as f:
f.write(b'''2 128
133.92 135.88 14.38 -2.732
3 12 23 38 10 15 78 20 39 67 42 8 12 8 39 35 118 43 17 0
0 1 12 109 9 2 6 0 0 21 46 22 14 18 51 19 5 9 41 52
65 30 3 21 55 49 26 30 118 118 25 12 8 3 2 60 53 56 72 20
7 10 16 7 88 23 13 15 12 11 11 71 45 7 4 49 82 38 38 91
118 15 2 16 33 3 5 118 98 38 6 19 36 1 0 15 64 22 1 2
6 11 18 61 31 3 0 6 15 23 118 118 13 0 0 35 38 18 40 96
24 1 0 13 17 3 24 98
132.36 99.75 11.45 -2.910
94 32 7 2 13 7 5 23 121 94 13 5 0 0 4 59 13 30 71 32
0 6 32 11 25 32 13 0 0 16 51 5 44 50 0 3 33 55 11 9
121 121 12 9 6 3 0 18 55 60 48 44 44 9 0 2 106 117 13 2
1 0 1 1 37 1 1 25 80 35 15 41 121 3 0 2 14 3 2 121
51 11 0 20 93 6 0 20 109 57 3 4 5 0 0 28 21 2 0 5
13 12 75 119 35 0 0 13 28 14 37 121 12 0 0 21 46 5 11 93
29 0 0 3 14 4 11 99''')
# Check whether loading by filename works
load_sift(fname)
with open(fname) as f:
features = load_sift(f)
os.remove(fname)
assert_equal(len(features), 2)
assert_equal(len(features['data'][0]), 128)
assert_equal(features['row'][0], 133.92)
assert_equal(features['column'][1], 99.75)
def test_load_surf():
with NamedTemporaryFile(delete=False) as f:
fname = f.name
with open(fname, 'wb') as f:
f.write(b'''65
2
38.3727 62.0491 0.0371343 0 0.0371343 -1 -0.0705589 0.0130983 -0.00460534 0.132168 -0.0718833 0.0320583 -0.0134032 0.0988654 -0.0542241 0.0171002 -0.00135754 0.105755 -0.0362088 0.0151748 -0.00694272 0.0610017 -0.247091 0.109605 -0.0337623 0.0813307 -0.24185 0.278548 -0.0494523 0.107804 -0.166312 0.0691584 -0.0288199 0.138476 -0.110956 0.0280772 -0.0752509 0.0736344 -0.22667 0.164226 -0.0544717 0.0388139 -0.30194 0.33065 -0.0537507 0.0596398 -0.245395 0.110925 -0.0603322 0.0239389 -0.18726 0.0374145 -0.0355872 0.0140762 -0.129022 0.135104 -0.0703396 0.0374049 -0.24256 0.222544 -0.0536354 0.0501252 -0.209004 0.0971316 -0.0550094 0.0229767 -0.125547 0.0317879 -0.0291574 0.0124569
68.5773 61.474 0.0313267 0 0.0313267 1 -0.10198 0.130987 -0.0321845 0.0487543 -0.0900435 0.121113 -0.100917 0.0444702 -0.0151742 0.107604 -0.0542035 0.014069 -0.00594097 0.0339933 -0.00994295 0.0127262 -0.125613 0.192551 -0.0174399 0.0433488 -0.272698 0.164641 -0.0676735 0.0467444 -0.0527907 0.258005 -0.0818114 0.0440569 -0.0104433 0.0548934 -0.0323454 0.0145296 -0.112357 0.199223 -0.0532903 0.0332622 -0.342481 0.207469 -0.0526129 0.0741355 -0.256234 0.402708 -0.108296 0.117362 -0.0560274 0.128856 -0.123509 0.0510046 -0.0198793 0.0775934 -0.103863 0.00406679 -0.10264 0.1312 -0.108244 0.0812913 -0.127868 0.182924 -0.0680942 0.071913 -0.0858004 0.144806 -0.0176522 0.0686146''')
# Check whether loading by filename works
load_surf(fname)
with open(fname) as f:
features = load_surf(f)
os.remove(fname)
assert_equal(len(features), 2)
assert_equal(len(features['data'][0]), 64)
assert_equal(features['column'][1], 68.5773)
assert_equal(features['row'][0], 62.0491)

View File

@@ -0,0 +1,83 @@
import numpy as np
import unittest
from tempfile import NamedTemporaryFile
from skimage.io import imread, imsave, use_plugin, reset_plugins
from skimage._shared import testing
from pytest import importorskip, raises, fixture
importorskip('SimpleITK')
np.random.seed(0)
def teardown():
reset_plugins()
@fixture(autouse=True)
def setup_plugin():
"""This ensures that `use_plugin` is directly called before all tests to
ensure that SimpleITK is used.
"""
use_plugin('simpleitk')
yield
def test_imread_as_gray():
img = imread(testing.fetch('data/color.png'), as_gray=True)
assert img.ndim == 2
assert img.dtype == np.float64
img = imread(testing.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_bilevel():
expected = np.zeros((10, 10))
expected[::2] = 255
img = imread(testing.fetch('data/checker_bilevel.png'))
np.testing.assert_array_equal(img, expected)
def test_imread_truncated_jpg():
with raises(RuntimeError):
imread(testing.fetch('data/truncated.jpg'))
def test_imread_uint16():
expected = np.load(testing.fetch('data/chessboard_GRAY_U8.npy'))
img = imread(testing.fetch('data/chessboard_GRAY_U16.tif'))
assert np.issubdtype(img.dtype, np.uint16)
np.testing.assert_array_almost_equal(img, expected)
def test_imread_uint16_big_endian():
expected = np.load(testing.fetch('data/chessboard_GRAY_U8.npy'))
img = imread(testing.fetch('data/chessboard_GRAY_U16B.tif'))
np.testing.assert_array_almost_equal(img, expected)
class TestSave(unittest.TestCase):
def roundtrip(self, dtype, x):
with NamedTemporaryFile(suffix='.mha') as f:
fname = f.name
imsave(fname, x)
y = imread(fname)
np.testing.assert_array_almost_equal(x, y)
def test_imsave_roundtrip(self):
for shape in [(10, 10), (10, 10, 3), (10, 10, 4)]:
for dtype in (np.uint8, np.uint16, np.float32, np.float64):
x = np.ones(shape, dtype=dtype) * np.random.rand(*shape)
if np.issubdtype(dtype, np.floating):
yield self.roundtrip, dtype, x
else:
x = (x * 255).astype(dtype)
yield self.roundtrip, dtype, x

View File

@@ -0,0 +1,83 @@
import pathlib
from tempfile import NamedTemporaryFile
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal, assert_array_equal
from skimage._shared.testing import fetch
from skimage.io import imread, imsave, reset_plugins, use_plugin
def setup():
use_plugin('tifffile')
np.random.seed(0)
def teardown():
reset_plugins()
def test_imread_uint16():
expected = np.load(fetch('data/chessboard_GRAY_U8.npy'))
img = imread(fetch('data/chessboard_GRAY_U16.tif'))
assert img.dtype == np.uint16
assert_array_almost_equal(img, expected)
def test_imread_uint16_big_endian():
expected = np.load(fetch('data/chessboard_GRAY_U8.npy'))
img = imread(fetch('data/chessboard_GRAY_U16B.tif'))
assert img.dtype == np.uint16
assert_array_almost_equal(img, expected)
def test_imread_multipage_rgb_tif():
img = imread(fetch('data/multipage_rgb.tif'))
assert img.shape == (2, 10, 10, 3), img.shape
def test_tifffile_kwarg_passthrough ():
img = imread(fetch('data/multipage.tif'), key=[1], is_ome=True)
assert img.shape == (15, 10), img.shape
def test_imread_handle():
expected = np.load(fetch('data/chessboard_GRAY_U8.npy'))
with open(fetch('data/chessboard_GRAY_U16.tif'), 'rb') as fh:
img = imread(fh)
assert img.dtype == np.uint16
assert_array_almost_equal(img, expected)
class TestSave:
def roundtrip(self, dtype, x, use_pathlib=False, **kwargs):
with NamedTemporaryFile(suffix='.tif') as f:
fname = f.name
if use_pathlib:
fname = pathlib.Path(fname)
imsave(fname, x, check_contrast=False, **kwargs)
y = imread(fname)
assert_array_equal(x, y)
shapes = ((10, 10), (10, 10, 3), (10, 10, 4))
dtypes = (np.uint8, np.uint16, np.float32, np.int16, np.float64)
@pytest.mark.parametrize("shape", shapes)
@pytest.mark.parametrize("dtype", dtypes)
@pytest.mark.parametrize("use_pathlib", [False, True])
@pytest.mark.parametrize('explicit_photometric_kwarg', [False, True])
def test_imsave_roundtrip(self, shape, dtype, use_pathlib,
explicit_photometric_kwarg):
x = np.random.rand(*shape)
if not np.issubdtype(dtype, np.floating):
x = (x * np.iinfo(dtype).max).astype(dtype)
else:
x = x.astype(dtype)
if explicit_photometric_kwarg and x.shape[-1] in [3, 4]:
kwargs = {'photometric': 'rgb'}
else:
kwargs = {}
self.roundtrip(dtype, x, use_pathlib, **kwargs)