Python and 16 Bit Tiff

后端 未结 4 484
遇见更好的自我
遇见更好的自我 2020-12-05 08:24

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

相关标签:
4条回答
  • 2020-12-05 08:54

    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')
    
    0 讨论(0)
  • 2020-12-05 09:00

    Convert an ImageJ TIFF to a JPEG with PIL 4.1+

    im = numpy.array(Image.open('my.tiff'))
    image = Image.fromarray(im / numpy.amax(im) * 255)
    image.save('my.jpg')
    
    0 讨论(0)
  • 2020-12-05 09:04

    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")
    
    0 讨论(0)
  • 2020-12-05 09:10

    Stumbled on this thread trying to save 16 bit TIFF images with PIL / numpy.

    Versions: python 2.7.1 - numpy 1.6.1 - PIL 1.1.7

    Here's a quick test I wrote. uint16 numpy array -> converted to string -> converted to a PIL image of type 'I;16' -> saved as a 16 bit TIFF.

    Opening the image in ImageJ shows the right horizontal gradient pattern and the image type is 'Bits per pixel: 16 (unsigned)'

    import Image
    import numpy
    
    data = numpy.zeros((1024,1024),numpy.uint16)
    
    h,w = data.shape
    
    for i in range(h):
        data[i,:] = numpy.arange(w)
    
    im = Image.fromstring('I;16',(w,h),data.tostring())
    im.save('test_16bit.tif')
    

    edit: As of 1.1.7, PIL does not support writing compressed files, but pylibtiff does (lzw compression). The test code thus becomes (tested with pylibtiff 0.3):

    import Image
    import numpy
    from libtiff import TIFFimage
    
    data = numpy.zeros((1024,1024),numpy.uint16)
    
    h,w = data.shape
    
    for i in range(w):
        data[:,i] = numpy.arange(h)
    
    tiff = TIFFimage(data, description='')
    tiff.write_file('test_16bit.tif', compression='lzw')
    #flush the file to disk:
    del tiff
    

    Please note: test code changed to generate a vertical gradient otherwise, no compression achieved (refer to warning: pylibtiff currently supports reading and writing images that are stored using TIFF strips).

    0 讨论(0)
提交回复
热议问题