Question

I want to make a calculation using two arrays, containing values from 0 to 255. Since i cannot divide by zero I used the following code to circumvent this problem.

#creation of the two arrays by reading pixel values of an image
data2 = band2.ReadAsArray(0,0,cols,rows)
data3 = band3.ReadAsArray(0,0,cols,rows)

#create array to mark all zero values
mask = numpy.greater((data2+data3), 0)

#do calculation with all values >0 or else assign them -99
ndvi = numpy.choose(mask,(-99, (data3-data2)/(data2 + data3)))

However, i still recieve the error: RuntimeWarning: divide by zero encountered in divide where is my mistake? It shouldnt still want to divide by zero, should it?

When I change the last line to this it works, but my data is not accurate anymore.

ndvi = numpy.choose(mask,(-99, (data3-data2)/(data2 + data3 + 1)))
Was it helpful?

Solution

Your condition for division by zero is (data2+data3)==0, so the following should work:

mask = numpy.not_equal((data2+data3), 0)
ndvi = numpy.choose(mask,(-99, (data3-data2)/(data2 + data3)))

Another way to do this is:

mask = (data2+data3)==0
ndvi = np.zeros(data2.shape)
ndvi[  mask ] = -99
ndvi[ ~mask ] = ((data3-data2)/(data2+data3))[ ~mask ]

OTHER TIPS

If you don't care about getting an "Infinity" where you divide by zero, you can suppress numpy's warning using numpy.seterr(zero='ignore') at the top of your code.

Or, if you only want to use it for a specific section (say in a function), do numpy.seterr(zero='ignore') at the top of your function, then numpy.seterr(zero='warn') at the end of the function.

This way you don't have to worry about making masks to avoid a warning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top