0

I'm new in python and I would like to know how I can read and plot MULTIPLE TIFF files in Colaboratory with (maybe) a for loop.

Here is what I did for a single TIFF image:

from google.colab import drive

drive = "/content/drive/MyDrive/exercise"

dataset = gdal.Open(r'/content/drive/MyDrive/exercise/image_20180127.tif')

print(dataset.RasterCount)

band1 = dataset.GetRasterBand(1) #Red Channel

band2 = dataset.GetRasterBand(2) #Green Channel

band2 = dataset.GetRasterBand(3) #Blue Channel

#Read the band as Numpy arrays

b1 = band1.ReadAsArray()

b2 = band1.ReadAsArray()

b3 = band1.ReadAsArray()

#Plot the arrays using imshow()

img = np.dstack((b1,b2,b3))

f=plt.figure()


plt.show()

I would like to perform the same actions for multiple TIFFs (I have 39) with a for loop.

1 Answer 1

0

You can try automizing your method by creating two functions: one to open the image and obtain necessary info, and a second to plot. For example,

from google.colab import drive
drive = "/content/drive/MyDrive/exercise/"

import numpy as np
import matplotlib.pyplot as plt
from osgeo import gdal

def loadTiff(in_image, init=None, size_img=None):
    src = gdal.Open(in_image)
    nbands = src.RasterCount
    in_band = src.GetRasterBand(1)  # load one band for size reference
    if init is None:
        xinit,yinit = (0, 0)
    else:
        xinit,yinit = init
    if size_img is None:
        block_xsize, block_ysize = (in_band.XSize, in_band.YSize)
    else:
        block_xsize, block_ysize = size_img

    # read the (multiband) file into an array
    image = src.ReadAsArray(xinit, yinit, block_xsize, block_ysize)
    # reshape from bandsxheightxwidth to wxhxb
    image = np.moveaxis(image, 0, -1)
    return image, block_ysize, block_xsize, nbands

def RGBplot(image, bindex):  # band index should be in order of r,g,b
  #assumes shape is as obtained above
  img = np.dstack((image[:,:,index[0]]/np.percentile(image[:,:,index[0]],95),
                  image[:,:,index[1]]/np.percentile(image[:,:,index[1]],95),
                  image[:,:,index[2]]/np.percentile(image[:,:,index[2]],95)))
  img = np.clip(img, 0, 1)
  f = plt.figure()
  plt.imshow(np.array(img))
  plt.axis('off')
  plt.show()

Then create the loop to go through your images. For example,

# how you access the folder will depend on your colab setup, naming system, etc
for image in os.listdir(drive):
  if image.endswith('.tif'):
    [img, xsize, ysize, nbands] = loadTiff(os.path.join(drive,image))
    RGBplot(img, [3,2,1])

I can't say if this is the most efficient or effective method but it's worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.