Search code examples
pythonpython-imaging-library

Get number of layers in tif image using python


I have the tif image with 5 layers (not color channels but layers). How can I get the number of layers in this tif file using python?

I tried PIL.Image im.n_frames and cv2.imreadmulti they all show that image has only one layer.


Solution

  • The layers in these kind of TIFF files are hidden in the Adobe Photoshop specific ImageResources (#34377) and ImageSourceData (#37724) TIFF tags.

    Use the psdtags library to parse these tags, e.g.:

    from psdtags import TiffImageSourceData
    
    isd = TiffImageSourceData.fromtiff('5_layers.tif')
    number_layers = len(isd.layers)
    for layer in isd.layers:
        layer.name
        for channel in layer.channels:
            ch = channel.data  # a numpy array
    

    Run python -m psdtags 5_layers.tif to preview the layer information in the TIFF file.