Read tif images using GDAL library
The default band of the sample code is [B, G, R, NIR order, and four bands]
import gdal def readTif(fileName): dataset = (fileName) if dataset == None: print(fileName+"File cannot be opened") return im_width = #Number of columns in raster matrix im_height = #Number of rows of raster matrix im_bands = #Number of bands im_data = (0,0,im_width,im_height)#Get data im_geotrans = ()#Get affine matrix information im_proj = ()#Get projection information im_blueBand = im_data[0,0:im_height,0:im_width]#Get blue band im_greenBand = im_data[1,0:im_height,0:im_width]#Get green band im_redBand = im_data[2,0:im_height,0:im_width]#Get the red band im_nirBand = im_data[3,0:im_height,0:im_width]#Obtain the near-infrared band
Write tif image function
#Save tif file functionimport gdal import numpy as np def writeTiff(im_data,im_width,im_height,im_bands,im_geotrans,im_proj,path): if 'int8' in im_data.: datatype = gdal.GDT_Byte elif 'int16' in im_data.: datatype = gdal.GDT_UInt16 else: datatype = gdal.GDT_Float32 if len(im_data.shape) == 3: im_bands, im_height, im_width = im_data.shape elif len(im_data.shape) == 2: im_data = ([im_data]) else: im_bands, (im_height, im_width) = 1,im_data.shape #Create a file driver = ("GTiff") dataset = (path, im_width, im_height, im_bands, datatype) if(dataset!= None): (im_geotrans) #Write affine transformation parameters (im_proj) #Write projection for i in range(im_bands): (i+1).WriteArray(im_data[i]) del dataset
The above method of using GDAL to read and write tif files in python is all the content I share with you. I hope you can give you a reference and I hope you can support me more.