conversion.py 4.53 KB
Newer Older
1
# -*- coding: utf-8 -*-
2

3
4
# py_tools_ds - A collection of geospatial data analysis tools that simplify standard
# operations when handling geospatial raster and vector data as well as projections.
5
#
6
7
8
9
# Copyright (C) 2016-2021
# - Daniel Scheffler (GFZ Potsdam, daniel.scheffler@gfz-potsdam.de)
# - Helmholtz Centre Potsdam - GFZ German Research Centre for Geosciences Potsdam,
#   Germany (https://www.gfz-potsdam.de/)
10
11
12
13
14
#
# This software was developed within the context of the GeoMultiSens project funded
# by the German Federal Ministry of Education and Research
# (project grant code: 01 IS 14 010 A-C).
#
15
16
17
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
18
#
19
#   http://www.apache.org/licenses/LICENSE-2.0
20
#
21
22
23
24
25
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
26

27
28
__author__ = "Daniel Scheffler"

Daniel Scheffler's avatar
Daniel Scheffler committed
29
30
import datetime

31
import numpy as np
32
from osgeo import gdal
33
34
35

# dictionary to translate Numpy data types (strings) into corresponding GDAL data types,
#  e.g. dTypeDic_NumPy2GDAL(str(np.dtype(np.uint8)))
36
37
38
39
40
41
42
43
44
45
46
47
48
49
dTypeDic_NumPy2GDAL = {'bool': gdal.GDT_Byte,
                       'bool_': gdal.GDT_Int32,
                       'int': gdal.GDT_Int32,
                       'int8': gdal.GDT_Int16,
                       'uint8': gdal.GDT_Byte,
                       'uint16': gdal.GDT_UInt16,
                       'int16': gdal.GDT_Int16,
                       'uint32': gdal.GDT_UInt32,
                       'int32': gdal.GDT_Int32,
                       'int64': gdal.GDT_Float64,
                       'float': gdal.GDT_Float32,
                       'float16': gdal.GDT_Float32,
                       'float32': gdal.GDT_Float32,
                       'float64': gdal.GDT_Float64
50
51
52
                       }

# dictionary to translate GDAL data types (strings) into corresponding numpy data types
53
54
55
56
57
58
59
dTypeDic_GDAL2Numpy = {gdal.GDT_Byte: np.uint8,
                       gdal.GDT_UInt16: np.uint16,
                       gdal.GDT_Int16: np.int16,
                       gdal.GDT_UInt32: np.uint32,
                       gdal.GDT_Int32: np.int32,
                       gdal.GDT_Float32: np.float32,
                       gdal.GDT_Float64: np.float64,
60
61
62
63
64
65
66
                       }

# dictionary to translate Numpy data types into GDAL compatible Numpy data types
dTypeDic_NumPy2GDALcompatible = \
    dict(zip(dTypeDic_NumPy2GDAL.keys(),
             [dTypeDic_GDAL2Numpy[dTypeDic_NumPy2GDAL[str(np.dtype(NDT))]] for NDT in dTypeDic_NumPy2GDAL.keys()]))

Daniel Scheffler's avatar
Daniel Scheffler committed
67
68
69

def get_dtypeStr(val):
    is_numpy = 'numpy' in str(type(val))
70
71
72
73
74
75
    DType = str(np.dtype(val)) if is_numpy else \
        'int' if isinstance(val, int) else \
        'float' if isinstance(val, float) else \
        'str' if isinstance(val, str) else \
        'complex' if isinstance(val, complex) else \
        'date' if isinstance(val, datetime.datetime) else None
Daniel Scheffler's avatar
Daniel Scheffler committed
76
    assert DType, 'data type not understood'
77
    return DType
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95


def convertGdalNumpyDataType(dType):
    """convertGdalNumpyDataType
    :param dType: GDALdataType string or numpy dataType
    :return: corresponding dataType
    """
    # dictionary to translate GDAL data types (strings) in corresponding numpy data types
    dTypeDic = {"Byte": np.uint8, "UInt16": np.uint16, "Int16": np.int16, "UInt32": np.uint32, "Int32": np.int32,
                "Float32": np.float32, "Float64": np.float64, "GDT_UInt32": np.uint32}
    outdType = None

    if dType in dTypeDic:
        outdType = dTypeDic[dType]
    elif dType in dTypeDic.values():
        for i in dTypeDic.items():
            if dType == i[1]:
                outdType = i[0]
96
    elif dType in [np.int8, np.int64, int]:
97
98
        outdType = "Int32"
        print(">>>  Warning: %s is converted to GDAL_Type 'Int_32'\n" % dType)
99
    elif dType in [bool, np.bool_]:
100
101
        outdType = "Byte"
        print(">>>  Warning: %s is converted to GDAL_Type 'Byte'\n" % dType)
102
    elif dType in [float]:
103
104
105
106
107
108
109
110
        outdType = "Float32"
        print(">>>  Warning: %s is converted to GDAL_Type 'Float32'\n" % dType)
    elif dType in [np.float16]:
        outdType = "Float32"
        print(">>>  Warning: %s is converted to GDAL_Type 'Float32'\n" % dType)
    else:
        raise Exception('GEOP.convertGdalNumpyDataType: Unexpected input data type %s.' % dType)
    return outdType