Imageio’s developer API

This page lists the developer documentation for imageio. Normal users will generally not need this, except perhaps the Format class. All these functions and classes are available in the imageio.core namespace.

This subpackage provides the core functionality of imageio (everything but the plugins).

Functions: appdata_dir(), asarray(), get_platform(), get_remote_file(), has_module(), image_as_uint(), load_lib(), read_n_bytes(), resource_dirs(), urlopen()

Classes: Array, BaseProgressIndicator, Dict, Format, FormatManager, Image, InternetNotAllowedError, NeedDownloadError, Request, StdoutProgressIndicator


imageio.core.appdata_dir(appname=None, roaming=False)

Get the path to the application directory, where applications are allowed to write user specific files (e.g. configurations). For non-user specific data, consider using common_appdata_dir(). If appname is given, a subdir is appended (and created if necessary). If roaming is True, will prefer a roaming directory (Windows Vista/7).

imageio.core.asarray(a)

Pypy-safe version of np.asarray. Pypy’s np.asarray consumes a lot of memory if the given array is an ndarray subclass. This function does not.

imageio.core.get_platform()

Get a string that specifies the platform more specific than sys.platform does. The result can be: linux32, linux64, win32, win64, osx32, osx64. Other platforms may be added in the future.

imageio.core.get_remote_file(fname, directory=None, force_download=False, auto=True)

Get a the filename for the local version of a file from the web

Parameters:
fname : str

The relative filename on the remote data repository to download. These correspond to paths on https://github.com/imageio/imageio-binaries/.

directory : str | None

The directory where the file will be cached if a download was required to obtain the file. By default, the appdata directory is used. This is also the first directory that is checked for a local version of the file. If the directory does not exist, it will be created.

force_download : bool | str

If True, the file will be downloaded even if a local copy exists (and this copy will be overwritten). Can also be a YYYY-MM-DD date to ensure a file is up-to-date (modified date of a file on disk, if present, is checked).

auto : bool

Whether to auto-download the file if its not present locally. Default True. If False and a download is needed, raises NeedDownloadError.

Returns:
fname : str

The path to the file on the local system.

imageio.core.has_module(module_name)

Check to see if a python module is available.

imageio.core.image_as_uint(im, bitdepth=None)

Convert the given image to uint (default: uint8)

If the dtype already matches the desired format, it is returned as-is. If the image is float, and all values are between 0 and 1, the values are multiplied by np.power(2.0, bitdepth). In all other situations, the values are scaled such that the minimum value becomes 0 and the maximum value becomes np.power(2.0, bitdepth)-1 (255 for 8-bit and 65535 for 16-bit).

imageio.core.load_lib(exact_lib_names, lib_names, lib_dirs=None)

Load a dynamic library.

This function first tries to load the library from the given exact names. When that fails, it tries to find the library in common locations. It searches for files that start with one of the names given in lib_names (case insensitive). The search is performed in the given lib_dirs and a set of common library dirs.

Returns (ctypes_library, library_path)

imageio.core.read_n_bytes(file, n)

Read n bytes from the given file, or less if the file has less bytes. Returns zero bytes if the file is closed.

imageio.core.resource_dirs()

Get a list of directories where imageio resources may be located. The first directory in this list is the “resources” directory in the package itself. The second directory is the appdata directory (~/.imageio on Linux). The list further contains the application directory (for frozen apps), and may include additional directories in the future.

imageio.core.urlopen(*args, **kwargs)

Compatibility function for the urlopen function. Raises an RuntimeError if urlopen could not be imported (which can occur in frozen applications.

class imageio.core.Array(array, meta=None)

A subclass of np.ndarray that has a meta attribute. Get the dictionary that contains the meta data using im.meta. Convert to a plain numpy array using np.asarray(im).

Attributes:
T

Same as self.transpose(), except that self is returned if self.ndim < 2.

base

Base object if memory is from some other object.

ctypes

An object to simplify the interaction of the array with the ctypes module.

data

Python buffer object pointing to the start of the array’s data.

dtype

Data-type of the array’s elements.

flags

Information about the memory layout of the array.

flat

A 1-D iterator over the array.

imag

The imaginary part of the array.

itemsize

Length of one array element in bytes.

meta

The dict with the meta data of this image.

nbytes

Total bytes consumed by the elements of the array.

ndim

Number of array dimensions.

real

The real part of the array.

shape

Tuple of array dimensions.

size

Number of elements in the array.

strides

Tuple of bytes to step in each dimension when traversing an array.

meta

The dict with the meta data of this image.

class imageio.core.BaseProgressIndicator(name)

A progress indicator helps display the progres of a task to the user. Progress can be pending, running, finished or failed.

Each task has:
  • a name - a short description of what needs to be done.
  • an action - the current action in performing the task (e.g. a subtask)
  • progress - how far the task is completed
  • max - max number of progress units. If 0, the progress is indefinite
  • unit - the units in which the progress is counted
  • status - 0: pending, 1: in progress, 2: finished, 3: failed

This class defines an abstract interface. Subclasses should implement _start, _stop, _update_progress(progressText), _write(message).

fail(message=None)

Stop the progress with a failure, optionally specifying a message.

finish(message=None)

Finish the progress, optionally specifying a message. This will not set the progress to the maximum.

increase_progress(extra_progress)

Increase the progress by a certain amount.

set_progress(progress=0, force=False)

Set the current progress. To avoid unnecessary progress updates this will only have a visual effect if the time since the last update is > 0.1 seconds, or if force is True.

start(action='', unit='', max=0)

Start the progress. Optionally specify an action, a unit, and a maxium progress value.

status()

Get the status of the progress - 0: pending, 1: in progress, 2: finished, 3: failed

write(message)

Write a message during progress (such as a warning).

class imageio.core.Dict

A dict in which the keys can be get and set as if they were attributes. Very convenient in combination with autocompletion.

This Dict still behaves as much as possible as a normal dict, and keys can be anything that are otherwise valid keys. However, keys that are not valid identifiers or that are names of the dict class (such as ‘items’ and ‘copy’) cannot be get/set as attributes.

class imageio.core.Format(name, description, extensions=None, modes=None)

Represents an implementation to read/write a particular file format

A format instance is responsible for 1) providing information about a format; 2) determining whether a certain file can be read/written with this format; 3) providing a reader/writer class.

Generally, imageio will select the right format and use that to read/write an image. A format can also be explicitly chosen in all read/write functions. Use print(format), or help(format_name) to see its documentation.

To implement a specific format, one should create a subclass of Format and the Format.Reader and Format.Writer classes. see Creating imageio plugins for details.

Parameters:
name : str

A short name of this format. Users can select a format using its name.

description : str

A one-line description of the format.

extensions : str | list | None

List of filename extensions that this format supports. If a string is passed it should be space or comma separated. The extensions are used in the documentation and to allow users to select a format by file extension. It is not used to determine what format to use for reading/saving a file.

modes : str

A string containing the modes that this format can handle (‘iIvV’), “i” for an image, “I” for multiple images, “v” for a volume, “V” for multiple volumes. This attribute is used in the documentation and to select the formats when reading/saving a file.

Attributes:
Reader
Writer
description

A short description of this format.

doc

The documentation for this format (name + description + docstring).

extensions

A list of file extensions supported by this plugin.

modes

A string specifying the modes that this format can handle.

name

The name of this format.

can_read(request)

Get whether this format can read data from the specified uri.

can_write(request)

Get whether this format can write data to the speciefed uri.

description

A short description of this format.

doc

The documentation for this format (name + description + docstring).

extensions

A list of file extensions supported by this plugin. These are all lowercase with a leading dot.

get_reader(request)

Return a reader object that can be used to read data and info from the given file. Users are encouraged to use imageio.get_reader() instead.

get_writer(request)

Return a writer object that can be used to write data and info to the given file. Users are encouraged to use imageio.get_writer() instead.

modes

A string specifying the modes that this format can handle.

name

The name of this format.

class imageio.core.FormatManager

There is exactly one FormatManager object in imageio: imageio.formats. Its purpose it to keep track of the registered formats.

The format manager supports getting a format object using indexing (by format name or extension). When used as an iterator, this object yields all registered format objects.

See also help().

add_format(format, overwrite=False)

Register a format, so that imageio can use it. If a format with the same name already exists, an error is raised, unless overwrite is True, in which case the current format is replaced.

get_format_names()

Get the names of all registered formats.

search_read_format(request)

Search a format that can read a file according to the given request. Returns None if no appropriate format was found. (used internally)

search_write_format(request)

Search a format that can write a file according to the given request. Returns None if no appropriate format was found. (used internally)

show()

Show a nicely formatted list of available formats

sort(name1, name2, name3, ...)

Sort the formats based on zero or more given names; a format with a name that matches one of the given names will take precedence over other formats. A match means an equal name, or ending with that name (though the former counts higher). Case insensitive.

Format preference will match the order of the given names: using sort('TIFF', '-FI', '-PIL') would prefer the FreeImage formats over the Pillow formats, but prefer TIFF even more. Each time this is called, the starting point is the default format order, and calling sort() with no arguments will reset the order.

Be aware that using the function can affect the behavior of other code that makes use of imageio.

Also see the IMAGEIO_FORMAT_ORDER environment variable.

imageio.core.Image

alias of imageio.core.util.Array

exception imageio.core.InternetNotAllowedError

Plugins that need resources can just use get_remote_file(), but should catch this error and silently ignore it.

exception imageio.core.NeedDownloadError

Is raised when a remote file is requested that is not locally available, but which needs to be explicitly downloaded by the user.

class imageio.core.Request(uri, mode, **kwargs)

Represents a request for reading or saving an image resource. This object wraps information to that request and acts as an interface for the plugins to several resources; it allows the user to read from filenames, files, http, zipfiles, raw bytes, etc., but offer a simple interface to the plugins via get_file() and get_local_filename().

For each read/write operation a single Request instance is used and passed to the can_read/can_write method of a format, and subsequently to the Reader/Writer class. This allows rudimentary passing of information between different formats and between a format and associated reader/writer.

Parameters:
uri : {str, bytes, file}

The resource to load the image from.

mode : str

The first character is “r” or “w”, indicating a read or write request. The second character is used to indicate the kind of data: “i” for an image, “I” for multiple images, “v” for a volume, “V” for multiple volumes, “?” for don’t care.

Attributes:
extension

The (lowercase) extension of the requested filename.

filename

The uri for which reading/saving was requested.

firstbytes

The first 256 bytes of the file.

kwargs

The dict of keyword arguments supplied by the user.

mode

The mode of the request.

extension

The (lowercase) extension of the requested filename. Suffixes in url’s are stripped. Can be None if the request is not based on a filename.

filename

The uri for which reading/saving was requested. This can be a filename, an http address, or other resource identifier. Do not rely on the filename to obtain the data, but use get_file() or get_local_filename() instead.

finish()

For internal use (called when the context of the reader/writer exits). Finishes this request. Close open files and process results.

firstbytes

The first 256 bytes of the file. These can be used to parse the header to determine the file-format.

get_file()

Get a file object for the resource associated with this request. If this is a reading request, the file is in read mode, otherwise in write mode. This method is not thread safe. Plugins should not close the file when done.

This is the preferred way to read/write the data. But if a format cannot handle file-like objects, they should use get_local_filename().

get_local_filename()

If the filename is an existing file on this filesystem, return that. Otherwise a temporary file is created on the local file system which can be used by the format to read from or write to.

get_result()

For internal use. In some situations a write action can have a result (bytes data). That is obtained with this function.

kwargs

The dict of keyword arguments supplied by the user.

mode

The mode of the request. The first character is “r” or “w”, indicating a read or write request. The second character is used to indicate the kind of data: “i” for an image, “I” for multiple images, “v” for a volume, “V” for multiple volumes, “?” for don’t care.

class imageio.core.StdoutProgressIndicator(name)

A progress indicator that shows the progress in stdout. It assumes that the tty can appropriately deal with backspace characters.