Christin Abel Christin Abel - 7 months ago 28
Python Question

Reclassify raster values using python, numpy

I have a raster which contains the values [0, 1, 2, 3, 4, 255] and I want to reclassify it. It worked fine doing it pixel by pixel but that took forever, so I tried to change it... :

# working
for j in range(cf.RasterXSize):
for i in range(cf.RasterYSize):
if cf_array[i, j] <= 1:
cf_array[i, j] = 5 # 5 = No Clouds
elif 1 < cf_array[i, j] <= 4:
cf_array[i, j] = 6 # 6 = Clouds
elif 4 < cf_array[i, j]:
cf_array[i, j] = 7 # 7 = NoData

# Not working:
cf_array[np.where(cf_array <= 1)] = 5
cf_array[np.where((1 < cf_array) & (cf_array <= 4))] = 6
cf_array[np.where(cf_array > 4)] = 7

values = list(numpy.unique(cf_array))
print (values)


And this is what I get when I print the value list with list(numpy.unique(cf_array)) :

original raster: [0, 1, 2, 3, 4, 255]

after reclassify attempt: [7]

So, why is that not working? I found several existing threads regarding the reclassification of a raster but all suggested the numpy.where method which is apparently not working for me...

Answer

As has been noted, you don't need the where, however, I believe the issue is the order of your statements. You are first setting some elements to five and six, respectively, and then finally everything bigger than four to seven - this will include all those elements previously set to five and six. It should work by changing the order:

cf_array[cf_array > 4] = 7
cf_array[cf_array <= 1] = 5
cf_array[(1 < cf_array) & (cf_array <= 4)] = 6