| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
""" |
| 5 |
|
| 6 |
.. note:: |
| 7 |
imageio is under construction, some details with regard to the |
| 8 |
Reader and Writer classes may change. |
| 9 |
|
| 10 |
These are the main classes of imageio. They expose an interface for |
| 11 |
advanced users and plugin developers. A brief overview: |
| 12 |
|
| 13 |
* imageio.FormatManager - for keeping track of registered formats. |
| 14 |
* imageio.Format - representation of a file format reader/writer |
| 15 |
* imageio.Format.Reader - object used during the reading of a file. |
| 16 |
* imageio.Format.Writer - object used during saving a file. |
| 17 |
* imageio.Request - used to store the filename and other info. |
| 18 |
|
| 19 |
Plugins need to implement a Format class and register |
| 20 |
a format object using ``imageio.formats.add_format()``. |
| 21 |
|
| 22 |
""" |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
import sys |
| 33 |
import warnings |
| 34 |
import contextlib |
| 35 |
|
| 36 |
import numpy as np |
| 37 |
from pathlib import Path |
| 38 |
|
| 39 |
from . import Array, asarray |
| 40 |
from .request import ImageMode |
| 41 |
from ..config import known_plugins, known_extensions, PluginConfig, FileExtension |
| 42 |
from ..config.plugins import _original_order |
| 43 |
from .imopen import imopen |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
MODENAMES = ImageMode |
| 49 |
|
| 50 |
|
| 51 |
def _get_config(plugin): |
| 52 |
"""Old Plugin resolution logic. |
| 53 |
|
| 54 |
Remove once we remove the old format manager. |
| 55 |
""" |
| 56 |
|
| 57 |
extension_name = None |
| 58 |
|
| 59 |
if Path(plugin).suffix.lower() in known_extensions: |
| 60 |
extension_name = Path(plugin).suffix.lower() |
| 61 |
elif plugin in known_plugins: |
| 62 |
pass |
| 63 |
elif plugin.lower() in known_extensions: |
| 64 |
extension_name = plugin.lower() |
| 65 |
elif "." + plugin.lower() in known_extensions: |
| 66 |
extension_name = "." + plugin.lower() |
| 67 |
else: |
| 68 |
raise IndexError(f"No format known by name `{plugin}`.") |
| 69 |
|
| 70 |
if extension_name is not None: |
| 71 |
for plugin_name in [ |
| 72 |
x |
| 73 |
for file_extension in known_extensions[extension_name] |
| 74 |
for x in file_extension.priority |
| 75 |
]: |
| 76 |
if known_plugins[plugin_name].is_legacy: |
| 77 |
plugin = plugin_name |
| 78 |
break |
| 79 |
|
| 80 |
return known_plugins[plugin] |
| 81 |
|
| 82 |
|
| 83 |
class Format(object): |
| 84 |
"""Represents an implementation to read/write a particular file format |
| 85 |
|
| 86 |
A format instance is responsible for 1) providing information about |
| 87 |
a format; 2) determining whether a certain file can be read/written |
| 88 |
with this format; 3) providing a reader/writer class. |
| 89 |
|
| 90 |
Generally, imageio will select the right format and use that to |
| 91 |
read/write an image. A format can also be explicitly chosen in all |
| 92 |
read/write functions. Use ``print(format)``, or ``help(format_name)`` |
| 93 |
to see its documentation. |
| 94 |
|
| 95 |
To implement a specific format, one should create a subclass of |
| 96 |
Format and the Format.Reader and Format.Writer classes. See |
| 97 |
:class:`imageio.plugins` for details. |
| 98 |
|
| 99 |
Parameters |
| 100 |
---------- |
| 101 |
name : str |
| 102 |
A short name of this format. Users can select a format using its name. |
| 103 |
description : str |
| 104 |
A one-line description of the format. |
| 105 |
extensions : str | list | None |
| 106 |
List of filename extensions that this format supports. If a |
| 107 |
string is passed it should be space or comma separated. The |
| 108 |
extensions are used in the documentation and to allow users to |
| 109 |
select a format by file extension. It is not used to determine |
| 110 |
what format to use for reading/saving a file. |
| 111 |
modes : str |
| 112 |
A string containing the modes that this format can handle ('iIvV'), |
| 113 |
“i” for an image, “I” for multiple images, “v” for a volume, |
| 114 |
“V” for multiple volumes. |
| 115 |
This attribute is used in the documentation and to select the |
| 116 |
formats when reading/saving a file. |
| 117 |
""" |
| 118 |
|
| 119 |
def __init__(self, name, description, extensions=None, modes=None): |
| 120 |
"""Initialize the Plugin. |
| 121 |
|
| 122 |
Parameters |
| 123 |
---------- |
| 124 |
name : str |
| 125 |
A short name of this format. Users can select a format using its name. |
| 126 |
description : str |
| 127 |
A one-line description of the format. |
| 128 |
extensions : str | list | None |
| 129 |
List of filename extensions that this format supports. If a |
| 130 |
string is passed it should be space or comma separated. The |
| 131 |
extensions are used in the documentation and to allow users to |
| 132 |
select a format by file extension. It is not used to determine |
| 133 |
what format to use for reading/saving a file. |
| 134 |
modes : str |
| 135 |
A string containing the modes that this format can handle ('iIvV'), |
| 136 |
“i” for an image, “I” for multiple images, “v” for a volume, |
| 137 |
“V” for multiple volumes. |
| 138 |
This attribute is used in the documentation and to select the |
| 139 |
formats when reading/saving a file. |
| 140 |
""" |
| 141 |
|
| 142 |
|
| 143 |
self._name = name.upper() |
| 144 |
self._description = description |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
if extensions is None: |
| 149 |
extensions = [] |
| 150 |
elif isinstance(extensions, str): |
| 151 |
extensions = extensions.replace(",", " ").split(" ") |
| 152 |
|
| 153 |
if isinstance(extensions, (tuple, list)): |
| 154 |
self._extensions = tuple( |
| 155 |
["." + e.strip(".").lower() for e in extensions if e] |
| 156 |
) |
| 157 |
else: |
| 158 |
raise ValueError("Invalid value for extensions given.") |
| 159 |
|
| 160 |
|
| 161 |
self._modes = modes or "" |
| 162 |
if not isinstance(self._modes, str): |
| 163 |
raise ValueError("Invalid value for modes given.") |
| 164 |
for m in self._modes: |
| 165 |
if m not in "iIvV?": |
| 166 |
raise ValueError("Invalid value for mode given.") |
| 167 |
|
| 168 |
def __repr__(self): |
| 169 |
|
| 170 |
return "<Format %s - %s>" % (self.name, self.description) |
| 171 |
|
| 172 |
def __str__(self): |
| 173 |
return self.doc |
| 174 |
|
| 175 |
@property |
| 176 |
def doc(self): |
| 177 |
"""The documentation for this format (name + description + docstring).""" |
| 178 |
|
| 179 |
|
| 180 |
return "%s - %s\n\n %s\n" % ( |
| 181 |
self.name, |
| 182 |
self.description, |
| 183 |
self.__doc__.strip(), |
| 184 |
) |
| 185 |
|
| 186 |
@property |
| 187 |
def name(self): |
| 188 |
"""The name of this format.""" |
| 189 |
return self._name |
| 190 |
|
| 191 |
@property |
| 192 |
def description(self): |
| 193 |
"""A short description of this format.""" |
| 194 |
return self._description |
| 195 |
|
| 196 |
@property |
| 197 |
def extensions(self): |
| 198 |
"""A list of file extensions supported by this plugin. |
| 199 |
These are all lowercase with a leading dot. |
| 200 |
""" |
| 201 |
return self._extensions |
| 202 |
|
| 203 |
@property |
| 204 |
def modes(self): |
| 205 |
"""A string specifying the modes that this format can handle.""" |
| 206 |
return self._modes |
| 207 |
|
| 208 |
def get_reader(self, request): |
| 209 |
"""get_reader(request) |
| 210 |
|
| 211 |
Return a reader object that can be used to read data and info |
| 212 |
from the given file. Users are encouraged to use |
| 213 |
imageio.get_reader() instead. |
| 214 |
""" |
| 215 |
select_mode = request.mode[1] if request.mode[1] in "iIvV" else "" |
| 216 |
if select_mode not in self.modes: |
| 217 |
raise RuntimeError( |
| 218 |
f"Format {self.name} cannot read in {request.mode.image_mode} mode" |
| 219 |
) |
| 220 |
return self.Reader(self, request) |
| 221 |
|
| 222 |
def get_writer(self, request): |
| 223 |
"""get_writer(request) |
| 224 |
|
| 225 |
Return a writer object that can be used to write data and info |
| 226 |
to the given file. Users are encouraged to use |
| 227 |
imageio.get_writer() instead. |
| 228 |
""" |
| 229 |
select_mode = request.mode[1] if request.mode[1] in "iIvV" else "" |
| 230 |
if select_mode not in self.modes: |
| 231 |
raise RuntimeError( |
| 232 |
f"Format {self.name} cannot write in {request.mode.image_mode} mode" |
| 233 |
) |
| 234 |
return self.Writer(self, request) |
| 235 |
|
| 236 |
def can_read(self, request): |
| 237 |
"""can_read(request) |
| 238 |
|
| 239 |
Get whether this format can read data from the specified uri. |
| 240 |
""" |
| 241 |
return self._can_read(request) |
| 242 |
|
| 243 |
def can_write(self, request): |
| 244 |
"""can_write(request) |
| 245 |
|
| 246 |
Get whether this format can write data to the speciefed uri. |
| 247 |
""" |
| 248 |
return self._can_write(request) |
| 249 |
|
| 250 |
def _can_read(self, request): |
| 251 |
"""Check if Plugin can read from ImageResource. |
| 252 |
|
| 253 |
This method is called when the format manager is searching for a format |
| 254 |
to read a certain image. Return True if this format can do it. |
| 255 |
|
| 256 |
The format manager is aware of the extensions and the modes that each |
| 257 |
format can handle. It will first ask all formats that *seem* to be able |
| 258 |
to read it whether they can. If none can, it will ask the remaining |
| 259 |
formats if they can: the extension might be missing, and this allows |
| 260 |
formats to provide functionality for certain extensions, while giving |
| 261 |
preference to other plugins. |
| 262 |
|
| 263 |
If a format says it can, it should live up to it. The format would |
| 264 |
ideally check the request.firstbytes and look for a header of some kind. |
| 265 |
|
| 266 |
Parameters |
| 267 |
---------- |
| 268 |
request : Request |
| 269 |
A request that can be used to access the ImageResource and obtain |
| 270 |
metadata about it. |
| 271 |
|
| 272 |
Returns |
| 273 |
------- |
| 274 |
can_read : bool |
| 275 |
True if the plugin can read from the ImageResource, False otherwise. |
| 276 |
|
| 277 |
""" |
| 278 |
return None |
| 279 |
|
| 280 |
def _can_write(self, request): |
| 281 |
"""Check if Plugin can write to ImageResource. |
| 282 |
|
| 283 |
Parameters |
| 284 |
---------- |
| 285 |
request : Request |
| 286 |
A request that can be used to access the ImageResource and obtain |
| 287 |
metadata about it. |
| 288 |
|
| 289 |
Returns |
| 290 |
------- |
| 291 |
can_read : bool |
| 292 |
True if the plugin can write to the ImageResource, False otherwise. |
| 293 |
|
| 294 |
""" |
| 295 |
return None |
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
class _BaseReaderWriter(object): |
| 300 |
"""Base class for the Reader and Writer class to implement common |
| 301 |
functionality. It implements a similar approach for opening/closing |
| 302 |
and context management as Python's file objects. |
| 303 |
""" |
| 304 |
|
| 305 |
def __init__(self, format, request): |
| 306 |
self.__closed = False |
| 307 |
self._BaseReaderWriter_last_index = -1 |
| 308 |
self._format = format |
| 309 |
self._request = request |
| 310 |
|
| 311 |
self._open(**self.request.kwargs.copy()) |
| 312 |
|
| 313 |
@property |
| 314 |
def format(self): |
| 315 |
"""The :class:`.Format` object corresponding to the current |
| 316 |
read/write operation. |
| 317 |
""" |
| 318 |
return self._format |
| 319 |
|
| 320 |
@property |
| 321 |
def request(self): |
| 322 |
"""The :class:`.Request` object corresponding to the |
| 323 |
current read/write operation. |
| 324 |
""" |
| 325 |
return self._request |
| 326 |
|
| 327 |
def __enter__(self): |
| 328 |
self._checkClosed() |
| 329 |
return self |
| 330 |
|
| 331 |
def __exit__(self, type, value, traceback): |
| 332 |
if value is None: |
| 333 |
|
| 334 |
self.close() |
| 335 |
|
| 336 |
def __del__(self): |
| 337 |
try: |
| 338 |
self.close() |
| 339 |
except Exception: |
| 340 |
pass |
| 341 |
|
| 342 |
def close(self): |
| 343 |
"""Flush and close the reader/writer. |
| 344 |
This method has no effect if it is already closed. |
| 345 |
""" |
| 346 |
if self.__closed: |
| 347 |
return |
| 348 |
self.__closed = True |
| 349 |
self._close() |
| 350 |
|
| 351 |
self.request.finish() |
| 352 |
|
| 353 |
@property |
| 354 |
def closed(self): |
| 355 |
"""Whether the reader/writer is closed.""" |
| 356 |
return self.__closed |
| 357 |
|
| 358 |
def _checkClosed(self, msg=None): |
| 359 |
"""Internal: raise an ValueError if reader/writer is closed""" |
| 360 |
if self.closed: |
| 361 |
what = self.__class__.__name__ |
| 362 |
msg = msg or ("I/O operation on closed %s." % what) |
| 363 |
raise RuntimeError(msg) |
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
def _open(self, **kwargs): |
| 368 |
"""_open(**kwargs) |
| 369 |
|
| 370 |
Plugins should probably implement this. |
| 371 |
|
| 372 |
It is called when reader/writer is created. Here the |
| 373 |
plugin can do its initialization. The given keyword arguments |
| 374 |
are those that were given by the user at imageio.read() or |
| 375 |
imageio.write(). |
| 376 |
""" |
| 377 |
raise NotImplementedError() |
| 378 |
|
| 379 |
def _close(self): |
| 380 |
"""_close() |
| 381 |
|
| 382 |
Plugins should probably implement this. |
| 383 |
|
| 384 |
It is called when the reader/writer is closed. Here the plugin |
| 385 |
can do a cleanup, flush, etc. |
| 386 |
|
| 387 |
""" |
| 388 |
raise NotImplementedError() |
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
class Reader(_BaseReaderWriter): |
| 393 |
""" |
| 394 |
The purpose of a reader object is to read data from an image |
| 395 |
resource, and should be obtained by calling :func:`.get_reader`. |
| 396 |
|
| 397 |
A reader can be used as an iterator to read multiple images, |
| 398 |
and (if the format permits) only reads data from the file when |
| 399 |
new data is requested (i.e. streaming). A reader can also be |
| 400 |
used as a context manager so that it is automatically closed. |
| 401 |
|
| 402 |
Plugins implement Reader's for different formats. Though rare, |
| 403 |
plugins may provide additional functionality (beyond what is |
| 404 |
provided by the base reader class). |
| 405 |
""" |
| 406 |
|
| 407 |
def get_length(self): |
| 408 |
"""get_length() |
| 409 |
|
| 410 |
Get the number of images in the file. (Note: you can also |
| 411 |
use ``len(reader_object)``.) |
| 412 |
|
| 413 |
The result can be: |
| 414 |
* 0 for files that only have meta data |
| 415 |
* 1 for singleton images (e.g. in PNG, JPEG, etc.) |
| 416 |
* N for image series |
| 417 |
* inf for streams (series of unknown length) |
| 418 |
""" |
| 419 |
return self._get_length() |
| 420 |
|
| 421 |
def get_data(self, index, **kwargs): |
| 422 |
"""get_data(index, **kwargs) |
| 423 |
|
| 424 |
Read image data from the file, using the image index. The |
| 425 |
returned image has a 'meta' attribute with the meta data. |
| 426 |
Raises IndexError if the index is out of range. |
| 427 |
|
| 428 |
Some formats may support additional keyword arguments. These are |
| 429 |
listed in the documentation of those formats. |
| 430 |
""" |
| 431 |
self._checkClosed() |
| 432 |
self._BaseReaderWriter_last_index = index |
| 433 |
try: |
| 434 |
im, meta = self._get_data(index, **kwargs) |
| 435 |
except StopIteration: |
| 436 |
raise IndexError(index) |
| 437 |
return Array(im, meta) |
| 438 |
|
| 439 |
def get_next_data(self, **kwargs): |
| 440 |
"""get_next_data(**kwargs) |
| 441 |
|
| 442 |
Read the next image from the series. |
| 443 |
|
| 444 |
Some formats may support additional keyword arguments. These are |
| 445 |
listed in the documentation of those formats. |
| 446 |
""" |
| 447 |
return self.get_data(self._BaseReaderWriter_last_index + 1, **kwargs) |
| 448 |
|
| 449 |
def set_image_index(self, index, **kwargs): |
| 450 |
"""set_image_index(index) |
| 451 |
|
| 452 |
Set the internal pointer such that the next call to |
| 453 |
get_next_data() returns the image specified by the index |
| 454 |
""" |
| 455 |
self._checkClosed() |
| 456 |
n = self.get_length() |
| 457 |
self._BaseReaderWriter_last_index = min(max(index - 1, -1), n) |
| 458 |
|
| 459 |
def get_meta_data(self, index=None): |
| 460 |
"""get_meta_data(index=None) |
| 461 |
|
| 462 |
Read meta data from the file. using the image index. If the |
| 463 |
index is omitted or None, return the file's (global) meta data. |
| 464 |
|
| 465 |
Note that ``get_data`` also provides the meta data for the returned |
| 466 |
image as an attribute of that image. |
| 467 |
|
| 468 |
The meta data is a dict, which shape depends on the format. |
| 469 |
E.g. for JPEG, the dict maps group names to subdicts and each |
| 470 |
group is a dict with name-value pairs. The groups represent |
| 471 |
the different metadata formats (EXIF, XMP, etc.). |
| 472 |
""" |
| 473 |
self._checkClosed() |
| 474 |
meta = self._get_meta_data(index) |
| 475 |
if not isinstance(meta, dict): |
| 476 |
raise ValueError( |
| 477 |
"Meta data must be a dict, not %r" % meta.__class__.__name__ |
| 478 |
) |
| 479 |
return meta |
| 480 |
|
| 481 |
def iter_data(self): |
| 482 |
"""iter_data() |
| 483 |
|
| 484 |
Iterate over all images in the series. (Note: you can also |
| 485 |
iterate over the reader object.) |
| 486 |
|
| 487 |
""" |
| 488 |
self._checkClosed() |
| 489 |
n = self.get_length() |
| 490 |
i = 0 |
| 491 |
while i < n: |
| 492 |
try: |
| 493 |
im, meta = self._get_data(i) |
| 494 |
except StopIteration: |
| 495 |
return |
| 496 |
except IndexError: |
| 497 |
if n == float("inf"): |
| 498 |
return |
| 499 |
raise |
| 500 |
yield Array(im, meta) |
| 501 |
i += 1 |
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
def __iter__(self): |
| 506 |
return self.iter_data() |
| 507 |
|
| 508 |
def __len__(self): |
| 509 |
n = self.get_length() |
| 510 |
if n == float("inf"): |
| 511 |
n = sys.maxsize |
| 512 |
return n |
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
def _get_length(self): |
| 517 |
"""_get_length() |
| 518 |
|
| 519 |
Plugins must implement this. |
| 520 |
|
| 521 |
The returned scalar specifies the number of images in the series. |
| 522 |
See Reader.get_length for more information. |
| 523 |
""" |
| 524 |
raise NotImplementedError() |
| 525 |
|
| 526 |
def _get_data(self, index): |
| 527 |
"""_get_data() |
| 528 |
|
| 529 |
Plugins must implement this, but may raise an IndexError in |
| 530 |
case the plugin does not support random access. |
| 531 |
|
| 532 |
It should return the image and meta data: (ndarray, dict). |
| 533 |
""" |
| 534 |
raise NotImplementedError() |
| 535 |
|
| 536 |
def _get_meta_data(self, index): |
| 537 |
"""_get_meta_data(index) |
| 538 |
|
| 539 |
Plugins must implement this. |
| 540 |
|
| 541 |
It should return the meta data as a dict, corresponding to the |
| 542 |
given index, or to the file's (global) meta data if index is |
| 543 |
None. |
| 544 |
""" |
| 545 |
raise NotImplementedError() |
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
class Writer(_BaseReaderWriter): |
| 550 |
""" |
| 551 |
The purpose of a writer object is to write data to an image |
| 552 |
resource, and should be obtained by calling :func:`.get_writer`. |
| 553 |
|
| 554 |
A writer will (if the format permits) write data to the file |
| 555 |
as soon as new data is provided (i.e. streaming). A writer can |
| 556 |
also be used as a context manager so that it is automatically |
| 557 |
closed. |
| 558 |
|
| 559 |
Plugins implement Writer's for different formats. Though rare, |
| 560 |
plugins may provide additional functionality (beyond what is |
| 561 |
provided by the base writer class). |
| 562 |
""" |
| 563 |
|
| 564 |
def append_data(self, im, meta=None): |
| 565 |
"""append_data(im, meta={}) |
| 566 |
|
| 567 |
Append an image (and meta data) to the file. The final meta |
| 568 |
data that is used consists of the meta data on the given |
| 569 |
image (if applicable), updated with the given meta data. |
| 570 |
""" |
| 571 |
self._checkClosed() |
| 572 |
|
| 573 |
if not isinstance(im, np.ndarray): |
| 574 |
raise ValueError("append_data requires ndarray as first arg") |
| 575 |
|
| 576 |
total_meta = {} |
| 577 |
if hasattr(im, "meta") and isinstance(im.meta, dict): |
| 578 |
total_meta.update(im.meta) |
| 579 |
if meta is None: |
| 580 |
pass |
| 581 |
elif not isinstance(meta, dict): |
| 582 |
raise ValueError("Meta must be a dict.") |
| 583 |
else: |
| 584 |
total_meta.update(meta) |
| 585 |
|
| 586 |
|
| 587 |
im = asarray(im) |
| 588 |
|
| 589 |
return self._append_data(im, total_meta) |
| 590 |
|
| 591 |
def set_meta_data(self, meta): |
| 592 |
"""set_meta_data(meta) |
| 593 |
|
| 594 |
Sets the file's (global) meta data. The meta data is a dict which |
| 595 |
shape depends on the format. E.g. for JPEG the dict maps |
| 596 |
group names to subdicts, and each group is a dict with |
| 597 |
name-value pairs. The groups represents the different |
| 598 |
metadata formats (EXIF, XMP, etc.). |
| 599 |
|
| 600 |
Note that some meta formats may not be supported for |
| 601 |
writing, and individual fields may be ignored without |
| 602 |
warning if they are invalid. |
| 603 |
""" |
| 604 |
self._checkClosed() |
| 605 |
if not isinstance(meta, dict): |
| 606 |
raise ValueError("Meta must be a dict.") |
| 607 |
else: |
| 608 |
return self._set_meta_data(meta) |
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
def _append_data(self, im, meta): |
| 613 |
|
| 614 |
raise NotImplementedError() |
| 615 |
|
| 616 |
def _set_meta_data(self, meta): |
| 617 |
|
| 618 |
raise NotImplementedError() |
| 619 |
|
| 620 |
|
| 621 |
class FormatManager(object): |
| 622 |
""" |
| 623 |
The FormatManager is a singleton plugin factory. |
| 624 |
|
| 625 |
The format manager supports getting a format object using indexing (by |
| 626 |
format name or extension). When used as an iterator, this object |
| 627 |
yields all registered format objects. |
| 628 |
|
| 629 |
See also :func:`.help`. |
| 630 |
""" |
| 631 |
|
| 632 |
@property |
| 633 |
def _formats(self): |
| 634 |
available_formats = list() |
| 635 |
|
| 636 |
for config in known_plugins.values(): |
| 637 |
with contextlib.suppress(ImportError): |
| 638 |
|
| 639 |
if config.is_legacy and config.format is not None: |
| 640 |
available_formats.append(config) |
| 641 |
|
| 642 |
return available_formats |
| 643 |
|
| 644 |
def __repr__(self): |
| 645 |
return f"<imageio.FormatManager with {len(self._formats)} registered formats>" |
| 646 |
|
| 647 |
def __iter__(self): |
| 648 |
return iter(x.format for x in self._formats) |
| 649 |
|
| 650 |
def __len__(self): |
| 651 |
return len(self._formats) |
| 652 |
|
| 653 |
def __str__(self): |
| 654 |
ss = [] |
| 655 |
for config in self._formats: |
| 656 |
ext = config.legacy_args["extensions"] |
| 657 |
desc = config.legacy_args["description"] |
| 658 |
s = f"{config.name} - {desc} [{ext}]" |
| 659 |
ss.append(s) |
| 660 |
return "\n".join(ss) |
| 661 |
|
| 662 |
def __getitem__(self, name): |
| 663 |
warnings.warn( |
| 664 |
"The usage of `FormatManager` is deprecated and it will be " |
| 665 |
"removed in Imageio v3. Use `iio.imopen` instead.", |
| 666 |
DeprecationWarning, |
| 667 |
stacklevel=2, |
| 668 |
) |
| 669 |
|
| 670 |
if not isinstance(name, str): |
| 671 |
raise ValueError( |
| 672 |
"Looking up a format should be done by name or by extension." |
| 673 |
) |
| 674 |
|
| 675 |
if name == "": |
| 676 |
raise ValueError("No format matches the empty string.") |
| 677 |
|
| 678 |
|
| 679 |
if Path(name).is_file(): |
| 680 |
|
| 681 |
try: |
| 682 |
return imopen(name, "r", legacy_mode=True)._format |
| 683 |
except ValueError: |
| 684 |
|
| 685 |
pass |
| 686 |
|
| 687 |
config = _get_config(name.upper()) |
| 688 |
|
| 689 |
try: |
| 690 |
return config.format |
| 691 |
except ImportError: |
| 692 |
raise ImportError( |
| 693 |
f"The `{config.name}` format is not installed. " |
| 694 |
f"Use `pip install imageio[{config.install_name}]` to install it." |
| 695 |
) |
| 696 |
|
| 697 |
def sort(self, *names): |
| 698 |
"""sort(name1, name2, name3, ...) |
| 699 |
|
| 700 |
Sort the formats based on zero or more given names; a format with |
| 701 |
a name that matches one of the given names will take precedence |
| 702 |
over other formats. A match means an equal name, or ending with |
| 703 |
that name (though the former counts higher). Case insensitive. |
| 704 |
|
| 705 |
Format preference will match the order of the given names: using |
| 706 |
``sort('TIFF', '-FI', '-PIL')`` would prefer the FreeImage formats |
| 707 |
over the Pillow formats, but prefer TIFF even more. Each time |
| 708 |
this is called, the starting point is the default format order, |
| 709 |
and calling ``sort()`` with no arguments will reset the order. |
| 710 |
|
| 711 |
Be aware that using the function can affect the behavior of |
| 712 |
other code that makes use of imageio. |
| 713 |
|
| 714 |
Also see the ``IMAGEIO_FORMAT_ORDER`` environment variable. |
| 715 |
""" |
| 716 |
|
| 717 |
warnings.warn( |
| 718 |
"`FormatManager` is deprecated and it will be removed in ImageIO v3." |
| 719 |
" Migrating `FormatManager.sort` depends on your use-case:\n" |
| 720 |
"\t- modify `iio.config.known_plugins` to specify the search order for " |
| 721 |
"unrecognized formats.\n" |
| 722 |
"\t- modify `iio.config.known_extensions[<extension>].priority`" |
| 723 |
" to control a specific extension.", |
| 724 |
DeprecationWarning, |
| 725 |
stacklevel=2, |
| 726 |
) |
| 727 |
|
| 728 |
|
| 729 |
for name in names: |
| 730 |
if not isinstance(name, str): |
| 731 |
raise TypeError("formats.sort() accepts only string names.") |
| 732 |
if any(c in name for c in ".,"): |
| 733 |
raise ValueError( |
| 734 |
"Names given to formats.sort() should not " |
| 735 |
"contain dots `.` or commas `,`." |
| 736 |
) |
| 737 |
|
| 738 |
should_reset = len(names) == 0 |
| 739 |
if should_reset: |
| 740 |
names = _original_order |
| 741 |
|
| 742 |
sane_names = [name.strip().upper() for name in names if name != ""] |
| 743 |
|
| 744 |
|
| 745 |
flat_extensions = [ |
| 746 |
ext for ext_list in known_extensions.values() for ext in ext_list |
| 747 |
] |
| 748 |
for extension in flat_extensions: |
| 749 |
if should_reset: |
| 750 |
extension.reset() |
| 751 |
continue |
| 752 |
|
| 753 |
for name in reversed(sane_names): |
| 754 |
for plugin in [x for x in extension.default_priority]: |
| 755 |
if plugin.endswith(name): |
| 756 |
extension.priority.remove(plugin) |
| 757 |
extension.priority.insert(0, plugin) |
| 758 |
|
| 759 |
old_order = known_plugins.copy() |
| 760 |
known_plugins.clear() |
| 761 |
|
| 762 |
for name in sane_names: |
| 763 |
plugin = old_order.pop(name, None) |
| 764 |
if plugin is not None: |
| 765 |
known_plugins[name] = plugin |
| 766 |
|
| 767 |
known_plugins.update(old_order) |
| 768 |
|
| 769 |
def add_format(self, iio_format, overwrite=False): |
| 770 |
"""add_format(format, overwrite=False) |
| 771 |
|
| 772 |
Register a format, so that imageio can use it. If a format with the |
| 773 |
same name already exists, an error is raised, unless overwrite is True, |
| 774 |
in which case the current format is replaced. |
| 775 |
""" |
| 776 |
|
| 777 |
warnings.warn( |
| 778 |
"`FormatManager` is deprecated and it will be removed in ImageIO v3." |
| 779 |
"To migrate `FormatManager.add_format` add the plugin directly to " |
| 780 |
"`iio.config.known_plugins`.", |
| 781 |
DeprecationWarning, |
| 782 |
stacklevel=2, |
| 783 |
) |
| 784 |
|
| 785 |
if not isinstance(iio_format, Format): |
| 786 |
raise ValueError("add_format needs argument to be a Format object") |
| 787 |
elif not overwrite and iio_format.name in self.get_format_names(): |
| 788 |
raise ValueError( |
| 789 |
f"A Format named {iio_format.name} is already registered, use" |
| 790 |
" `overwrite=True` to replace." |
| 791 |
) |
| 792 |
|
| 793 |
config = PluginConfig( |
| 794 |
name=iio_format.name.upper(), |
| 795 |
class_name=iio_format.__class__.__name__, |
| 796 |
module_name=iio_format.__class__.__module__, |
| 797 |
is_legacy=True, |
| 798 |
install_name="unknown", |
| 799 |
legacy_args={ |
| 800 |
"name": iio_format.name, |
| 801 |
"description": iio_format.description, |
| 802 |
"extensions": " ".join(iio_format.extensions), |
| 803 |
"modes": iio_format.modes, |
| 804 |
}, |
| 805 |
) |
| 806 |
|
| 807 |
known_plugins[config.name] = config |
| 808 |
|
| 809 |
for extension in iio_format.extensions: |
| 810 |
|
| 811 |
ext = FileExtension( |
| 812 |
extension=extension, |
| 813 |
priority=[config.name], |
| 814 |
name="Unique Format", |
| 815 |
description="A format inserted at runtime." |
| 816 |
f" It is being read by the `{config.name}` plugin.", |
| 817 |
) |
| 818 |
known_extensions.setdefault(extension, list()).append(ext) |
| 819 |
|
| 820 |
def search_read_format(self, request): |
| 821 |
"""search_read_format(request) |
| 822 |
|
| 823 |
Search a format that can read a file according to the given request. |
| 824 |
Returns None if no appropriate format was found. (used internally) |
| 825 |
""" |
| 826 |
|
| 827 |
try: |
| 828 |
|
| 829 |
return imopen(request, request.mode.io_mode, legacy_mode=True)._format |
| 830 |
except AttributeError: |
| 831 |
warnings.warn( |
| 832 |
"ImageIO now uses a v3 plugin when reading this format." |
| 833 |
" Please migrate to the v3 API (preferred) or use imageio.v2.", |
| 834 |
DeprecationWarning, |
| 835 |
stacklevel=2, |
| 836 |
) |
| 837 |
return None |
| 838 |
except ValueError: |
| 839 |
|
| 840 |
|
| 841 |
return None |
| 842 |
|
| 843 |
def search_write_format(self, request): |
| 844 |
"""search_write_format(request) |
| 845 |
|
| 846 |
Search a format that can write a file according to the given request. |
| 847 |
Returns None if no appropriate format was found. (used internally) |
| 848 |
""" |
| 849 |
|
| 850 |
try: |
| 851 |
|
| 852 |
return imopen(request, request.mode.io_mode, legacy_mode=True)._format |
| 853 |
except AttributeError: |
| 854 |
warnings.warn( |
| 855 |
"ImageIO now uses a v3 plugin when writing this format." |
| 856 |
" Please migrate to the v3 API (preferred) or use imageio.v2.", |
| 857 |
DeprecationWarning, |
| 858 |
stacklevel=2, |
| 859 |
) |
| 860 |
return None |
| 861 |
except ValueError: |
| 862 |
|
| 863 |
|
| 864 |
return None |
| 865 |
|
| 866 |
def get_format_names(self): |
| 867 |
"""Get the names of all registered formats.""" |
| 868 |
|
| 869 |
warnings.warn( |
| 870 |
"`FormatManager` is deprecated and it will be removed in ImageIO v3." |
| 871 |
"To migrate `FormatManager.get_format_names` use `iio.config.known_plugins.keys()` instead.", |
| 872 |
DeprecationWarning, |
| 873 |
stacklevel=2, |
| 874 |
) |
| 875 |
|
| 876 |
return [f.name for f in self._formats] |
| 877 |
|
| 878 |
def show(self): |
| 879 |
"""Show a nicely formatted list of available formats""" |
| 880 |
print(self) |