你可以将上述代码封装成一个函数,如下所示:
”`python import os import glob import gdal import numpy as np import matplotlib.pyplot as plt
def process_tif(tif_path, out_dir):
in_ds = gdal.Open(tif_path)
if in_ds is None:
print('Could not open the file ' + tif_path)
return
# 获取文件所在路径以及不带后缀的文件名
(filepath, fullname) = os.path.split(tif_path)
(prename, suffix) = os.path.splitext(fullname)
red = in_ds.GetRasterBand(1).ReadAsArray() * 0.0001
nir = in_ds.GetRasterBand(2).ReadAsArray() * 0.0001
ndvi = (nir - red) / (nir + red)
# 将NAN转化为0值
nan_index = np.isnan(ndvi)
ndvi[nan_index] = 0
ndvi = ndvi.astype(np.float32)
gtiff_driver = gdal.GetDriverByName('GTiff')
out_path = os.path.join(out_dir, prename + '_ndvi.tif')
out_ds = gtiff_driver.Create(out_path, ndvi.shape[1], ndvi.shape[0], 1, gdal.GDT_Float32)
out_ds.SetProjection(in_ds.GetProjection())
out_ds.SetGeoTransform(in_ds.GetGeoTransform())
out_band = out_ds.GetRasterBand(1)
out_band.WriteArray(ndvi)
内容由零声教学AI助手提供,问题来源于学员提问




