From 79bbcd824dd91819b4e7d2a3511809c09443b25c Mon Sep 17 00:00:00 2001 From: "Daniel.Frisinghelli" <daniel.frisinghelli@eurac.edu> Date: Wed, 24 Feb 2021 12:46:40 +0100 Subject: [PATCH] Check for projection in header files when converting hdf to tif. --- pysegcnn/core/utils.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/pysegcnn/core/utils.py b/pysegcnn/core/utils.py index 4be32f9..101029b 100644 --- a/pysegcnn/core/utils.py +++ b/pysegcnn/core/utils.py @@ -500,6 +500,20 @@ def hdf2tifs(path, outpath=None, overwrite=False, create_stack=True, **kwargs): for tif in tifs: tif.unlink() + # header file + hdr = pathlib.Path('.'.join([str(path), 'hdr'])) + + # check if header file exists and contains projection + wkt = None + if hdr.exists(): + LOGGER.info('Found header file: {}'.format(hdr)) + with open(hdr, 'r') as file: + # search for WKT-projection string + content = file.read() + wkt = re.search('PROJCS[^}]*', content) + if wkt is not None: + wkt = wkt[0] + # read the hdf dataset hdf = gdal.Open(str(path)).GetSubDatasets() @@ -519,12 +533,15 @@ def hdf2tifs(path, outpath=None, overwrite=False, create_stack=True, **kwargs): # convert hdf subdataset to GeoTIFF LOGGER.info('Converting: {}'.format(tif_name.name)) - gdal.Translate(str(tif_name), hdf_ds, creationOptions=[ - 'COMPRESS=DEFLATE', 'PREDICTOR=1', 'TILED=YES'], **kwargs) + gdal.Translate(str(tif_name), hdf_ds, outputSRS=wkt, + creationOptions=[ + 'COMPRESS=DEFLATE', 'PREDICTOR=1', 'TILED=YES'], + **kwargs) # set metadata field tif_ds = gdal.Open(str(tif_name)) tif_ds.SetMetadata(hdf_ds.GetMetadata()) + del tif_ds # check whether to create a GeoTIFF stack -- GitLab