Below is my code for calculating NDVI using Landsat 8. I have used band 4 and 5, but I am not getting any output. How should I get the output image?
import numpy as np
import rasterio
import subprocess
b4 = rasterio.open('C:\\Users\\ARSH\\Downloads\\LC08_L1TP_143051_20191219_20191226_01_T1\\LC08_L1TP_143051_20191219_20191226_01_T1_B4.tif')
b5 = rasterio.open('C:\\Users\\ARSH\\Downloads\\LC08_L1TP_143051_20191219_20191226_01_T1\\LC08_L1TP_143051_20191219_20191226_01_T1_B5.tif')
red = b4.read()
nir = b5.read()
np.seterr(divide='ignore', invalid='ignore')
# Calculate ndvi
ndvi = (nir.astype(float)-red.astype(float))/(nir+red)
# Write the NDVI image
meta = b4.meta
meta.update(driver='GTiff')
meta.update(dtype=rasterio.float32)
with rasterio.open('NDVI.tif', 'w', **meta) as dst:
dst.write(ndvi.astype(rasterio.float32)
1 Answer 1
I adapted your code for my own raster layers (Landsat 5):
import numpy as np
import rasterio
b4 = rasterio.open('/home/zeito/pyqgis_data/b3_ref.tif')
b5 = rasterio.open('/home/zeito/pyqgis_data/b4_ref.tif')
red = b4.read()
nir = b5.read()
np.seterr(divide='ignore', invalid='ignore')
# Calculate ndvi
ndvi = (nir.astype(float)-red.astype(float))/(nir+red)
# Write the NDVI image
meta = b4.meta
meta.update(driver='GTiff')
meta.update(dtype=rasterio.float32)
with rasterio.open('/home/zeito/pyqgis_data/NDVI.tif', 'w', **meta) as dst:
dst.write(ndvi.astype(rasterio.float32))
and, after running it, I found out that the issue was due a missing parentheses in last instruction. Result can be visualized in following image:
NDVI values vary (-0.614977, 0,860435) as expected.
In your case (as Windows user), you should get the output image in:
C:\\Users\\ARSH\\
If you have some issues for founding it, put the full pass in following instruction:
.
.
.
with rasterio.open('NDVI.tif', 'w', **meta) as dst:
.
.
.
-
"put explicitly the pass" do you mean the full path?user2856– user28562020年01月12日 09:38:50 +00:00Commented Jan 12, 2020 at 9:38
-
thankyou i got the output after putting the complete path. how can we add a colour scale to this final ndvi image.Slack 2018– Slack 20182020年01月12日 12:07:53 +00:00Commented Jan 12, 2020 at 12:07
-
@ user2856 Yes. I edit my answer.xunilk– xunilk2020年01月12日 13:26:10 +00:00Commented Jan 12, 2020 at 13:26