Package qubx :: Module tifffile
[hide private]
[frames] | no frames]

Module tifffile

source code

Read and write image data from and to TIFF files.

Image and meta-data can be read from TIFF, BigTIFF, OME-TIFF, STK, LSM, NIH, ImageJ, MicroManager, FluoView, SEQ and GEL files. Only a subset of the TIFF specification is supported, mainly uncompressed and losslessly compressed 2**(0 to 6) bit integer, 16, 32 and 64-bit float, grayscale and RGB(A) images, which are commonly used in bio-scientific imaging. Specifically, reading JPEG/CCITT compressed image data or EXIF/IPTC/GPS/XMP meta-data is not implemented. Only primary info records are read for STK, FluoView, MicroManager, and NIH image formats.

TIFF, the Tagged Image File Format, is under the control of Adobe Systems. BigTIFF allows for files greater than 4 GB. STK, LSM, FluoView, SEQ, GEL, and OME-TIFF, are custom extensions defined by MetaMorph, Carl Zeiss MicroImaging, Olympus, Media Cybernetics, Molecular Dynamics, and the Open Microscopy Environment consortium respectively.

For command line usage run python tifffile.py --help

Requirements

Notes

The API is not stable yet and might change between revisions.

Tested on little-endian platforms only.

Other Python packages and modules for reading bio-scientific TIFF files: * Imread * PyLibTiff * SimpleITK * PyLSM * PyMca.TiffIO.py * BioImageXD.Readers * Cellcognition.io * CellProfiler.bioformats

Acknowledgements

References

  1. TIFF 6.0 Specification and Supplements. Adobe Systems Incorporated. http://partners.adobe.com/public/developer/tiff/
  2. TIFF File Format FAQ. http://www.awaresystems.be/imaging/tiff/faq.html
  3. MetaMorph Stack (STK) Image File Format. http://support.meta.moleculardevices.com/docs/t10243.pdf
  4. File Format Description - LSM 5xx Release 2.0. http://ibb.gsf.de/homepage/karsten.rodenacker/IDL/Lsmfile.doc
  5. BioFormats. http://www.loci.wisc.edu/ome/formats.html
  6. The OME-TIFF format. http://www.openmicroscopy.org/site/support/file-formats/ome-tiff
  7. TiffDecoder.java http://rsbweb.nih.gov/ij/developer/source/ij/io/TiffDecoder.java.html
  8. UltraQuant(r) Version 6.0 for Windows Start-Up Guide. http://www.ultralum.com/images%20ultralum/pdf/UQStart%20Up%20Guide.pdf
  9. Micro-Manager File Formats. http://www.micro-manager.org/wiki/Micro-Manager_File_Formats

Examples

>>> data = numpy.random.rand(301, 219)
>>> imsave('temp.tif', data)
>>> image = imread('temp.tif')
>>> assert numpy.all(image == data)
>>> tif = TiffFile('test.tif')
>>> images = tif.asarray()
>>> image0 = tif[0].asarray()
>>> for page in tif:
...     for tag in page.tags.values():
...         t = tag.name, tag.value
...     image = page.asarray()
...     if page.is_rgb: pass
...     if page.is_palette:
...         t = page.color_map
...     if page.is_stk:
...         t = page.mm_uic_tags.number_planes
...     if page.is_lsm:
...         t = page.cz_lsm_info
>>> tif.close()

Author: Christoph Gohlke

Organization: Laboratory for Fluorescence Dynamics, University of California, Irvine

Version: 2013.11.03

Classes [hide private]
  lazyattr
Lazy object attribute whose value is computed on first access.
  TiffFile
Read image and meta-data from TIFF, STK, LSM, and FluoView files.
  TiffPage
A TIFF image file directory (IFD).
  TiffTag
A TIFF tag structure.
  TiffSequence
Sequence of image files.
  Record
Dictionary with attribute access.
  TiffTags
Dictionary of TiffTags with attribute access.
  TIFF_SUBFILE_TYPES
  TIFFfile
Read image and meta-data from TIFF, STK, LSM, and FluoView files.
  unicode
str(object='') -> string
Functions [hide private]
 
imsave(filename, data, photometric=None, planarconfig=None, resolution=None, description=None, software='tifffile.py', byteorder=None, bigtiff=False, compress=0, extratags=())
Write image data to TIFF file.
source code
 
imread(files, *args, **kwargs)
Return image data from TIFF file(s) as numpy array.
source code
 
read_bytes(fh, byteorder, dtype, count)
Read tag data from file and return as byte string.
source code
 
read_numpy(fh, byteorder, dtype, count)
Read tag data from file and return as numpy array.
source code
 
read_json(fh, byteorder, dtype, count)
Read tag data from file and return as object.
source code
 
read_mm_header(fh, byteorder, dtype, count)
Read MM_HEADER tag from file and return as numpy.rec.array.
source code
 
read_mm_stamp(fh, byteorder, dtype, count)
Read MM_STAMP tag from file and return as numpy.array.
source code
 
read_mm_uic1(fh, byteorder, dtype, count)
Read MM_UIC1 tag from file and return as dictionary.
source code
 
read_mm_uic2(fh, byteorder, dtype, count)
Read MM_UIC2 tag from file and return as dictionary.
source code
 
read_mm_uic3(fh, byteorder, dtype, count)
Read MM_UIC3 tag from file and return as dictionary.
source code
 
read_mm_uic4(fh, byteorder, dtype, count)
Read MM_UIC4 tag from file and return as dictionary.
source code
 
read_cz_lsm_info(fh, byteorder, dtype, count)
Read CS_LSM_INFO tag from file and return as numpy.rec.array.
source code
 
read_cz_lsm_time_stamps(fh, byteorder)
Read LSM time stamps from file and return as list.
source code
 
read_cz_lsm_event_list(fh, byteorder)
Read LSM events from file and return as list of (time, type, text).
source code
 
read_cz_lsm_scan_info(fh, byteorder)
Read LSM scan information from file and return as Record.
source code
 
read_nih_image_header(fh, byteorder, dtype, count)
Read NIH_IMAGE_HEADER tag from file and return as numpy.rec.array.
source code
 
imagej_metadata(data, bytecounts, byteorder)
Return dict from ImageJ meta data tag value.
source code
 
imagej_description(description)
Return dict from ImageJ image_description tag.
source code
 
read_micromanager_metadata(fh)
Read MicroManager non-TIFF settings from open file and return as dict.
source code
 
_replace_by(module_function, package=None, warn=True)
Try replace decorated function by module.function.
source code
 
decodepackbits(encoded)
Decompress PackBits encoded byte string.
source code
 
decodelzw(encoded)
Decompress LZW (Lempel-Ziv-Welch) encoded TIFF strip (byte string).
source code
 
unpackints(data, dtype, itemsize, runlen=0)
Decompress byte string to array of integers of any bit size <= 32.
source code
 
unpackrgb(data, dtype='<B', bitspersample=(5, 6, 5), rescale=True)
Return array from byte string containing packed samples.
source code
 
reorient(image, orientation)
Return reoriented view of image array.
source code
 
numpy_fromfile(arg, dtype=<type 'float'>, count=-1, sep='')
Return array from data in binary file.
source code
 
stripnull(string)
Return string truncated at first null character.
source code
 
format_size(size)
Return file size as string from byte size.
source code
 
natural_sorted(iterable)
Return human sorted list of strings.
source code
 
datetime_from_timestamp(n, epoch=datetime.datetime(1899, 12, 30, 0, 0))
Return datetime object from timestamp in Excel serial format.
source code
 
test_tifffile(directory='testimages', verbose=True)
Read all images in directory. Print error message on failure.
source code
 
imshow(data, title=None, vmin=0, vmax=None, cmap=None, bitspersample=None, photometric='rgb', interpolation='nearest', dpi=96, figure=None, subplot=111, maxdim=8192, **kwargs)
Plot n-dimensional images using matplotlib.pyplot.
source code
 
_app_show()
Block the GUI. For use as skimage plugin.
source code
 
main(argv=None)
Command line usage main function.
source code
Variables [hide private]
  __version__ = '2013.11.03'
  TIFF_PHOTOMETRICS = {0: 'miniswhite', 1: 'minisblack', 2: 'rgb...
  TIFF_COMPESSIONS = {1: None, 2: 'ccittrle', 3: 'ccittfax3', 4:...
  TIFF_DECOMPESSORS = {None: <__builtin__.function object>, 'ado...
  TIFF_DATA_TYPES = {1: '1B', 2: '1s', 3: '1H', 4: '1I', 5: '2I'...
  TIFF_SAMPLE_FORMATS = {1: 'uint', 2: 'int', 3: 'float', 6: 'co...
  TIFF_SAMPLE_DTYPES = {('complex', 64): 'F', ('complex', 128): ...
  TIFF_ORIENTATIONS = {1: 'top_left', 2: 'top_right', 3: 'bottom...
  AXES_LABELS = {'A': 'angle', 'C': 'channel', 'E': 'lambda', 'F...
  NIH_IMAGE_HEADER = [('fileid', 'a8'), ('nlines', 'i2'), ('pixe...
  MM_TAG_IDS = {0: 'auto_scale', 1: 'min_scale', 2: 'max_scale',...
  MM_DIMENSION = [('name', 'a16'), ('size', 'i4'), ('origin', 'f...
  MM_HEADER = [('header_flag', 'i2'), ('image_type', 'u1'), ('im...
  CZ_LSM_INFO = [('magic_number', 'i4'), ('structure_size', 'i4'...
  CZ_LSM_INFO_READERS = {'event_list': <__builtin__.function obj...
  CZ_SCAN_TYPES = {0: 'XYZCT', 1: 'XYZCT', 2: 'XYZCT', 3: 'XYTCZ...
  CZ_DIMENSIONS = {'C': 'dimension_channels', 'T': 'dimension_ti...
  CZ_DATA_TYPES = {0: 'varying data types', 2: '12 bit unsigned ...
  CZ_LSM_SCAN_INFO_ARRAYS = {285212672: 'timers', 318767104: 'ma...
  CZ_LSM_SCAN_INFO_STRUCTS = {301989888: 'timers', 335544320: 'm...
  CZ_LSM_SCAN_INFO_ATTRIBUTES = {268435457: 'name', 268435458: '...
  TIFF_TAGS = {254: ('new_subfile_type', 0, 4, 1, <qubx.tifffile...
  CUSTOM_TAGS = {700: ('xmp', <__builtin__.function object>), 33...
  PRINT_LINE_LEN = 79
  basestring = str, bytes
  __package__ = 'qubx'
  __warningregistry__ = {('failed to import _tifffile.decodelzw'...
Function Details [hide private]

imsave(filename, data, photometric=None, planarconfig=None, resolution=None, description=None, software='tifffile.py', byteorder=None, bigtiff=False, compress=0, extratags=())

source code 
Write image data to TIFF file.

Image data are written in one stripe per plane.
Dimensions larger than 2 or 3 (depending on photometric mode and
planar configuration) are flattened and saved as separate pages.
The 'sample_format' and 'bits_per_sample' TIFF tags are derived from
the data type.

Parameters
----------
filename : str
    Name of file to write.
data : array_like
    Input image. The last dimensions are assumed to be image height,
    width, and samples.
photometric : {'minisblack', 'miniswhite', 'rgb'}
    The color space of the image data.
    By default this setting is inferred from the data shape.
planarconfig : {'contig', 'planar'}
    Specifies if samples are stored contiguous or in separate planes.
    By default this setting is inferred from the data shape.
    'contig': last dimension contains samples.
    'planar': third last dimension contains samples.
resolution : (float, float) or ((int, int), (int, int))
    X and Y resolution in dots per inch as float or rational numbers.
description : str
    The subject of the image. Saved with the first page only.
software : str
    Name of the software used to create the image.
    Saved with the first page only.
byteorder : {'<', '>'}
    The endianness of the data in the file.
    By default this is the system's native byte order.
bigtiff : bool
    If True, the BigTIFF format is used.
    By default the standard TIFF format is used for data less than 2000 MB.
compress : int
    Values from 0 to 9 controlling the level of zlib compression.
    If 0, data are written uncompressed (default).
extratags: sequence of tuples
    Additional tags as [(code, dtype, count, value, writeonce)].
    code : int
        The TIFF tag Id.
    dtype : str
        Data type of items in `value` in Python struct format.
        One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
    count : int
        Number of data values. Not used for string values.
    value : sequence
        `Count` values compatible with `dtype`.
    writeonce : bool
        If True, the tag is written to the first page only.

Examples
--------
>>> data = numpy.ones((2, 5, 3, 301, 219), 'float32') * 0.5
>>> imsave('temp.tif', data, compress=6)

>>> data = numpy.ones((5, 301, 219, 3), 'uint8') + 127
>>> value = u'{"shape": %s}' % str(list(data.shape))
>>> imsave('temp.tif', data, extratags=[(270, 's', 0, value, True)])

imread(files, *args, **kwargs)

source code 

Return image data from TIFF file(s) as numpy array.

The first image series is returned if no arguments are provided.

Parameters

files : str or list
File name, glob pattern, or list of file names.
key : int, slice, or sequence of page indices
Defines which pages to return as array.
series : int
Defines which series of pages in file to return as array.
multifile : bool
If True (default), OME-TIFF data may include pages from multiple files.
pattern : str
Regular expression pattern that matches axes names and indices in file names.

Examples

>>> im = imread('test.tif', 0)
>>> im.shape
(256, 256, 4)
>>> ims = imread(['test.tif', 'test.tif'])
>>> ims.shape
(2, 256, 256, 4)

read_micromanager_metadata(fh)

source code 

Read MicroManager non-TIFF settings from open file and return as dict.

The settings can be used to read image data without parsing the TIFF file.

Raise ValueError if file does not contain valid MicroManager metadata.

decodepackbits(encoded)

source code 

Decompress PackBits encoded byte string.

PackBits is a simple byte-oriented run-length compression scheme.

Decorators:
  • @_replace_by('_tifffile.decodepackbits')

decodelzw(encoded)

source code 

Decompress LZW (Lempel-Ziv-Welch) encoded TIFF strip (byte string).

The strip must begin with a CLEAR code and end with an EOI code.

This is an implementation of the LZW decoding algorithm described in (1). It is not compatible with old style LZW compressed files like quad-lzw.tif.

Decorators:
  • @_replace_by('_tifffile.decodelzw')

unpackints(data, dtype, itemsize, runlen=0)

source code 

Decompress byte string to array of integers of any bit size <= 32.

Parameters

data : byte str
Data to decompress.
dtype : numpy.dtype or str
A numpy boolean or integer type.
itemsize : int
Number of bits per integer.
runlen : int
Number of consecutive integers, after which to start at next byte.
Decorators:
  • @_replace_by('_tifffile.unpackints')

unpackrgb(data, dtype='<B', bitspersample=(5, 6, 5), rescale=True)

source code 

Return array from byte string containing packed samples.

Use to unpack RGB565 or RGB555 to RGB888 format.

Parameters

data : byte str
The data to be decoded. Samples in each pixel are stored consecutively. Pixels are aligned to 8, 16, or 32 bit boundaries.
dtype : numpy.dtype
The sample data type. The byteorder applies also to the data stream.
bitspersample : tuple
Number of bits for each sample in a pixel.
rescale : bool
Upscale samples to the number of bits in dtype.

Returns

result : ndarray
Flattened array of unpacked samples of native dtype.

Examples

>>> data = struct.pack('BBBB', 0x21, 0x08, 0xff, 0xff)
>>> print(unpackrgb(data, '<B', (5, 6, 5), False))
[ 1  1  1 31 63 31]
>>> print(unpackrgb(data, '<B', (5, 6, 5)))
[  8   4   8 255 255 255]
>>> print(unpackrgb(data, '<B', (5, 5, 5)))
[ 16   8   8 255 255 255]

reorient(image, orientation)

source code 

Return reoriented view of image array.

Parameters

image : numpy array
Non-squeezed output of asarray() functions. Axes -3 and -2 must be image length and width respectively.
orientation : int or str
One of TIFF_ORIENTATIONS keys or values.

numpy_fromfile(arg, dtype=<type 'float'>, count=-1, sep='')

source code 

Return array from data in binary file.

Work around numpy issue #2230, "numpy.fromfile does not accept StringIO object" https://github.com/numpy/numpy/issues/2230.

imshow(data, title=None, vmin=0, vmax=None, cmap=None, bitspersample=None, photometric='rgb', interpolation='nearest', dpi=96, figure=None, subplot=111, maxdim=8192, **kwargs)

source code 

Plot n-dimensional images using matplotlib.pyplot.

Return figure, subplot and plot axis. Requires pyplot already imported from matplotlib import pyplot.

Parameters

bitspersample : int or None
Number of bits per channel in integer RGB images.
photometric : {'miniswhite', 'minisblack', 'rgb', or 'palette'}
The color space of the image data.
title : str
Window and subplot title.
figure : matplotlib.figure.Figure (optional).
Matplotlib to use for plotting.
subplot : int
A matplotlib.pyplot.subplot axis.
maxdim : int
maximum image size in any dimension.
kwargs : optional
Arguments for matplotlib.pyplot.imshow.

Variables Details [hide private]

TIFF_PHOTOMETRICS

Value:
{0: 'miniswhite',
 1: 'minisblack',
 2: 'rgb',
 3: 'palette',
 4: 'mask',
 5: 'separated',
 6: 'cielab',
 7: 'icclab',
...

TIFF_COMPESSIONS

Value:
{1: None,
 2: 'ccittrle',
 3: 'ccittfax3',
 4: 'ccittfax4',
 5: 'lzw',
 6: 'ojpeg',
 7: 'jpeg',
 8: 'adobe_deflate',
...

TIFF_DECOMPESSORS

Value:
{None: <__builtin__.function object>,
 'adobe_deflate': <built-in function decompress>,
 'deflate': <built-in function decompress>,
 'lzw': <__builtin__.function object>,
 'packbits': <__builtin__.function object>}

TIFF_DATA_TYPES

Value:
{1: '1B',
 2: '1s',
 3: '1H',
 4: '1I',
 5: '2I',
 6: '1b',
 7: '1B',
 8: '1h',
...

TIFF_SAMPLE_FORMATS

Value:
{1: 'uint', 2: 'int', 3: 'float', 6: 'complex'}

TIFF_SAMPLE_DTYPES

Value:
{('complex', 64): 'F',
 ('complex', 128): 'D',
 ('float', 16): 'e',
 ('float', 32): 'f',
 ('float', 64): 'd',
 ('int', 8): 'b',
 ('int', 16): 'h',
 ('int', 32): 'i',
...

TIFF_ORIENTATIONS

Value:
{1: 'top_left',
 2: 'top_right',
 3: 'bottom_right',
 4: 'bottom_left',
 5: 'left_top',
 6: 'right_top',
 7: 'right_bottom',
 8: 'left_bottom'}

AXES_LABELS

Value:
{'A': 'angle',
 'C': 'channel',
 'E': 'lambda',
 'F': 'phase',
 'H': 'lifetime',
 'L': 'exposure',
 'P': 'plane',
 'Q': 'other',
...

NIH_IMAGE_HEADER

Value:
[('fileid', 'a8'),
 ('nlines', 'i2'),
 ('pixelsperline', 'i2'),
 ('version', 'i2'),
 ('oldlutmode', 'i2'),
 ('oldncolors', 'i2'),
 ('colors', 'u1', (3, 32)),
 ('oldcolorstart', 'i2'),
...

MM_TAG_IDS

Value:
{0: 'auto_scale',
 1: 'min_scale',
 2: 'max_scale',
 3: 'spatial_calibration',
 8: 'thresh_state',
 9: 'thresh_state_red',
 11: 'thresh_state_green',
 12: 'thresh_state_blue',
...

MM_DIMENSION

Value:
[('name', 'a16'),
 ('size', 'i4'),
 ('origin', 'f8'),
 ('resolution', 'f8'),
 ('unit', 'a64')]

MM_HEADER

Value:
[('header_flag', 'i2'),
 ('image_type', 'u1'),
 ('image_name', 'a257'),
 ('offset_data', 'u4'),
 ('palette_size', 'i4'),
 ('offset_palette0', 'u4'),
 ('offset_palette1', 'u4'),
 ('comment_size', 'i4'),
...

CZ_LSM_INFO

Value:
[('magic_number', 'i4'),
 ('structure_size', 'i4'),
 ('dimension_x', 'i4'),
 ('dimension_y', 'i4'),
 ('dimension_z', 'i4'),
 ('dimension_channels', 'i4'),
 ('dimension_time', 'i4'),
 ('dimension_data_type', 'i4'),
...

CZ_LSM_INFO_READERS

Value:
{'event_list': <__builtin__.function object>,
 'scan_information': <__builtin__.function object>,
 'time_stamps': <__builtin__.function object>}

CZ_SCAN_TYPES

Value:
{0: 'XYZCT',
 1: 'XYZCT',
 2: 'XYZCT',
 3: 'XYTCZ',
 4: 'XYZTC',
 5: 'XYTCZ',
 6: 'XYZTC',
 7: 'XYCTZ',
...

CZ_DIMENSIONS

Value:
{'C': 'dimension_channels',
 'T': 'dimension_time',
 'X': 'dimension_x',
 'Y': 'dimension_y',
 'Z': 'dimension_z'}

CZ_DATA_TYPES

Value:
{0: 'varying data types',
 2: '12 bit unsigned integer',
 5: '32 bit float'}

CZ_LSM_SCAN_INFO_ARRAYS

Value:
{285212672: 'timers',
 318767104: 'markers',
 536870912: 'tracks',
 805306368: 'lasers',
 1610612736: 'detectionchannels',
 2147483648: 'illuminationchannels',
 2684354560: 'beamsplitters',
 3221225472: 'datachannels'}

CZ_LSM_SCAN_INFO_STRUCTS

Value:
{301989888: 'timers',
 335544320: 'markers',
 1073741824: 'tracks',
 1342177280: 'lasers',
 1879048192: 'detectionchannels',
 2415919104: 'illuminationchannels',
 2952790016: 'beamsplitters',
 3489660928: 'datachannels'}

CZ_LSM_SCAN_INFO_ATTRIBUTES

Value:
{268435457: 'name',
 268435458: 'description',
 268435459: 'notes',
 268435460: 'objective',
 268435461: 'processing_summary',
 268435462: 'special_scan_mode',
 268435463: 'oledb_recording_scan_type',
 268435464: 'oledb_recording_scan_mode',
...

TIFF_TAGS

Value:
{254: ('new_subfile_type',
       0,
       4,
       1,
       <qubx.tifffile.TIFF_SUBFILE_TYPES object>),
 255: ('subfile_type',
       None,
       3,
...

CUSTOM_TAGS

Value:
{700: ('xmp', <__builtin__.function object>),
 33628: ('mm_uic1', <__builtin__.function object>),
 33629: ('mm_uic2', <__builtin__.function object>),
 33630: ('mm_uic3', <__builtin__.function object>),
 33631: ('mm_uic4', <__builtin__.function object>),
 33723: ('iptc', <__builtin__.function object>),
 34361: ('mm_header', <__builtin__.function object>),
 34362: ('mm_stamp', <__builtin__.function object>),
...

__warningregistry__

Value:
{('failed to import _tifffile.decodelzw',
  <type 'exceptions.UserWarning'>,
  2170): True,
 ('failed to import _tifffile.decodepackbits',
  <type 'exceptions.UserWarning'>,
  2170): True,
 ('failed to import _tifffile.unpackints',
  <type 'exceptions.UserWarning'>,
...