Search code examples
pythonopencvtiffsigned

How to read a signed 16-bit TIFF in python?


I used imread() of OpenCV to read the TIFF. But values aren't same as I have already known. This TIFF is signed 16-bit, it has negative values.The range of values using imread() is 0~65535, it is unsigned 16-bit.

import cv2 as cv

img = cv.imread("MYD_20140102.tif",2)
print img
print img.dtype 
print img.shape
print img.min()
print img.max()

cv.namedWindow("Image")
cv.imshow("Image",img)
cv.waitKey(0)
cv.destroyAllWindows()


output:
img=[[55537 55537 55537 ... 55537 55537 55537]
 [55537 55537 55537 ... 55537 55537 55537]
 [55537 55537 55537 ... 55537 55537 55537]
 ...
 [55537 55537 55537 ... 55537 55537 55537]
 [55537 55537 55537 ... 55537 55537 55537]
 [55537 55537 55537 ... 55537 55537 55537]]
type=uint16
shape=(2318, 2296)
imgMin=0
imgMAX=65535

Solution

  • The library tifffile ( https://pypi.python.org/pypi/tifffile ) does exactly what you are looking for. Here is an example that creates an int16 numpy array, saves it on the disk, then load it back again:

    import tifffile
    import numpy as np
    
    # random array of numbers between -5 and 5
    a = np.asarray(np.random.rand(8, 8)*10-5, dtype=np.int16)
    # save array to disk and display its content
    tifffile.imsave("test.tiff", a)
    print(str(a) + "\n")
    # load the array back from the disk and display its content too
    b = tifffile.imread("test.tiff")
    print(b)
    

    The output:

    a=[[ 1 -1 -3  2  3 -1  4  0]
       [ 2 -2  2  0 -1  0  3 -4]
       [ 0 -4  3  2 -4 -2  0 -3]
       [ 0 -1  0 -2  0  3 -3  1]
       [ 0 -4  3  1 -1  3  2  3]
       [-3  4  4  3 -3  1 -3 -2]
       [ 4  0 -4 -2  1 -3  3 -3]
       [ 4  0  4  2  3  1 -2 -4]]
    
    b=[[ 1 -1 -3  2  3 -1  4  0]
       [ 2 -2  2  0 -1  0  3 -4]
       [ 0 -4  3  2 -4 -2  0 -3]
       [ 0 -1  0 -2  0  3 -3  1]
       [ 0 -4  3  1 -1  3  2  3]
       [-3  4  4  3 -3  1 -3 -2]
       [ 4  0 -4 -2  1 -3  3 -3]
       [ 4  0  4  2  3  1 -2 -4]]