Writing multipage TIFF with Python

The best way to write multipage TIFF (all at once or iteratively appending) on any platform (Windows, Mac, Linux) is tifffile.

Python tifffile

Install tifffile.py:

pip install tifffile

Example

import tifffile

tifffile.imsave('myimages.tiff',imgs)
imgs.shape
(Nimg,y,x) for monochrome. (Nimg,y,x,3) for RGB color.

tifffile.imsave() is capable of description and tags arguments and to compress losslessly.

Advanced Python TIFF multi-page writing example: Demo_image_write_multipage.py.

Raspberry Pi

tifffile ≥ 0.7 requires Numpy 1.13, while the Raspberry Pi has Numpy 1.12 with most up to date Raspbian 9.1 currently available.

I worked around this issue by

pip uninstall tifffile

pip install tifffile==0.6

Test on the Raspberry Pi:

python -c "import tifffile"

If you have too-new tifffile, you’ll get error:

RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa

Read TIFF headers

There are de facto TIFF header tags. These can be read from the command line with

apt install libimages-exiftool-perl

exifinfo myfile.tif

Note: tiffinfo doesn’t print tiff tags

Print all TIFF tags from Python using PrintTiffTags.py

Alternative Python multipage TIFF method

Alternative multipage-Tiff method using scikit-image and FreeImage: (we recommend tifffile instead)

from skimage.io._plugins import freeimage_plugin as freeimg 
"""
imgs is a Numpy ndarray: 
Nimg x Y x X   (grayscale)
Nimg x Y x X x 3  (RGB color)
"""

freeimg.write_multipage(imgs,'myimages.tiff')

Fix scikit-image errors

Due to the large number of image libraries invoked, sometimes scikit-image needs a little tweaking for image I/O:

Windows

if you get error:

RuntimeError: Could not find a FreeImage library

Fix by:

  1. download the FreeImage DLL
  2. extract Dist/x64/FreeImage.dll to
    $(python -c "import skimage; print(skimage.__path__[0])")/io/_plugins/
    

Linux

If you get error:

freeimage had a problem: Could not find a FreeImage library in any of…

Fix by:

apt install libfreeimage3

reference

Tags:

Categories:

Updated:

Leave a Comment