Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculating NDVI using python results in all zeros

I want to calculate the ndvi from a Sentinel-2 image.

import os
import numpy as np
import rasterio as rio

# suppress true divide warning numpy for 0 divide
np.seterr(divide='ignore', invalid='ignore')

red_f = absolute/path/to/band/4
nir_f = absolute/path/to/band/8

def calc_ndvi():
    
    with rio.open(red_f) as src:
        red = src.read()
        red = red.astype(np.float64)
    
    with rio.open(nir_f) as src:
        nir = src.read()
        nir = red.astype(np.float64)

    ndvi = np.divide((nir - red),(nir + red))
    
    return ndvi


ndvi = calc_ndvi()

The ‘red’ and ‘nir’ originally get loaded in as ‘Array of uint16’ with a shape of (1, 10980, 10980). I convert this to a float before the calculation using astype. As far as I know it’s not necessary to flatten the array to a 2d shape. I have tried this but this didn’t work.

The result unfortunately is an array completely filled with 0’s.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I doing wrong?

>Solution :

You have a typo:

nir = red.astype(np.float64)

Should be:

nir = nir.astype(np.float64)

In:

ndvi = np.divide((nir - red),(nir + red))

You are really doing:

ndvi = np.divide((red - red),(red + red))

Which results in array of 0

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading