filebasedimages
¶
Common interface for any image format–volume or surface, binary or xml.
Template class to implement header protocol |
|
|
Abstract image class with interface for loading/saving images from disk. |
|
Abstract image class for (de)serializing images to/from byte streams/strings. |
FileBasedHeader
¶
- class nibabel.filebasedimages.FileBasedHeader¶
Bases:
object
Template class to implement header protocol
- __init__(*args, **kwargs)¶
- copy() FileBasedHeader ¶
Copy object to independent representation
The copy should not be affected by any changes to the original object.
- classmethod from_header(header=None)¶
FileBasedImage
¶
- class nibabel.filebasedimages.FileBasedImage(header: Optional[Union[FileBasedHeader, Mapping]] = None, extra: Optional[Mapping] = None, file_map: Optional[Mapping[str, FileHolder]] = None)¶
Bases:
object
Abstract image class with interface for loading/saving images from disk.
The class doesn’t define any image properties.
It has:
attributes:
extra
properties:
header
methods:
to_filename(fname) - writes data to filename(s) derived from
fname
, where the derivation may differ between formats.to_file_map() - save image to files with which the image is already associated.
classmethods:
from_filename(fname) - make instance by loading from filename
from_file_map(fmap) - make instance from file map
instance_to_filename(img, fname) - save
img
instance to filenamefname
.
It also has a
header
- some standard set of meta-data that is specific to the image format, andextra
- a dictionary container for any other metadata.You cannot slice an image, and trying to slice an image generates an informative TypeError.
There are several ways of writing data
There is the usual way, which is the default:
img.to_filename(fname)
and that is, to take the data encapsulated by the image and cast it to the datatype the header expects, setting any available header scaling into the header to help the data match.
You can load the data into an image from file with:
img.from_filename(fname)
The image stores its associated files in its
file_map
attribute. In order to just save an image, for which you know there is an associated filename, or other storage, you can do:img.to_file_map()
Files interface
The image has an attribute
file_map
. This is a mapping, that has keys corresponding to the file types that an image needs for storage. For example, the Analyze data format needs animage
and aheader
file type for storage:>>> import numpy as np >>> import nibabel as nib >>> data = np.arange(24, dtype='f4').reshape((2,3,4)) >>> img = nib.AnalyzeImage(data, np.eye(4)) >>> sorted(img.file_map) ['header', 'image']
The values of
file_map
are not in fact files but objects with attributesfilename
,fileobj
andpos
.The reason for this interface, is that the contents of files has to contain enough information so that an existing image instance can save itself back to the files pointed to in
file_map
. When a file holder holds active file-like objects, then these may be affected by the initial file read; in this case, the file-like objects need to carry the position at which a write (withto_file_map
) should place the data. Thefile_map
contents should therefore be such, that this will work.Initialize image
The image is a combination of (header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.
- Parameters:
- headerNone or mapping or header instance, optional
metadata for this image format
- extraNone or mapping, optional
metadata to associate with image that cannot be stored in the metadata of this image type
- file_mapmapping, optional
mapping giving file information for this image format
- __init__(header: Optional[Union[FileBasedHeader, Mapping]] = None, extra: Optional[Mapping] = None, file_map: Optional[Mapping[str, FileHolder]] = None)¶
Initialize image
The image is a combination of (header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.
- Parameters:
- headerNone or mapping or header instance, optional
metadata for this image format
- extraNone or mapping, optional
metadata to associate with image that cannot be stored in the metadata of this image type
- file_mapmapping, optional
mapping giving file information for this image format
- classmethod filespec_to_file_map(filespec: Union[str, PathLike])¶
Make file_map for this class from filename filespec
Class method
- Parameters:
- filespecstr or os.PathLike
Filename that might be for this image file type.
- Returns:
- file_mapdict
file_map dict with (key, value) pairs of (
file_type
, FileHolder instance), wherefile_type
is a string giving the type of the contained file.
- Raises:
- ImageFileError
if filespec is not recognizable as being a filename for this image type.
- classmethod from_file_map(file_map: Mapping[str, FileHolder])¶
- classmethod from_image(img: FileBasedImage)¶
Class method to create new instance of own class from img
- Parameters:
- img
spatialimage
instance In fact, an object with the API of
FileBasedImage
.
- img
- Returns:
- cimg
spatialimage
instance Image, of our own class
- cimg
- get_filename() str | None ¶
Fetch the image filename
- Parameters:
- None
- Returns:
- fnameNone or str
Returns None if there is no filename, or a filename string. If an image may have several filenames associated with it (e.g. Analyze
.img, .hdr
pair) then we return the more characteristic filename (the.img
filename in the case of Analyze’)
- property header: FileBasedHeader¶
- header_class¶
alias of
FileBasedHeader
- classmethod instance_to_filename(img: FileBasedImage, filename: Union[str, PathLike])¶
Save img in our own format, to name implied by filename
This is a class method
- Parameters:
- img
any FileBasedImage
instance - filenamestr
Filename, implying name to which to save image.
- img
- classmethod make_file_map(mapping: Optional[Mapping[str, str | io.IOBase]] = None)¶
Class method to make files holder for this image type
- Parameters:
- mappingNone or mapping, optional
mapping with keys corresponding to image file types (such as ‘image’, ‘header’ etc, depending on image class) and values that are filenames or file-like. Default is None
- Returns:
- file_mapdict
dict with string keys given by first entry in tuples in sequence klass.files_types, and values of type FileHolder, where FileHolder objects have default values, other than those given by mapping
- classmethod path_maybe_image(filename: Union[str, PathLike], sniff: Optional[Tuple[bytes, str]] = None, sniff_max: int = 1024)¶
Return True if filename may be image matching this class
- Parameters:
- filenamestr or os.PathLike
Filename for an image, or an image header (metadata) file. If filename points to an image data file, and the image type has a separate “header” file, we work out the name of the header file, and read from that instead of filename.
- sniffNone or (bytes, filename), optional
Bytes content read from a previous call to this method, on another class, with metadata filename. This allows us to read metadata bytes once from the image or header, and pass this read set of bytes to other image classes, therefore saving a repeat read of the metadata. filename is used to validate that metadata would be read from the same file, re-reading if not. None forces this method to read the metadata.
- sniff_maxint, optional
The maximum number of bytes to read from the metadata. If the metadata file is long enough, we read this many bytes from the file, otherwise we read to the end of the file. Longer values sniff more of the metadata / image file, making it more likely that the returned sniff will be useful for later calls to
path_maybe_image
for other image classes.
- Returns:
- maybe_imagebool
True if filename may be valid for an image of this class.
- sniffNone or (bytes, filename)
Read bytes content from found metadata. May be None if the file does not appear to have useful metadata.
- set_filename(filename: str)¶
Sets the files in the object from a given filename
The different image formats may check whether the filename has an extension characteristic of the format, and raise an error if not.
- Parameters:
- filenamestr or os.PathLike
If the image format only has one file associated with it, this will be the only filename set into the image
.file_map
attribute. Otherwise, the image instance will try and guess the other filenames from this given filename.
- to_file_map(file_map: Optional[Mapping[str, FileHolder]] = None, **kwargs)¶
- to_filename(filename: Union[str, PathLike], **kwargs)¶
Write image to files implied by filename string
- Parameters:
- filenamestr or os.PathLike
filename to which to save image. We will parse filename with
filespec_to_file_map
to work out names for image, header etc.- **kwargskeyword arguments
Keyword arguments to format-specific save
- Returns:
- None
ImageFileError
¶
SerializableImage
¶
- class nibabel.filebasedimages.SerializableImage(header: Optional[Union[FileBasedHeader, Mapping]] = None, extra: Optional[Mapping] = None, file_map: Optional[Mapping[str, FileHolder]] = None)¶
Bases:
FileBasedImage
Abstract image class for (de)serializing images to/from byte streams/strings.
The class doesn’t define any image properties.
It has:
methods:
to_bytes() - serialize image to byte string
classmethods:
from_bytes(bytestring) - make instance by deserializing a byte string
from_url(url) - make instance by fetching and deserializing a URL
Loading from byte strings should provide round-trip equivalence:
img_a = klass.from_bytes(bstr) img_b = klass.from_bytes(img_a.to_bytes()) np.allclose(img_a.get_fdata(), img_b.get_fdata()) np.allclose(img_a.affine, img_b.affine)
Further, for images that are single files on disk, the following methods of loading the image must be equivalent:
img = klass.from_filename(fname) with open(fname, 'rb') as fobj: img = klass.from_bytes(fobj.read())
And the following methods of saving a file must be equivalent:
img.to_filename(fname) with open(fname, 'wb') as fobj: fobj.write(img.to_bytes())
Images that consist of separate header and data files (e.g., Analyze images) currently do not support this interface. For multi-file images,
to_bytes()
andfrom_bytes()
must be overridden, and any encoding details should be documented.Initialize image
The image is a combination of (header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.
- Parameters:
- headerNone or mapping or header instance, optional
metadata for this image format
- extraNone or mapping, optional
metadata to associate with image that cannot be stored in the metadata of this image type
- file_mapmapping, optional
mapping giving file information for this image format
- __init__(header: Optional[Union[FileBasedHeader, Mapping]] = None, extra: Optional[Mapping] = None, file_map: Optional[Mapping[str, FileHolder]] = None)¶
Initialize image
The image is a combination of (header), with optional metadata in extra, and filename / file-like objects contained in the file_map mapping.
- Parameters:
- headerNone or mapping or header instance, optional
metadata for this image format
- extraNone or mapping, optional
metadata to associate with image that cannot be stored in the metadata of this image type
- file_mapmapping, optional
mapping giving file information for this image format
- classmethod from_bytes(bytestring: bytes)¶
Construct image from a byte string
Class method
- Parameters:
- bytestringbytes
Byte string containing the on-disk representation of an image
- classmethod from_stream(io_obj: IOBase)¶
Load image from readable IO stream
Convert to BytesIO to enable seeking, if input stream is not seekable
- Parameters:
- io_objIOBase object
Readable stream
- classmethod from_url(url: str | urllib.request.Request, timeout: float = 5)¶
Retrieve and load an image from a URL
Class method
- Parameters:
- urlstr or urllib.request.Request object
URL of file to retrieve
- timeoutfloat, optional
Time (in seconds) to wait for a response