Search code examples
pythonpython-imaging-libraryjpegtiff

Python Pillow unknown RAW mode with 24 bit grayscal TIFF image


I am trying to convert a 24 bit grayscale Tiff image to JPEG in Python with Pillow. This attempt works for some 24 bit Tiff images, but not all. It gives unknown raw mode for the image below:

from PIL import Image

im = Image.open("example.tif")
if im.mode != "L":  # rescale 16 bit tiffs to 8 bits
    im.mode = "I"
    im = im.point(lambda i: i * (1.0 / 256))
im = im.convert("RGB")
im.save("example.jpg", "JPEG", quality=100)

Here's an example of an offending image (which appears to be converted to PNG on upload to the site):

enter image description here


Solution

  • It turns out the mode of this example image is already RGB even though the image appears to be grayscale. If you don't try manual rescaling first, the pillow conversion works fine:

    from PIL import Image
    
    im = Image.open("example.tif")
    if im.mode not in ("L", "RGB"):  # rescale 16 bit tiffs to 8 bits
        im.mode = "L"
        im = im.point(lambda i: i * (1.0 / 256))
    im = im.convert("RGB")
    im.save("example.jpg", "JPEG", quality=100)