File size: 12,327 Bytes
d381118 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | """Handle image reading, writing and plotting plugins.
To improve performance, plugins are only loaded as needed. As a result, there
can be multiple states for a given plugin:
available: Defined in an *ini file located in ``skimage.io._plugins``.
See also :func:`skimage.io.available_plugins`.
partial definition: Specified in an *ini file, but not defined in the
corresponding plugin module. This will raise an error when loaded.
available but not on this system: Defined in ``skimage.io._plugins``, but
a dependent library (e.g. Qt, PIL) is not available on your system.
This will raise an error when loaded.
loaded: The real availability is determined when it's explicitly loaded,
either because it's one of the default plugins, or because it's
loaded explicitly by the user.
"""
import os.path
import warnings
from configparser import ConfigParser
from glob import glob
from contextlib import contextmanager
from .._shared.utils import deprecate_func
from .collection import imread_collection_wrapper
__all__ = [
'use_plugin',
'call_plugin',
'plugin_info',
'plugin_order',
'reset_plugins',
'find_available_plugins',
'_available_plugins',
]
# The plugin store will save a list of *loaded* io functions for each io type
# (e.g. 'imread', 'imsave', etc.). Plugins are loaded as requested.
plugin_store = None
# Dictionary mapping plugin names to a list of functions they provide.
plugin_provides = {}
# The module names for the plugins in `skimage.io._plugins`.
plugin_module_name = {}
# Meta-data about plugins provided by *.ini files.
plugin_meta_data = {}
# For each plugin type, default to the first available plugin as defined by
# the following preferences.
preferred_plugins = {
# Default plugins for all types (overridden by specific types below).
'all': ['imageio', 'pil', 'matplotlib'],
'imshow': ['matplotlib'],
'imshow_collection': ['matplotlib'],
}
@contextmanager
def _hide_plugin_deprecation_warnings():
"""Ignore warnings related to plugin infrastructure deprecation."""
with warnings.catch_warnings():
warnings.filterwarnings(
action="ignore",
message=".*use `imageio` or other I/O packages directly.*",
category=FutureWarning,
module="skimage",
)
yield
def _clear_plugins():
"""Clear the plugin state to the default, i.e., where no plugins are loaded"""
global plugin_store
plugin_store = {
'imread': [],
'imsave': [],
'imshow': [],
'imread_collection': [],
'imshow_collection': [],
'_app_show': [],
}
with _hide_plugin_deprecation_warnings():
_clear_plugins()
def _load_preferred_plugins():
# Load preferred plugin for each io function.
io_types = ['imsave', 'imshow', 'imread_collection', 'imshow_collection', 'imread']
for p_type in io_types:
_set_plugin(p_type, preferred_plugins['all'])
plugin_types = (p for p in preferred_plugins.keys() if p != 'all')
for p_type in plugin_types:
_set_plugin(p_type, preferred_plugins[p_type])
def _set_plugin(plugin_type, plugin_list):
for plugin in plugin_list:
if plugin not in _available_plugins:
continue
try:
use_plugin(plugin, kind=plugin_type)
break
except (ImportError, RuntimeError, OSError):
pass
@deprecate_func(
deprecated_version="0.25",
removed_version="0.27",
hint="The plugin infrastructure of `skimage.io` is deprecated. "
"Instead, use `imageio` or other I/O packages directly.",
)
def reset_plugins():
with _hide_plugin_deprecation_warnings():
_clear_plugins()
_load_preferred_plugins()
def _parse_config_file(filename):
"""Return plugin name and meta-data dict from plugin config file."""
parser = ConfigParser()
parser.read(filename)
name = parser.sections()[0]
meta_data = {}
for opt in parser.options(name):
meta_data[opt] = parser.get(name, opt)
return name, meta_data
def _scan_plugins():
"""Scan the plugins directory for .ini files and parse them
to gather plugin meta-data.
"""
pd = os.path.dirname(__file__)
config_files = glob(os.path.join(pd, '_plugins', '*.ini'))
for filename in config_files:
name, meta_data = _parse_config_file(filename)
if 'provides' not in meta_data:
warnings.warn(
f'file {filename} not recognized as a scikit-image io plugin, skipping.'
)
continue
plugin_meta_data[name] = meta_data
provides = [s.strip() for s in meta_data['provides'].split(',')]
valid_provides = [p for p in provides if p in plugin_store]
for p in provides:
if p not in plugin_store:
print(f"Plugin `{name}` wants to provide non-existent `{p}`. Ignoring.")
# Add plugins that provide 'imread' as provider of 'imread_collection'.
need_to_add_collection = (
'imread_collection' not in valid_provides and 'imread' in valid_provides
)
if need_to_add_collection:
valid_provides.append('imread_collection')
plugin_provides[name] = valid_provides
plugin_module_name[name] = os.path.basename(filename)[:-4]
with _hide_plugin_deprecation_warnings():
_scan_plugins()
@deprecate_func(
deprecated_version="0.25",
removed_version="0.27",
hint="The plugin infrastructure of `skimage.io` is deprecated. "
"Instead, use `imageio` or other I/O packages directly.",
)
def find_available_plugins(loaded=False):
"""List available plugins.
Parameters
----------
loaded : bool
If True, show only those plugins currently loaded. By default,
all plugins are shown.
Returns
-------
p : dict
Dictionary with plugin names as keys and exposed functions as
values.
"""
active_plugins = set()
for plugin_func in plugin_store.values():
for plugin, func in plugin_func:
active_plugins.add(plugin)
d = {}
for plugin in plugin_provides:
if not loaded or plugin in active_plugins:
d[plugin] = [f for f in plugin_provides[plugin] if not f.startswith('_')]
return d
with _hide_plugin_deprecation_warnings():
_available_plugins = find_available_plugins()
@deprecate_func(
deprecated_version="0.25",
removed_version="0.27",
hint="The plugin infrastructure of `skimage.io` is deprecated. "
"Instead, use `imageio` or other I/O packages directly.",
)
def call_plugin(kind, *args, **kwargs):
"""Find the appropriate plugin of 'kind' and execute it.
Parameters
----------
kind : {'imshow', 'imsave', 'imread', 'imread_collection'}
Function to look up.
plugin : str, optional
Plugin to load. Defaults to None, in which case the first
matching plugin is used.
*args, **kwargs : arguments and keyword arguments
Passed to the plugin function.
"""
if kind not in plugin_store:
raise ValueError(f'Invalid function ({kind}) requested.')
plugin_funcs = plugin_store[kind]
if len(plugin_funcs) == 0:
msg = (
f"No suitable plugin registered for {kind}.\n\n"
"You may load I/O plugins with the `skimage.io.use_plugin` "
"command. A list of all available plugins are shown in the "
"`skimage.io` docstring."
)
raise RuntimeError(msg)
plugin = kwargs.pop('plugin', None)
if plugin is None:
_, func = plugin_funcs[0]
else:
_load(plugin)
try:
func = [f for (p, f) in plugin_funcs if p == plugin][0]
except IndexError:
raise RuntimeError(f'Could not find the plugin "{plugin}" for {kind}.')
return func(*args, **kwargs)
@deprecate_func(
deprecated_version="0.25",
removed_version="0.27",
hint="The plugin infrastructure of `skimage.io` is deprecated. "
"Instead, use `imageio` or other I/O packages directly.",
)
def use_plugin(name, kind=None):
"""Set the default plugin for a specified operation. The plugin
will be loaded if it hasn't been already.
Parameters
----------
name : str
Name of plugin. See ``skimage.io.available_plugins`` for a list of available
plugins.
kind : {'imsave', 'imread', 'imshow', 'imread_collection', 'imshow_collection'}, optional
Set the plugin for this function. By default,
the plugin is set for all functions.
Examples
--------
To use Matplotlib as the default image reader, you would write:
>>> from skimage import io
>>> io.use_plugin('matplotlib', 'imread') # doctest: +SKIP
To see a list of available plugins run ``skimage.io.available_plugins``. Note
that this lists plugins that are defined, but the full list may not be usable
if your system does not have the required libraries installed.
"""
if kind is None:
kind = plugin_store.keys()
else:
if kind not in plugin_provides[name]:
raise RuntimeError(f"Plugin {name} does not support `{kind}`.")
if kind == 'imshow':
kind = [kind, '_app_show']
else:
kind = [kind]
_load(name)
for k in kind:
if k not in plugin_store:
raise RuntimeError(f"'{k}' is not a known plugin function.")
funcs = plugin_store[k]
# Shuffle the plugins so that the requested plugin stands first
# in line
funcs = [(n, f) for (n, f) in funcs if n == name] + [
(n, f) for (n, f) in funcs if n != name
]
plugin_store[k] = funcs
def _inject_imread_collection_if_needed(module):
"""Add `imread_collection` to module if not already present."""
if not hasattr(module, 'imread_collection') and hasattr(module, 'imread'):
imread = getattr(module, 'imread')
func = imread_collection_wrapper(imread)
setattr(module, 'imread_collection', func)
@_hide_plugin_deprecation_warnings()
def _load(plugin):
"""Load the given plugin.
Parameters
----------
plugin : str
Name of plugin to load.
See Also
--------
plugins : List of available plugins
"""
if plugin in find_available_plugins(loaded=True):
return
if plugin not in plugin_module_name:
raise ValueError(f"Plugin {plugin} not found.")
else:
modname = plugin_module_name[plugin]
plugin_module = __import__('skimage.io._plugins.' + modname, fromlist=[modname])
provides = plugin_provides[plugin]
for p in provides:
if p == 'imread_collection':
_inject_imread_collection_if_needed(plugin_module)
elif not hasattr(plugin_module, p):
print(f"Plugin {plugin} does not provide {p} as advertised. Ignoring.")
continue
store = plugin_store[p]
func = getattr(plugin_module, p)
if (plugin, func) not in store:
store.append((plugin, func))
@deprecate_func(
deprecated_version="0.25",
removed_version="0.27",
hint="The plugin infrastructure of `skimage.io` is deprecated. "
"Instead, use `imageio` or other I/O packages directly.",
)
def plugin_info(plugin):
"""Return plugin meta-data.
Parameters
----------
plugin : str
Name of plugin.
Returns
-------
m : dict
Meta data as specified in plugin ``.ini``.
"""
try:
return plugin_meta_data[plugin]
except KeyError:
raise ValueError(f'No information on plugin "{plugin}"')
@deprecate_func(
deprecated_version="0.25",
removed_version="0.27",
hint="The plugin infrastructure of `skimage.io` is deprecated. "
"Instead, use `imageio` or other I/O packages directly.",
)
def plugin_order():
"""Return the currently preferred plugin order.
Returns
-------
p : dict
Dictionary of preferred plugin order, with function name as key and
plugins (in order of preference) as value.
"""
p = {}
for func in plugin_store:
p[func] = [plugin_name for (plugin_name, f) in plugin_store[func]]
return p
|