Search code examples
pythontiff

How to save image as binary compressed .tiff python?


Is there any library to save images in binary (1bit per pixel) .tiff compressed file? opencv and pillow cannot do that


Solution

  • In fact, I just found a way to do it with Pillow, but some tweaks are needed because of some bug.

    import numpy as np
    from PIL import Image, TiffImagePlugin
    
    filepath = '/some/file/path.tif'
    # generate a 1bit image
    ar = np.random.rand(50, 50) > 0.5
    arr_2 = np.repeat(np.repeat(ar, 10, axis=0), 10, axis=1)
    
    # save it t
    size = mask.shape[::-1]
    databytes = np.packbits(mask, axis=1)
    mask = Image.frombytes(mode='1', size=size, data=databytes)
    TiffImagePlugin.WRITE_LIBTIFF = True
    mask.save(filepath, compression='packbits')
    TiffImagePlugin.WRITE_LIBTIFF = False