I have multiple folders containing landsat data from different years . I have been just testing Landsat 5 before doing them all but I feel as though something is wrong with the code.
def calculate_ndvi_from_multiband_tiff(multiband_tiff_path, output_folder, red_band_index, nir_band_index):
# Create the output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Open the multi-band GeoTIFF
with rasterio.open(multiband_tiff_path) as src:
# Read the red and NIR bands
red = (src.read(red_band_index).astype('float32') * 0.0000275) + -0.2
nir = (src.read(nir_band_index).astype('float32') * 0.0000275) + -0.2
# Avoid division by zero
np.seterr(divide='ignore', invalid='ignore')
# Calculate NDVI
ndvi = (nir - red) / (nir + red)
# Save the NDVI image
profile = src.profile
profile.update(dtype=rasterio.float32, count=1)
# Construct the output path for NDVI image
base_filename = os.path.splitext(os.path.basename(multiband_tiff_path))[0]
ndvi_output_filename = f'{base_filename}_NDVI.tif'
ndvi_output_path = os.path.join(output_folder, ndvi_output_filename)
with rasterio.open(ndvi_output_path, 'w', **profile) as dst:
dst.write(ndvi, 1)
print(f'NDVI calculation complete. Output saved to {ndvi_output_path}')
def process_landsat_folder(input_folder, output_root_folder):
# Create the output root folder if it doesn't exist
os.makedirs(output_root_folder, exist_ok=True)
# Iterate over all files in the input folder
for filename in os.listdir(input_folder):
if filename.endswith('.tif') or filename.endswith('.tiff'):
multiband_tiff_path = os.path.join(input_folder, filename)
# Landsat 5: typically Red is Band 3 and NIR is Band 4
red_band_index = 3
nir_band_index = 4
calculate_ndvi_from_multiband_tiff(multiband_tiff_path, output_root_folder, red_band_index, nir_band_index)
# # Example usage
input_folder = "D:\PPR Downloads (Test)\Landsat_5_2005_05_09"
output_root_folder = "D:\Landsat_NDVI\Landsat_5_2005_NDVI"
process_landsat_folder(input_folder, output_root_folder)
I am not the best with python, I understand the basics but as soon as I start adding packages I am not to sure what to do so I turn to Chat GPT for help. So the code does not always work but after changing a few things it actually did the calculations from a single Landsat which is nice. I had to apply the scaling factors and what not but when I import just one tile into QGIS to make sure the calculations are correct and a few things stood out to me.
The first thing was that the Tile had been filled in from its negative space, which if I could avoid I would like to.
Second is that what which should have a NDVI value of <0 was not fully showing?