Core API v2#

Warning

This API exists for backwards compatibility. It is a wrapper around calls to the v3 API and new code should use the v3 API directly. Check the migration instructions below for detailed information on how to migrate.

These functions represent imageio’s main interface for the user. They provide a common API to read and write image data for a large variety of formats. All read and write functions accept keyword arguments, which are passed on to the backend that does the actual work. To see what keyword arguments are supported by a specific format, use the help() function.

Note

All read-functions return images as numpy arrays, and have a meta attribute; the meta-data dictionary can be accessed with im.meta. To make this work, imageio actually makes use of a subclass of np.ndarray. If needed, the image can be converted to a plain numpy array using np.asarray(im).

imageio.help(name=None)[source]#

Print the documentation of the format specified by name, or a list of supported formats if name is omitted.

Parameters:
namestr

Can be the name of a format, a filename extension, or a full filename. See also the formats page.

imageio.show_formats()[source]#

Show a nicely formatted list of available formats

Functions for reading#

imageio.v2.imread(uri[, format])

Reads an image from the specified file.

imageio.v2.mimread(uri[, format, memtest])

Reads multiple images from the specified file.

imageio.v2.volread(uri[, format])

Reads a volume from the specified file.

imageio.v2.mvolread(uri[, format, memtest])

Reads multiple volumes from the specified file.

Functions for writing#

imageio.v2.imwrite(uri, im[, format])

Write an image to the specified file.

imageio.v2.mimwrite(uri, ims[, format])

Write multiple images to the specified file.

imageio.v2.volwrite(uri, vol[, format])

Write a volume to the specified file.

imageio.v2.mvolwrite(uri, vols[, format])

Write multiple volumes to the specified file.

More control#

For a larger degree of control, imageio provides functions get_reader() and get_writer(). They respectively return an Reader and an Writer object, which can be used to read/write data and meta data in a more controlled manner. This also allows specific scientific formats to be exposed in a way that best suits that file-format.

imageio.v2.get_reader(uri, format=None, mode='?', **kwargs)[source]#

Returns a Reader object which can be used to read data and meta data from the specified file.

Parameters:
uri{str, pathlib.Path, bytes, file}

The resource to load the image from, e.g. a filename, pathlib.Path, http address or file object, see the docs for more info.

formatstr

The format to use to read the file. By default imageio selects the appropriate for you based on the filename and its contents.

mode{‘i’, ‘I’, ‘v’, ‘V’, ‘?’}

Used to give the reader a hint on what the user expects (default “?”): “i” for an image, “I” for multiple images, “v” for a volume, “V” for multiple volumes, “?” for don’t care.

kwargs

Further keyword arguments are passed to the reader. See help() to see what arguments are available for a particular format.

imageio.v2.get_writer(uri, format=None, mode='?', **kwargs)[source]#

Returns a Writer object which can be used to write data and meta data to the specified file.

Parameters:
uri{str, pathlib.Path, file}

The resource to write the image to, e.g. a filename, pathlib.Path or file object, see the docs for more info.

formatstr

The format to use to write the file. By default imageio selects the appropriate for you based on the filename.

mode{‘i’, ‘I’, ‘v’, ‘V’, ‘?’}

Used to give the writer a hint on what the user expects (default ‘?’): “i” for an image, “I” for multiple images, “v” for a volume, “V” for multiple volumes, “?” for don’t care.

kwargs

Further keyword arguments are passed to the writer. See help() to see what arguments are available for a particular format.


class imageio.core.format.Reader(format, request)[source]#

The purpose of a reader object is to read data from an image resource, and should be obtained by calling get_reader().

A reader can be used as an iterator to read multiple images, and (if the format permits) only reads data from the file when new data is requested (i.e. streaming). A reader can also be used as a context manager so that it is automatically closed.

Plugins implement Reader’s for different formats. Though rare, plugins may provide additional functionality (beyond what is provided by the base reader class).

Attributes:
closed

Whether the reader/writer is closed.

format

The Format object corresponding to the current read/write operation.

request

The Request object corresponding to the current read/write operation.

close()[source]#

Flush and close the reader/writer. This method has no effect if it is already closed.

property closed[source]#

Whether the reader/writer is closed.

property format[source]#

The Format object corresponding to the current read/write operation.

get_data(index, **kwargs)[source]#

Read image data from the file, using the image index. The returned image has a ‘meta’ attribute with the meta data. Raises IndexError if the index is out of range.

Some formats may support additional keyword arguments. These are listed in the documentation of those formats.

get_length()[source]#

Get the number of images in the file. (Note: you can also use len(reader_object).)

The result can be:
  • 0 for files that only have meta data

  • 1 for singleton images (e.g. in PNG, JPEG, etc.)

  • N for image series

  • inf for streams (series of unknown length)

get_meta_data(index=None)[source]#

Read meta data from the file. using the image index. If the index is omitted or None, return the file’s (global) meta data.

Note that get_data also provides the meta data for the returned image as an atrribute of that image.

The meta data is a dict, which shape depends on the format. E.g. for JPEG, the dict maps group names to subdicts and each group is a dict with name-value pairs. The groups represent the different metadata formats (EXIF, XMP, etc.).

get_next_data(**kwargs)[source]#

Read the next image from the series.

Some formats may support additional keyword arguments. These are listed in the documentation of those formats.

iter_data()[source]#

Iterate over all images in the series. (Note: you can also iterate over the reader object.)

property request[source]#

The Request object corresponding to the current read/write operation.

set_image_index(index)[source]#

Set the internal pointer such that the next call to get_next_data() returns the image specified by the index

class imageio.core.format.Writer(format, request)[source]#

The purpose of a writer object is to write data to an image resource, and should be obtained by calling get_writer().

A writer will (if the format permits) write data to the file as soon as new data is provided (i.e. streaming). A writer can also be used as a context manager so that it is automatically closed.

Plugins implement Writer’s for different formats. Though rare, plugins may provide additional functionality (beyond what is provided by the base writer class).

Attributes:
closed

Whether the reader/writer is closed.

format

The Format object corresponding to the current read/write operation.

request

The Request object corresponding to the current read/write operation.

append_data(im, meta={})[source]#

Append an image (and meta data) to the file. The final meta data that is used consists of the meta data on the given image (if applicable), updated with the given meta data.

close()[source]#

Flush and close the reader/writer. This method has no effect if it is already closed.

property closed[source]#

Whether the reader/writer is closed.

property format[source]#

The Format object corresponding to the current read/write operation.

property request[source]#

The Request object corresponding to the current read/write operation.

set_meta_data(meta)[source]#

Sets the file’s (global) meta data. The meta data is a dict which shape depends on the format. E.g. for JPEG the dict maps group names to subdicts, and each group is a dict with name-value pairs. The groups represents the different metadata formats (EXIF, XMP, etc.).

Note that some meta formats may not be supported for writing, and individual fields may be ignored without warning if they are invalid.

Migrating to the v3 API#

Note

Make sure to have a look at the narrative docs for the v3 API to build some intuition on how to use the new API.

The primary novelty of the v3 API compared to the v2 API is that images are now treated as ndimages, a generalization of (flat) 2D images to N dimensions. This change allows us to design a much simpler API; however, comes with a few backwards incompatible changes.

Avoiding Migration for Legacy Scripts

If you have an old script that you do not wish to migrate, you can avoid most of the migration by explicitly importing the v2 API:

import imageio.v2 as imageio

This will give you access to most of the old API. However, calls will still rely on the new (v3) plugins and backends, which may cause behavioral changes. As such, you should prefer a full migration to v3 and should avoid using the v2 API in new code. This is primarily as a quick way for you to postpone a full migration until it is convenient for you to do so.

Reading Images#

iio.imread can now return a ndimage instead of being limited to flat images. As such, iio.volread has merged into iio.imread and is now gone. Similarily, iio.mimread and iio.mvolread have merged into a new function called iio.imiter, which returns a generator that yields ndimages from a file in the order in which they appear. Further, the default behavior of iio.imread has changed and it has become more context aware. Now it will either return the first stored ndimage (like before) or, depending on the format, all images if this is the more common use-case.

To reproduce similar behavior to the v2 API in cases where the incompatibility matters use one of the following snippets:

# img = iio.v2.imread(image_resource)
img = iio.v3.imread(image_resource, index=...)[0]

# img = iio.v2.volread(image_resource)
img = iio.v3.imread(image_resource)

# img = iio.v2.mimread(image_resource)
# img = iio.v2.mvolread(image_resource)
img = [im for im in iio.v3.imiter(image_resource)]

Writing Images#

Similar to reading images, the new iio.imwrite can handle ndimages and lists of images, like iio.mimwrite and consorts. iio.mimwrite, iio.volwrite, and iio.mvolwrite have all dissapeared. The same goes for their aliases iio.mimsave, iio.volsave, iio.mvolsave, and iio.imsave. They are now all covered by iio.imwrite.

To reproduce similar behavior to the v2 API behavior use one of the following snippets:

# img = iio.v2.imwrite(image_resource, ndimage)
# img = iio.v2.volwrite(image_resource, ndimage)
img = iio.v3.imwrite(image_resource, ndimage)

# img = iio.v2.mimwrite(image_resource, list_of_ndimages)
# img = iio.v2.mvolwrite(image_resource, list_of_ndimages)
img = iio.v3.imwrite(image_resource, list_of_ndimages)

Reader and Writer#

Previously, the reader and writer objects provided an advanced way to read/write data with more control. These are no longer needed. Likewise, the functions iio.get_reader, iio.get_writer, iio.read, and iio.save have become obsolete. Instead, the plugin object is used directly, which is instantiated in mode r (reading) or w (writing). To create such a plugin object, call iio.imopen and use it as a context manager:

# reader = iio.get_reader(image_resource)
# reader = iio.read(image_resource)
with iio.imopen(image_resource, "r") as reader:
    # file is only open/accessible here
    # img = reader.read(index=0)
    # meta = reader.metadata(index=0)
    # ...
    pass


# writer = iio.get_writer(image_resource)
# writer = iio.save(image_resource)
with iio.imopen(image_resource, "w") as writer:
    # file is only open/accessible here
    # writer.write(ndimage)
    # ...
    pass

Metadata#

The v3 API makes handling of metadata much more consistent and explicit. Previously in v2, metadata was provided as a dict that was attached to the image by returning a custom subclass of np.ndarray. Now metadata is served independently from pixel data:

# metadata = iio.imread(image_resource).meta
metadata = iio.immeta(image_resource)

Further, ImageIO now provides a curated set of standardized metadata, which is called ImageProperties, in addition to above metadata. The difference between the two is as follows: The metadata dict contains metadata using format-specific keys to the extent the reading plugin supports them. The ImageProperties dataclass contains generally available metadata using standardized attribute names. Each plugin provides the same set of properties, and if the plugin or format doesn’t provide a field it is set to a default value; usually None. To access ImageProperties use:

props = iio.improps(image_resource)

Caveats and Notes#

This section is a collection of notes and feedback that we got from other developers that were migrating to ImageIO V3, which might be useful to know while you are migrating your own code.

  • The old pillow plugin used to np.squeeze the image before writing it. This has been removed in V3 to match pillows native behavior. A trailing axis with dimension 1, e.g., (256, 256, 1) will now raise an exception. (see #842)