GDAL – Resolving Nodata Value Issues When Stacking Files with GDAL_merge

gdalgdal-mergeraster

I masked a large raster stack by separating the stack in 18 chunks, masking each and writing each chunk to a file (due to memory problems).

Then, I use gdal_merge to stack the 18 GTiff files. All files have exactly the same resolution and extent. Also, the nodata value (-32768) and the data type (INT2S) are equal.

The resulting file (GTiff format) has the correct nodata value and data type in each band. However, beginning with the 6th band, the nodata pixels are changed to zero. The nodata value is still set to -32768, but the pixels that were -32768 (nodata) are 0 now.

When I stack the files beginning with, for example, the 16th up to the 18th file, the first 5 bands are correct again, and starting at band 6 (which comes now from the 16th, not the 1st file), the nodata values are set to 0 again. This means that the files itself are ok.

This behaviour is so strange that I can't even start debugging. I have no idea where the problem is.

Does anyone have an idea where this behaviour comes from? Please let me know if you need additional information.

Best Answer

Looking at the code of gdal_merge what I understand is this:

The effect of the "-n" option is the same as using input files with the NoDataValues set (to the same number). In both cases, gdal_merge ignores the pixels which present these values (the ones set beforehand as NoData or the ones set by the "-n" option). The value it places at their place is the value set by the "-init" option (if set, otherwise 0).

So, in your case you should just add the option "-init -32768" at the gdal_merge call (and you can ignore the -n option.

N option is useful, I guess, only if your input files don't have NoDataValues set, if they are set to different numbers or if you want to ignore other values, apart from the ones already set to NoData to your input.

My conclusion is that it's extremely important to always set your -init value in order to keep control of your dataset.