[GIS] How to use gdal to convert HDF multi-band file to a single GeoTiff file

gdalgdal-translategeotiff-tiffhdf

I have a multi-band HDF file that I want to convert to a single GeoTiff file, using free tools, preferably gdal. I'm trying to use gdal_translate, but I either get back multiple output .tif files, or I get "subdatasets" errors.

When I use the -b flag to specify bands:

gdal_translate -b 1 -b 2 -of GTiff input_image.hdf output_image.tif

I get "subdatasets" errors: "Input file contains subdatasets. Please, select one of them for reading."

And when I use the sds flag:

gdal_translate -sds -of GTiff input_file.hdf output_file.tif

I get back separate .tif files, one for each band in the input file.

How can I convert an HDF file into a single GeoTiff file using gdal?

Best Answer

I also couldn't find a way to do it in one step... but using -sds like you did, followed by a gdal_merge.py -separate should work https://gdal.org/programs/gdal_merge.html#cmdoption-gdaladdo-separate

https://gdal.org/programs/gdal_translate.html#cmdoption-gdal-translate-sds

So this should work for you:

gdal_translate -sds input_file.hdf tmp_outs.tif

gdal_merge.py -separate -o final_output.tif tmp_outs*tif

rm tmp_outs*tif

if your HDF5 subdatasets are different datatypes, specify which output type you want with gdal_merge.py -ot Float32 ...

Just to reference here what those options mean:

-sds

Copy all subdatasets of this file to individual output files. Use with formats like HDF that have subdatasets.



-separate

Place each input file into a separate band.