# Raster Function for NDVI Band Calculation - Divide by Zero

I am using rasterio to open image files related to 2 specific bands:

``````b4 = rio.open(r)
b8 = rio.open(poly)
``````

I then read the bands into a python array, I think it's a numpy array but not sure?:

``````#Read Red(b4) and NIR(b8) as arrays
``````

Then I perform band based calculation against them via the following:

``````#Calculate NDVI
ndvi = (nir.astype(float) - red.astype(float)) / (nir + red)
``````

Now, this of course can have the denominator (nir + red) be equal to zero, which will cause a divide by zero issue that I believe is messing with the results.

Is there a way to set the instances where the denominator is equal to zero to have a value of -1 or something? How are you handling those in your own raster functions?

I suggest using numpy to build your raster function, which can handle situations where the denominator is 0.

``````red = np.arange(0, 15).reshape(4,4)
ndvi = np.arange(-10, 6).reshape(4,4)
ndvi = np.divide(np.subtract(red, nir), np.add(red, nir))
ndvi = np.where(ndvi == np.inf, -99, ndvi)
``````

numpy returns `np.inf` when dividing by zero, which you can later on replace by any arbitrary number to indicate an invalid NDVI value; in the example -99.

• That's exactly the type of thing I was looking for. What is your Arrange and Reshape doing there in your example? Commented Apr 22, 2020 at 20:50
• `np.arange` gives a 1-D array starting-stopping at the numbers provided. `reshape` reshapes the 1-D array (shape (16,)) to a 2-Dimensional array (shape(4,4)). See arange and reshape documentation. If this answers helped you out, please tick 'answered'. Commented Apr 23, 2020 at 13:58
• What was the reasoning behind the numbers you supplied for the parameters in the arrange and reshape calls? Commented Apr 23, 2020 at 16:01
• The reason i ask is b/c just using the divide and where pieces, you still get a RuntimeWarning: invalid value encountered in true_divide. So I was trying to figure out the reasoning behind choosing the 0,15 and -10, 6 for the arrange calls, and 4,4 for the reshapes? Commented Apr 23, 2020 at 16:16
• I designed the value ranges so that a zero would occur once in the denominator. The `(4, 4)` shape is just to create a 2D array that would easily fit in my python window. Commented Apr 28, 2020 at 7:07