Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and 16 Bit Tiff

How can I convert and save a 16 bit single-channel TIF in Python?

I can load a 16 and 32 bit image without an issue, and see that the 32 bit image is mode F and the 16 bit image is mode I;16S:

import Image
i32 = Image.open('32.tif')
i16 = Image.open('16.tif')
i32
# <TiffImagePlugin.TiffImageFile image mode=F size=2000x1600 at 0x1098E5518>
i16
# <TiffImagePlugin.TiffImageFile image mode=I;16S size=2000x1600 at 0x1098B6DD0>

But I am having trouble working with the 16 bit image. If I want to save either as PNG, I cannot do so directly:

i32.save('foo.png')
# IOError: cannot write mode F as PNG
i16.save('foo.png')
# ValueError: unrecognized mode

If I convert the 32 bit image, I can save it:

i32.convert('L').save('foo.png')

But the same command will not work with the 16 bit image:

i16.convert('L').save('foo.png')
# ValueError: unrecognized mode
like image 739
mankoff Avatar asked Aug 30 '11 17:08

mankoff


2 Answers

You appear to have stumbled into a PIL bug, or a corner case that was unimplemented.

Here's a workaround:

i16.mode = 'I'
i16.point(lambda i:i*(1./256)).convert('L').save('foo.png')
like image 87
Mark Ransom Avatar answered Oct 14 '22 10:10

Mark Ransom


For lossless conversion from 16 bit grayscale TIFF to PNG use PythonMagick:

from PythonMagick import Image
Image('pinei_2002300_1525_modis_ch02.tif').write("foo.png")
like image 21
cgohlke Avatar answered Oct 14 '22 10:10

cgohlke