'''
用于将所有的影像的NIR波段合成在在一个影像中(n,height,width)
'''
import os
import numpy as np
from osgeo import gdal
os.environ['PROJ_LIB'] = r'e:\Anaconda3\envs\cloneTF21\Library\share\proj'
class GRID:
def read_img(self, filename):
dataset = gdal.Open(filename)
im_width = dataset.RasterXSize
im_height = dataset.RasterYSize
im_geotrans = dataset.GetGeoTransform()
im_proj = dataset.GetProjection()
im_data = dataset.GetRasterBand(1).ReadAsArray(0, 0, im_width, im_height)
del dataset
return im_data, im_width, im_height, im_geotrans, im_proj
def write_img(self, filename, im_proj, im_geotrans, im_data):
if 'int8' in im_data.dtype.name:
datatype = gdal.GDT_Byte
elif 'int16' in im_data.dtype.name:
datatype = gdal.GDT_UInt16
else:
datatype = gdal.GDT_Float32
if len(im_data.shape) == 3:
im_bands, im_height, im_width = im_data.shape
else:
im_bands, (im_height, im_width) = 1, im_data.shape
driver = gdal.GetDriverByName("GTiff")
dataset = driver.Create(filename, im_width, im_height, im_bands, datatype)
dataset.SetGeoTransform(im_geotrans)
dataset.SetProjection(im_proj)
if im_bands == 1:
dataset.GetRasterBand(1).WriteArray(im_data)
else:
for i in range(im_bands):
dataset.GetRasterBand(i + 1).WriteArray(im_data[i])
del dataset
if __name__ == "__main__":
run = GRID()
filename = r"K:\Area4\新建文件夹"
output_layerstack = r"K:\Area4"
files = []
datas = []
for file in os.listdir(filename):
if os.path.splitext(file)[1] == '.tif':
sourcefile = os.path.join(filename, file)
files.append(sourcefile)
for file, k in zip(files, range(len(files))):
(filepath, tempfilename) = os.path.split(file)
(filename, extension) = os.path.splitext(tempfilename)
print(filename)
data, height, width, geotrans, proj = run.read_img(file)
datas.append(data)
datas = np.array(datas)
print(datas.shape)
run.write_img(output_layerstack + "/layerstack.tif", proj, geotrans, datas, )