Reading and saving tif images with python

Viewed 2550

I am trying to read this tiff image with python. I have tried PIL to and save this image. The process goes smoothly, but the output image seems to be plain dark. Here is the code I used.

from PIL import Image

im = Image.open('file.tif')
imarray = np.array(im)

data = Image.fromarray(imarray)
    
data.save('x.tif')

Please let me know if I have done anything wrong, or if there is any other working way to read and save tif images. I mainly need it as NumPy array for processing purposes.

1 Answers

The problem is simply that the image is dark. If you open it with PIL, and convert to a Numpy array, you can see the maximum brightness is 2455, which on a 16-bit image with possible range 0..65535, means it is only 2455/65535, or 3.7% bright.

from PIL import Image

# Open image
im = Image.open('5 atm_gain 80_C001H001S0001000025.tif')

# Make into Numpy array
na = np.array(im)

print(na.max())       # prints 2455

So, you need to normalise your image or scale up the brightnesses. A VERY CRUDE method is to multiply by 50, for example:

Image.fromarray(na*50).show()

enter image description here

But really, you should use a proper normalisation, like PIL.ImageOps.autocontrast() or OpenCV normalize().

Related