Hopefully this is useful. Take note, it is written for python3 and needs specific libraries.
First you would need to read each tiff band as a numpy array using something like this:
import numpy as np
from osgeo import gdal
import os.path
def file_test(input_file):
return os.path.isfile(input_file)
def open_tiff(tiff_file):
print(tiff_file)
if file_test(tiff_file):
return gdal.Open(tiff_file)
else:
print("Error!")
def tiff_to_array(tiff_file, lon_offset_px=0, lat_offset_px=0):
gdo = open_tiff(tiff_file)
tiff_array = gdo.ReadAsArray(lon_offset_px,lat_offset_px,1000,1000)
tiff_array = np.array(bytescale(tiff_array, low=0, high=255), dtype=np.int16)
gdo = None
return tiff_array
This is used to create image array. I use the scikit-image library to do some enhancements.
import numpy as np
from scipy.misc import bytescale
from skimage import exposure
from matplotlib import pyplot as plt
def create_composite(red_band, green_band, blue_band):
img_dim = red.shape
img = np.zeros((img_dim[0], img_dim[1], 3), dtype=np.float)
img[:,:,0] = red
img[:,:,1] = green
img[:,:,2] = blue
p2, p98 = np.percentile(img, (2, 98))
img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))
return bytescale(img_rescale)
image = create_composite(red, green, blue)
plt.imshow(image)
You could convert each band to 8-bit using scipy.misc.bytescale first before passing it to the function.
I think the problem could be with the range of values in your original image. You can use the -scale
parameter in gdal_translate
to get images within the range of an 8 bit image.
For example
gdal_translate -of PNG -ot Byte -scale in_tiff.tif out_png_scaled.png
This will automatically set the input minimum and maximum values used to scale, if these don't work you can specify a minimum and maximum value after -scale
.
If you need to make the image smaller you can also resize with gdal_translate
using -outsize
. For example, -outsize 50% 50%
will resize to 50 % of the original.
Best Answer
The problem is that PIL wants to see a ".tiff" at the end of the file name. You have ".tif". The solution is to rename your file to "LakeEx.tiff".