TiffWriter

final class tifffile.TiffWriter(file, /, *, mode=None, bigtiff=False, byteorder=None, append=False, imagej=False, ome=None, shaped=None)

Write NumPy arrays to TIFF file.

TiffWriter’s main purpose is saving multi-dimensional NumPy arrays in TIFF containers, not to create any possible TIFF format. Specifically, ExifIFD and GPSIFD tags are not supported.

TiffWriter instances must be closed with TiffWriter.close(), which is automatically called when using the ‘with’ context manager.

TiffWriter instances are not thread-safe. All attributes are read-only.

Parameters:
  • file (str | os.PathLike[Any] | FileHandle | IO[bytes]) – Specifies file to write.

  • mode (Literal['w', 'x', 'r+'] | None) – Binary file open mode if file is file name. The default is ‘w’, which opens files for writing, truncating existing files. ‘x’ opens files for exclusive creation, failing on existing files. ‘r+’ opens files for updating, enabling append.

  • bigtiff (bool) – Write 64-bit BigTIFF formatted file, which can exceed 4 GB. By default, a classic 32-bit TIFF file is written, which is limited to 4 GB. If append is True, the existing file’s format is used.

  • byteorder (ByteOrder | None) – Endianness of TIFF format. One of ‘<’, ‘>’, ‘=’, or ‘|’. The default is the system’s native byte order.

  • append (bool | str) – If file is existing standard TIFF file, append image data and tags to file. Parameters bigtiff and byteorder set from existing file. Appending does not scale well with the number of pages already in the file and may corrupt specifically formatted TIFF files such as OME-TIFF, LSM, STK, ImageJ, or FluoView.

  • imagej (bool) – Write ImageJ hyperstack compatible file if ome is not enabled. This format can handle data types uint8, uint16, or float32 and data shapes up to 6 dimensions in TZCYXS order. RGB images (S=3 or S=4) must be uint8. ImageJ’s default byte order is big-endian, but this implementation uses the system’s native byte order by default. ImageJ hyperstacks do not support BigTIFF or compression. The ImageJ file format is undocumented. Use FIJI’s Bio-Formats import function for compressed files.

  • ome (bool | None) – Write OME-TIFF compatible file. By default, the OME-TIFF format is used if the file name extension contains ‘.ome.’, imagej is not enabled, and the description argument in the first call of TiffWriter.write() is not specified. The format supports multiple, up to 9 dimensional image series. The default axes order is TZC(S)YX(S). Refer to the OME model for restrictions of this format.

  • shaped (bool | None) – Write tifffile “shaped” compatible file. The shape of multi-dimensional images is stored in JSON format in a ImageDescription tag of the first page of a series. This is the default format used by tifffile unless imagej or ome are enabled or metadata=None is passed to TiffWriter.write().

Raises:

ValueError – The TIFF file cannot be appended to. Use append='force' to force appending, which may result in a corrupted file.

tiff: TiffFormat

Format of TIFF file being written.

write(data=None, *, shape=None, dtype=None, photometric=None, planarconfig=None, extrasamples=None, volumetric=False, tile=None, rowsperstrip=None, bitspersample=None, compression=None, compressionargs=None, predictor=None, subsampling=None, jpegtables=None, iccprofile=None, colormap=None, description=None, datetime=None, resolution=None, resolutionunit=None, subfiletype=None, software=None, subifds=None, metadata={}, extratags=None, contiguous=False, truncate=False, align=None, maxworkers=None, buffersize=None, returnoffset=False)

Write multi-dimensional image to series of TIFF pages.

Metadata in JSON, ImageJ, or OME-XML format are written to the ImageDescription tag of the first page of a series by default, such that the image can later be read back as an array of the same shape.

The values of the ImageWidth, ImageLength, ImageDepth, and SamplesPerPixel tags are inferred from the last dimensions of the data’s shape. The value of the SampleFormat tag is inferred from the data’s dtype. Image data are written uncompressed in one strip per plane by default. Dimensions higher than 2 to 4 (depending on photometric mode, planar configuration, and volumetric mode) are flattened and written as separate pages. If the data size is zero, write a single page with shape (0, 0).

Parameters:
  • data (ArrayLike | Iterator[NDArray[Any] | None] | Iterator[bytes] | None) – Specifies image to write. If None, an empty image is written, which size and type must be specified using shape and dtype arguments. This option cannot be used with compression, predictors, packed integers, or bilevel images. A copy of array-like data is made if it is not a C-contiguous numpy or dask array with the same byteorder as the TIFF file. Iterators must yield ndarrays or bytes compatible with the file’s byteorder as well as the shape and dtype arguments. Iterator bytes must be compatible with the compression, predictor, subsampling, and jpegtables arguments. If tile is specified, iterator items must match the tile shape. Incomplete tiles are zero-padded. Iterators of non-tiled images must yield ndarrays of shape[1:] or strips as bytes. Iterators of strip ndarrays are not supported. Writing dask arrays might be excruciatingly slow for arrays with many chunks or files with many segments. (https://github.com/dask/dask/issues/8570).

  • shape (Sequence[int] | None) – Shape of image to write. The default is inferred from the data argument if possible. A ValueError is raised if the value is incompatible with the data or other arguments.

  • dtype (DTypeLike | None) – NumPy data type of image to write. The default is inferred from the data argument if possible. A ValueError is raised if the value is incompatible with the data argument.

  • photometric (PHOTOMETRIC | int | str | None) – Color space of image. The default is inferred from the data shape, dtype, and the colormap argument. A UserWarning is logged if RGB color space is auto-detected. Specify this parameter to silence the warning and to avoid ambiguities. MINISBLACK: for bilevel and grayscale images, 0 is black. MINISWHITE: for bilevel and grayscale images, 0 is white. RGB: the image contains red, green and blue samples. SEPARATED: the image contains CMYK samples. PALETTE: the image is used as an index into a colormap. CFA: the image is a Color Filter Array. The CFARepeatPatternDim, CFAPattern, and other DNG or TIFF/EP tags must be specified in extratags to produce a valid file. The value is written to the PhotometricInterpretation tag.

  • planarconfig (PLANARCONFIG | int | str | None) – Specifies if samples are stored interleaved or in separate planes. CONTIG: the last dimension contains samples. SEPARATE: the 3rd or 4th last dimension contains samples. The default is inferred from the data shape and photometric mode. If this parameter is set, extra samples are used to store grayscale images. The value is written to the PlanarConfiguration tag.

  • extrasamples (Sequence[EXTRASAMPLE | int | str] | None) – Interpretation of extra components in pixels. UNSPECIFIED: no transparency information (default). ASSOCALPHA: true transparency with premultiplied color. UNASSALPHA: independent transparency masks. The values are written to the ExtraSamples tag.

  • volumetric (bool) – Write volumetric image to single page (instead of multiple pages) using SGI ImageDepth tag. The volumetric format is not part of the TIFF specification, and few software can read it. OME and ImageJ formats are not compatible with volumetric storage.

  • tile (Sequence[int] | None) – Shape ([depth,] length, width) of image tiles to write. By default, image data are written in strips. The tile length and width must be a multiple of 16. If a tile depth is provided, the SGI ImageDepth and TileDepth tags are used to write volumetric data. Tiles cannot be used to write contiguous series, except if the tile shape matches the data shape. The values are written to the TileWidth, TileLength, and TileDepth tags.

  • rowsperstrip (int | None) – Number of rows per strip. By default, strips are about 256 KB if compression is enabled, else rowsperstrip is set to the image length. The value is written to the RowsPerStrip tag.

  • bitspersample (int | None) – Number of bits per sample. The default is the number of bits of the data’s dtype. Different values per samples are not supported. Unsigned integer data are packed into bytes as tightly as possible. Valid values are 1-8 for uint8, 9-16 for uint16, and 17-32 for uint32. This setting cannot be used with compression, contiguous series, or empty files. The value is written to the BitsPerSample tag.

  • compression (COMPRESSION | int | str | bool | None) – Compression scheme used on image data. By default, image data are written uncompressed. Compression cannot be used to write contiguous series. Compressors may require certain data shapes, types or value ranges. For example, JPEG compression requires grayscale or RGB(A), uint8 or 12-bit uint16. JPEG compression is experimental. JPEG markers and TIFF tags may not match. Only a limited set of compression schemes are implemented. ‘ZLIB’ is short for ADOBE_DEFLATE. The value is written to the Compression tag.

  • compressionargs (dict[str, Any] | None) – Extra arguments passed to compression codec, for example, compression level. Refer to the Imagecodecs implementation for supported arguments.

  • predictor (PREDICTOR | int | str | bool | None) – Horizontal differencing operator applied to image data before compression. By default, no operator is applied. Predictors can only be used with certain compression schemes and data types. The value is written to the Predictor tag.

  • subsampling (tuple[int, int] | None) – Horizontal and vertical subsampling factors used for the chrominance components of images: (1, 1), (2, 1), (2, 2), or (4, 1). The default is (2, 2). Currently applies to JPEG compression of RGB images only. Images are stored in YCbCr color space, the value of the PhotometricInterpretation tag is YCBCR. Segment widths must be a multiple of 8 times the horizontal factor. Segment lengths and rowsperstrip must be a multiple of 8 times the vertical factor. The values are written to the YCbCrSubSampling tag.

  • jpegtables (bytes | None) – JPEG quantization and/or Huffman tables. Use for copying pre-compressed JPEG segments. The value is written to the JPEGTables tag.

  • iccprofile (bytes | None) – International Color Consortium (ICC) device profile characterizing image color space. The value is written verbatim to the InterColorProfile tag.

  • colormap (ArrayLike | None) – RGB color values for corresponding data value. The colormap array must be of shape (3, 2**(data.itemsize*8)) (or (3, 256) for ImageJ) and dtype uint16. The image’s data type must be uint8 or uint16 (or float32 for ImageJ) and the values are indices into the last dimension of the colormap. The value is written to the ColorMap tag.

  • description (str | bytes | None) – Subject of image. Must be 7-bit ASCII. Cannot be used with the ImageJ or OME formats. The value is written to the ImageDescription tag of the first page of a series.

  • datetime (str | bool | DateTime | None) – Date and time of image creation in %Y:%m:%d %H:%M:%S format or datetime object. If True, the current date and time is used. The value is written to the DateTime tag of the first page of a series.

  • resolution (tuple[float | tuple[int, int], float | tuple[int, int]] | None) – Number of pixels per resolutionunit in X and Y directions as float or rational numbers. The default is (1.0, 1.0). The values are written to the YResolution and XResolution tags.

  • resolutionunit (RESUNIT | int | str | None) – Unit of measurement for resolution values. The default is NONE if resolution is not specified and for ImageJ format, else INCH. The value is written to the ResolutionUnit tags.

  • subfiletype (FILETYPE | int | None) – Bitfield to indicate kind of image. Set bit 0 if the image is a reduced-resolution version of another image. Set bit 1 if the image is part of a multi-page image. Set bit 2 if the image is transparency mask for another image (photometric must be MASK, SamplesPerPixel and bitspersample must be 1).

  • software (str | bytes | bool | None) – Name of software used to create file. Must be 7-bit ASCII. The default is ‘tifffile.py’. Unless False, the value is written to the Software tag of the first page of a series.

  • subifds (int | Sequence[int] | None) – Number of child IFDs. If greater than 0, the following subifds number of series are written as child IFDs of the current series. The number of IFDs written for each SubIFD level must match the number of IFDs written for the current series. All pages written to a certain SubIFD level of the current series must have the same hash. SubIFDs cannot be used with truncated or ImageJ files. SubIFDs in OME-TIFF files must be sub-resolutions of the main IFDs.

  • metadata (dict[str, Any] | None) – Additional metadata describing image, written along with shape information in JSON, OME-XML, or ImageJ formats in ImageDescription or IJMetadata tags. If None, or the shaped argument to TiffWriter is False, no information in JSON format is written to the ImageDescription tag. The ‘axes’ item defines the character codes for dimensions in data or shape. Refer to OmeXml for supported keys when writing OME-TIFF. Refer to imagej_description() and imagej_metadata_tag() for items supported by the ImageJ format. Items ‘Info’, ‘Labels’, ‘Ranges’, ‘LUTs’, ‘Plot’, ‘ROI’, and ‘Overlays’ are written to the IJMetadata and IJMetadataByteCounts tags. Strings must be 7-bit ASCII. Written with the first page of a series only.

  • extratags (Sequence[TagTuple] | None) –

    Additional tags to write. A list of tuples with 5 items:

    1. code (int): Tag Id.

    2. dtype (DATATYPE): Data type of items in value.

    3. count (int): Number of data values. Not used for string or bytes values.

    4. value (Sequence[Any]): count values compatible with dtype. Bytes must contain count values of dtype packed as binary data.

    5. writeonce (bool): If True, write tag to first page of a series only.

    Duplicate and select tags in TIFF.TAG_FILTERED are not written if the extratag is specified by integer code. Extratags cannot be used to write IFD type tags.

  • contiguous (bool) – If False (default), write data to a new series. If True and the data and arguments are compatible with previous written ones (same shape, no compression, etc.), the image data are stored contiguously after the previous one. In that case, photometric, planarconfig, and rowsperstrip are ignored. Metadata such as description, metadata, datetime, and extratags are written to the first page of a contiguous series only. Contiguous mode cannot be used with the OME or ImageJ formats.

  • truncate (bool) – If True, only write first page of contiguous series if possible (uncompressed, contiguous, not tiled). Other TIFF readers will only be able to read part of the data. Cannot be used with the OME or ImageJ formats.

  • align (int | None) – Byte boundary on which to align image data in file. The default is 16. Use mmap.ALLOCATIONGRANULARITY for memory-mapped data. Following contiguous writes are not aligned.

  • maxworkers (int | None) – Maximum number of threads to concurrently compress tiles or strips. If None or 0, use up to _TIFF.MAXWORKERS CPU cores for compressing large segments. Using multiple threads can significantly speed up this function if the bottleneck is encoding the data, for example, in case of large JPEG compressed tiles. If the bottleneck is I/O or pure Python code, using multiple threads might be detrimental.

  • buffersize (int | None) – Approximate number of bytes to compress in one pass. The default is _TIFF.BUFFERSIZE * 2.

  • returnoffset (bool) – Return offset and number of bytes of memory-mappable image data in file.

Returns:

If returnoffset is True and the image data in the file are memory-mappable, return the offset and number of bytes of the image data in the file.

Return type:

tuple[int, int] | None

overwrite_description(description, /)

Overwrite value of last ImageDescription tag.

Can be used to write OME-XML after writing images. Ends a contiguous series.

Parameters:

description (str)

Return type:

None

close()

Write remaining pages and close file handle.

Return type:

None

property filehandle: FileHandle

File handle to write file.