LarsC LarsC - 1 year ago 179
Python Question

Python: Read and write TIFF 16 bit , three channel , colour images

Does anyone have a method for importing a 16 bit per channel, 3 channel TIFF image in Python?

I have yet to find a method which will preserve the 16 bit depth per channel when dealing with the TIFF format. I am hoping that some helpful soul will have a solution.

Here is a list of what I have tried so far without success and the results:

import numpy as np
import PIL.Image as Image
import libtiff
import cv2

im ='a.tif')
# IOError: cannot identify image file

tif ='a.tif')
im = tif.read_image()
# im only contains one of the three channels. im.dtype is uint16 as desired.
im = []
for i in tif.iter_images():
# still only returns one channel

im = np.array(cv2.imread('a.tif'))
# im.dtype is uint8 and not uint16 as desired.
# specifying dtype as uint16 does not correct this

So far the only solution I have found is to convert the image to PNG with ImageMagick. Then the bog standard
reads the PNG file without any problems.

Another problem I have is saving any numpy arrays as 16 bit PNG files which so far has not been straightforward either.

Answer Source

It has limited functionality, especially when it comes to writing back to disk non RGB images, but Christoph Gohlke's tifffile module reads in 3 channel 16-bit TIFFs with no problems, I just tested it:

>>> import tifffile as tiff
>>> a = tiff.imread('Untitled-1.tif')
>>> a.shape
(100L, 100L, 3L)
>>> a.dtype

And Photoshop reads without complaining what I get from doing:

>>> tiff.imsave('new.tiff', a)