1

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)
Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Jan 11, 2020 at 17:03

1 Answer 1

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:

enter image description here

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:
.
.
.
answered Jan 11, 2020 at 20:30
3
  • "put explicitly the pass" do you mean the full path? Commented 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. Commented Jan 12, 2020 at 12:07
  • @ user2856 Yes. I edit my answer. Commented Jan 12, 2020 at 13:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.