creating a 16 bit tiff image

Solution 1:

Saving 16 bit unsigned image with PIL

In the code

img = Image.fromarray(pic, 'L')

The 'L' specifies 8-bit pixels, black and white according to the PIL documentation.

To create an unsinged int 16 bit image the 'I;16' option is required.

img = Image.fromarray(pic[0], 'I;16')

The stackoverflow post Read 16-bit PNG image file using Python says there is issues with this argument, however it is working fine for me using PIL ver 8.2.0 and Python 3.8.8.

other considerations

  • You may also want to be careful with your data and noise array. They are unsigned 8 bit integers.

    data = np.zeros((t, h, w), dtype=np.uint8)
    noise = np.zeros((t, h, w), dtype=np.uint8)
    

    They can be converted to unsigned 16 using np.uint16 as the dtype parameter.

    data = np.zeros((t, h, w), dtype=np.uint16)
    noise = np.zeros((t, h, w), dtype=np.uint16)
    
  • Is it possible for your processing to create negative numbers? Another issue could be caused when placing negative numbers into an unsigned integer array.

Solution 2:

As this blog post suggests, you need help from an external library "libtiff". Since PIL struggles with 16-bit.

from libtiff import TIFF
tiff = TIFF.open('libtiff.tiff', mode='w')
tiff.write_image(ar)
tiff.close()