2

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)))
4

2 回答 2

1

如果您不关心除以零的“无穷大”,则可以numpy.seterr(zero='ignore')在代码顶部使用 numpy 的警告来抑制。

或者,如果您只想将它​​用于特定部分(例如在函数中),请numpy.seterr(zero='ignore')在函数顶部执行,然后numpy.seterr(zero='warn')在函数末尾执行。

这样您就不必担心制作口罩以避免警告。

于 2013-07-08T03:38:25.743 回答
1

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 ]
于 2013-07-07T17:59:08.307 回答