# gdal calc to convert multiple values

I'm trying to use GDAL calc to convert values in a .tif file, I've done this before with GDAL calc but for converting to a single value. Now I'm trying to convert multiple values in this fashion:

0.0 - 0.2 -> 1

0.2 - 0.4 -> 2

0.4 - 0.6 -> 3

etc

I've tried this:

``````    calculation='((0.0<A<0.2)*1)+((0.2<A<0.4)*2)+((0.4<A<0.6)*3)+
((0.6<A<0.8)*4)+((0.8<A<1.0)*5)+((1.0<A<1.5)*6)+((1.5<A<2.0)*7)+
((2.0<A<2.5)*8)+((2.5<A<3.0)*9)+((3.0<A<9999)*10)'

call([sys.executable, 'C:\Program Files (x86)\GDAL\gdal_calc.py', '-A',
inraster, "--outfile=" + outraster, '--calc='+calculation,'--
NoDataValue=-9999','--overwrite'])
``````

This results in the following error:

``````    0 .. evaluation of calculation [thecalculation] failed
``````

Any ideas? Maybe I need to split up the steps of converting but this could add significantly to the run time.

• have you tried (0<A)*(A<=0.2)*1 + ... – radouxju Dec 4 '17 at 13:39

I think the problem is chaining operators with an array. Python can handle `a<b<c` but only if `a`, `b` and `c` are scalars. In this case `b` is an array. For more: see docs and a discussion.

Assuming that is the problem, then based on this answer I imagine you can use something like this:

``````calculation='(logical_and(0.0<A,A<=0.2)*1)+(logical_and(0.2<A,A<=0.4)*2)+(logical_and(0.4<A,A<=0.6)*3)+(logical_and(0.6<A,A<=0.8)*4)+(logical_and(0.8<A,A<=1.0)*5)+(logical_and(1.0<A,A<=1.5)*6)+(logical_and(1.5<A,A<=2.0)*7)+(logical_and(2.0<A,A<=2.5)*8)+(logical_and(2.5<A,A<=3.0)*9)+(logical_and(3.0<A,A<=9999)*10)'
``````

Failing that there is a useful tool called gdal_reclassify that is straight forward to use and has clear docs. Your use case would require something like this (NB only done for 4 classes):

``````python gdal_reclassify.py source_dataset.tif destination_dataset.tif -c "<0.2, <0.4, <0.6, <0.8" -r "1, 2, 3, 4" -d 0 -n true -p "COMPRESS=LZW"
``````

You could build this call into your script as well.

If you're already working in a python script you could also just read to numpy array, and use numpy directly to do the reclassification.

• gdal_reclassify worked a charm! Fantastic answer, thank you so much! – Yjelza Dec 4 '17 at 13:53
• And for the record, the method with logical_and's did not work, it threw an error. – Yjelza Dec 4 '17 at 13:54
• Think that was my fault with the brackets. Might work now, not that it's needed! – RoperMaps Dec 4 '17 at 14:00