Fixed database typo and removed unnecessary class identifier.

This commit is contained in:
Batuhan Berk Başoğlu 2020-10-14 10:10:37 -04:00
parent 00ad49a143
commit 45fb349a7d
5098 changed files with 952558 additions and 85 deletions

View file

@ -0,0 +1,9 @@
from ..._shared.testing import setup_test, teardown_test
def setup():
setup_test()
def teardown():
teardown_test()

View file

@ -0,0 +1,111 @@
import os
import numpy as np
from skimage import data_dir
from skimage.io.collection import ImageCollection, alphanumeric_key
from skimage.io import reset_plugins
from skimage._shared import testing
from skimage._shared.testing import assert_equal, assert_allclose, TestCase
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']
sorted_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(sorted_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
# regarless 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(TestCase):
pattern = [os.path.join(data_dir, pic)
for pic in ['camera.png', 'color.png']]
pattern_matched = [os.path.join(data_dir, pic)
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.
self.images_matched = ImageCollection(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')
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()

View file

@ -0,0 +1,136 @@
import numpy as np
import skimage.io._plugins._colormixer as cm
from skimage._shared.testing import (assert_array_equal, assert_almost_equal,
assert_equal, assert_array_almost_equal)
class ColorMixerTest(object):
def setup(self):
self.state = np.full((18, 33, 3), 200, dtype=np.uint8)
self.img = np.zeros_like(self.state)
def test_basic(self):
self.op(self.img, self.state, 0, self.positive)
assert_array_equal(self.img[..., 0],
self.py_op(self.state[..., 0], self.positive))
def test_clip(self):
self.op(self.img, self.state, 0, self.positive_clip)
assert_array_equal(self.img[..., 0],
np.full_like(self.img[..., 0], 255))
def test_negative(self):
self.op(self.img, self.state, 0, self.negative)
assert_array_equal(self.img[..., 0],
self.py_op(self.state[..., 0], self.negative))
def test_negative_clip(self):
self.op(self.img, self.state, 0, self.negative_clip)
assert_array_equal(self.img[..., 0],
np.zeros_like(self.img[..., 0]))
class TestColorMixerAdd(ColorMixerTest):
op = staticmethod(cm.add)
py_op = np.add
positive = 50
positive_clip = 56
negative = -50
negative_clip = -220
class TestColorMixerMul(ColorMixerTest):
op = staticmethod(cm.multiply)
py_op = np.multiply
positive = 1.2
positive_clip = 2
negative = 0.5
negative_clip = -0.5
class TestColorMixerBright(object):
def setup(self):
self.state = np.ones((18, 33, 3), dtype=np.uint8) * 200
self.img = np.zeros_like(self.state)
def test_brightness_pos(self):
cm.brightness(self.img, self.state, 1.25, 1)
assert_array_equal(self.img, np.ones_like(self.img) * 251)
def test_brightness_neg(self):
cm.brightness(self.img, self.state, 0.5, -50)
assert_array_equal(self.img, np.ones_like(self.img) * 50)
def test_brightness_pos_clip(self):
cm.brightness(self.img, self.state, 2, 0)
assert_array_equal(self.img, np.ones_like(self.img) * 255)
def test_brightness_neg_clip(self):
cm.brightness(self.img, self.state, 0, 0)
assert_array_equal(self.img, np.zeros_like(self.img))
class TestColorMixer(object):
def setup(self):
self.state = np.ones((18, 33, 3), dtype=np.uint8) * 50
self.img = np.zeros_like(self.state)
def test_sigmoid(self):
import math
alpha = 1.5
beta = 1.5
c1 = 1 / (1 + math.exp(beta))
c2 = 1 / (1 + math.exp(beta - alpha)) - c1
state = self.state / 255.
cm.sigmoid_gamma(self.img, self.state, alpha, beta)
img = 1 / (1 + np.exp(beta - state * alpha))
img = np.asarray((img - c1) / c2 * 255, dtype='uint8')
assert_almost_equal(img, self.img)
def test_gamma(self):
gamma = 1.5
cm.gamma(self.img, self.state, gamma)
img = np.asarray(((self.state / 255.)**(1 / gamma)) * 255,
dtype='uint8')
assert_array_almost_equal(img, self.img)
def test_rgb_2_hsv(self):
r = 255
g = 0
b = 0
h, s, v = cm.py_rgb_2_hsv(r, g, b)
assert_almost_equal(np.array([h]), np.array([0]))
assert_almost_equal(np.array([s]), np.array([1]))
assert_almost_equal(np.array([v]), np.array([1]))
def test_hsv_2_rgb(self):
h = 0
s = 1
v = 1
r, g, b = cm.py_hsv_2_rgb(h, s, v)
assert_almost_equal(np.array([r]), np.array([255]))
assert_almost_equal(np.array([g]), np.array([0]))
assert_almost_equal(np.array([b]), np.array([0]))
def test_hsv_add(self):
cm.hsv_add(self.img, self.state, 360, 0, 0)
assert_almost_equal(self.img, self.state)
def test_hsv_add_clip_neg(self):
cm.hsv_add(self.img, self.state, 0, 0, -1)
assert_equal(self.img, np.zeros_like(self.state))
def test_hsv_add_clip_pos(self):
cm.hsv_add(self.img, self.state, 0, 0, 1)
assert_equal(self.img, np.ones_like(self.state) * 255)
def test_hsv_mul(self):
cm.hsv_multiply(self.img, self.state, 360, 1, 1)
assert_almost_equal(self.img, self.state)
def test_hsv_mul_clip_neg(self):
cm.hsv_multiply(self.img, self.state, 0, 0, 0)
assert_equal(self.img, np.zeros_like(self.state))

View file

@ -0,0 +1,35 @@
import os.path
import numpy as np
import skimage.io as io
from skimage._shared import testing
testing.pytest.importorskip('astropy')
from astropy.io import fits
import skimage.io._plugins.fits_plugin as fplug
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,79 @@
from tempfile import NamedTemporaryFile
import pytest
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.
with testing.raises(SyntaxError):
imread(fetch('data/truncated.jpg'))
class TestSave(TestCase):
def roundtrip(self, x, scaling=1):
f = NamedTemporaryFile(suffix='.png')
fname = f.name
f.close()
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):
f = NamedTemporaryFile(suffix='.png')
fname = f.name
f.close()
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,71 @@
import os
from tempfile import NamedTemporaryFile
import numpy as np
from skimage import data, 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):
f = NamedTemporaryFile(suffix='.png')
fname = f.name
f.close()
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,104 @@
import os
import tempfile
import numpy as np
from skimage import io
from skimage._shared import testing
from skimage._shared.testing import assert_array_equal
from skimage._shared.testing import 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 testing.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(testing.fetch('data/camera.png'))
data_path = data_path.replace(os.path.sep, '/')
image_url = 'file:///{0}'.format(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 _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>`__
for more information.
"""
def named_temp_file(*args, **kwargs):
raise error_class()
return named_temp_file
@testing.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 = 'file:///{0}/camera.png'.format(data_path)
with monkeypatch.context():
monkeypatch.setattr(
tempfile, 'NamedTemporaryFile', _named_tempfile_func(error_class)
)
with testing.raises(error_class):
image = io.imread(image_url)

View file

@ -0,0 +1,135 @@
import numpy as np
from skimage import io
from skimage._shared._warnings import expected_warnings
import matplotlib.pyplot as plt
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
if __name__ == '__main__':
np.testing.run_module_suite()

View file

@ -0,0 +1,94 @@
import os
import numpy as np
from skimage.io import use_plugin, reset_plugins
from skimage.io.collection import MultiImage, ImageCollection
from skimage._shared import testing
from skimage._shared.testing import assert_equal, assert_allclose
import pytest
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),
ImageCollection(paths[0]),
ImageCollection(paths[1], conserve_memory=False),
ImageCollection(os.pathsep.join(paths))]
yield imgs
reset_plugins()
def test_shapes(imgs):
img = imgs[-1]
imgs = img[:]
assert imgs[0].shape == imgs[1].shape
assert imgs[0].shape == (10, 10, 3)
def test_len(imgs):
assert len(imgs[0]) == len(imgs[1]) == 2
assert len(imgs[2]) == len(imgs[3]) == 24
assert len(imgs[4]) == 2
assert len(imgs[5]) == 24
assert len(imgs[6]) == 26, len(imgs[6])
def test_slicing(imgs):
img = imgs[-1]
assert type(img[:]) is ImageCollection
assert len(img[:]) == 26, len(img[:])
assert len(img[:1]) == 1
assert len(img[1:]) == 25
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:
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, ImageCollection):
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,297 @@
import os
import numpy as np
from io import BytesIO
from tempfile import NamedTemporaryFile
from ... import img_as_float
from .. import imread, imsave, use_plugin, reset_plugins
from PIL import Image
from .._plugins.pil_plugin import (
pil_to_ndarray, ndarray_to_pil, _palette_is_grayscale)
from ...color import rgb2lab
from skimage._shared import testing
from skimage._shared.testing import (mono_check, color_check,
assert_equal, assert_array_equal,
assert_array_almost_equal,
assert_allclose, fetch)
from skimage._shared._warnings import expected_warnings
from skimage._shared._tempfile import temporary_file
from skimage.metrics import structural_similarity
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():
f = NamedTemporaryFile(suffix='.png')
fname = f.name
f.close()
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']
def test_imread_separate_channels():
# Test that imread returns RGBA values contiguously even when they are
# stored in separate planes.
x = np.random.rand(3, 16, 8)
f = NamedTemporaryFile(suffix='.tif')
fname = f.name
f.close()
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=np.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')
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_extreme_palette():
img = imread(fetch('data/green_palette.png'))
assert_equal(img.ndim, 3)

View file

@ -0,0 +1,72 @@
from contextlib import contextmanager
from skimage import io
from skimage.io import manage_plugins
from skimage._shared import testing
from skimage._shared.testing import assert_equal
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 testing.raises(ValueError):
manage_plugins.use_plugin('asd')
def test_use_priority():
manage_plugins.use_plugin(priority_plugin)
plug, func = manage_plugins.plugin_store['imread'][0]
assert_equal(plug, priority_plugin)
manage_plugins.use_plugin('matplotlib')
plug, func = manage_plugins.plugin_store['imread'][0]
assert_equal(plug, 'matplotlib')
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')
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,69 @@
import numpy as np
from skimage.io._plugins.util import prepare_for_display, WindowManager
from skimage._shared import testing
from skimage._shared.testing import assert_array_equal, TestCase
from skimage._shared._warnings import expected_warnings
np.random.seed(0)
class TestPrepareForDisplay(TestCase):
def test_basic(self):
prepare_for_display(np.random.rand(10, 10))
def test_dtype(self):
x = prepare_for_display(np.random.rand(10, 15))
assert x.dtype == np.dtype(np.uint8)
def test_grey(self):
tmp = np.arange(12, dtype=float).reshape((4, 3)) / 11
x = prepare_for_display(tmp)
assert_array_equal(x[..., 0], x[..., 2])
assert x[0, 0, 0] == 0
assert x[3, 2, 0] == 255
def test_color(self):
prepare_for_display(np.random.rand(10, 10, 3))
def test_alpha(self):
prepare_for_display(np.random.rand(10, 10, 4))
def test_wrong_dimensionality(self):
with testing.raises(ValueError):
prepare_for_display(np.random.rand(10, 10, 1, 1))
def test_wrong_depth(self):
with testing.raises(ValueError):
prepare_for_display(np.random.rand(10, 10, 5))
class TestWindowManager(TestCase):
callback_called = False
@testing.fixture(autouse=True)
def setup(self):
self.wm = WindowManager()
self.wm.acquire('test')
def test_add_window(self):
self.wm.add_window('window1')
self.wm.remove_window('window1')
def callback(self):
self.callback_called = True
def test_callback(self):
self.wm.register_callback(self.callback)
self.wm.add_window('window')
self.wm.remove_window('window')
assert self.callback_called
def test_has_images(self):
assert not self.wm.has_windows()
self.wm.add_window('window')
assert self.wm.has_windows()
def teardown(self):
self.wm._release('test')

View file

@ -0,0 +1,68 @@
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():
f = NamedTemporaryFile(delete=False)
fname = f.name
f.close()
f = open(fname, 'wb')
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''')
f.close()
# Check whether loading by filename works
load_sift(fname)
with open(fname, 'r') 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():
f = NamedTemporaryFile(delete=False)
fname = f.name
f.close()
f = open(fname, 'wb')
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''')
f.close()
# Check whether loading by filename works
load_surf(fname)
f = open(fname, 'r')
features = load_surf(f)
f.close()
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,87 @@
import os.path
import numpy as np
import unittest
from tempfile import NamedTemporaryFile
from skimage import data
from skimage.io import imread, imsave, use_plugin, reset_plugins
from skimage._shared import testing
from pytest import importorskip
importorskip('SimpleITK')
np.random.seed(0)
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 SimpleITK is
used.
"""
use_plugin('simpleitk')
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)
"""
#TODO: This test causes a Segmentation fault
def test_imread_truncated_jpg():
assert_raises((RuntimeError, ValueError),
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):
f = NamedTemporaryFile(suffix='.mha')
fname = f.name
f.close()
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,75 @@
import itertools
from tempfile import NamedTemporaryFile
from skimage.io import imread, imsave, use_plugin, reset_plugins
import numpy as np
from skimage._shared.testing import (assert_array_equal,
assert_array_almost_equal,
parametrize, fetch)
from skimage._shared import testing
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],
multifile=False, multifile_close=True, fastij=True,
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):
f = NamedTemporaryFile(suffix='.tif')
fname = f.name
f.close()
imsave(fname, x, check_contrast=False)
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)
@parametrize("shape, dtype", itertools.product(shapes, dtypes))
def test_imsave_roundtrip(self, shape, dtype):
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)
self.roundtrip(dtype, x)