Python osgeo.gdal.GetDataTypeName() Examples

The following are code examples for showing how to use osgeo.gdal.GetDataTypeName(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMappingTools.py    MIT License 6 votes vote down vote up
def GetGeoInfo(FileName):

    if exists(FileName) is False:
            raise Exception('[Errno 2] No such file or directory: \'' + FileName + '\'')    
    
    
    SourceDS = gdal.Open(FileName, gdal.GA_ReadOnly)
    if SourceDS == None:
        raise Exception("Unable to read the data file")
    
    NDV = SourceDS.GetRasterBand(1).GetNoDataValue()
    xsize = SourceDS.RasterXSize
    ysize = SourceDS.RasterYSize
    GeoT = SourceDS.GetGeoTransform()
    Projection = osr.SpatialReference()
    Projection.ImportFromWkt(SourceDS.GetProjectionRef())
    DataType = SourceDS.GetRasterBand(1).DataType
    DataType = gdal.GetDataTypeName(DataType)
    
    return NDV, xsize, ysize, GeoT, Projection, DataType
#==============================================================================

#==============================================================================
# Function to read the original file's projection: 
Example 2
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: gdal_dataset.py    GNU General Public License v2.0 6 votes vote down vote up
def _create_simple_VRT(self,warped_ds,dataset_or_band):
        ''' Create a simple VRT XML string from a warped VRT (GDALWarpOptions)'''

        vrt=[]
        vrt.append('<VRTDataset rasterXSize="%s" rasterYSize="%s">' % (warped_ds.RasterXSize,warped_ds.RasterYSize))
        vrt.append('<SRS>%s</SRS>' % warped_ds.GetProjection())
        vrt.append('<GeoTransform>%s</GeoTransform>' % ', '.join(map(str,warped_ds.GetGeoTransform())))
        for i,band in enumerate(dataset_or_band._bands):
            rb=warped_ds.GetRasterBand(band+1) #gdal band index start at 1
            nodata=rb.GetNoDataValue()
            vrt.append('  <VRTRasterBand dataType="%s" band="%s">' % (gdal.GetDataTypeName(rb.DataType), i+1))
            vrt.append('    <SimpleSource>')
            vrt.append('      <SourceFilename relativeToVRT="0">%s</SourceFilename>' % (self._warped_fn))
            vrt.append('      <SourceBand>%s</SourceBand>'%(band+1))
            vrt.append('      <SrcRect xOff="0" yOff="0" xSize="%s" ySize="%s" />' % (warped_ds.RasterXSize,warped_ds.RasterYSize))
            vrt.append('      <DstRect xOff="0" yOff="0" xSize="%s" ySize="%s" />' % (warped_ds.RasterXSize,warped_ds.RasterYSize))
            vrt.append('    </SimpleSource>')
            if nodata is not None: # 0 is a valid value
                vrt.append('    <NoDataValue>%s</NoDataValue>' % nodata)
            vrt.append('  </VRTRasterBand>')
        vrt.append('</VRTDataset>')

        vrt='\n'.join(vrt)
        self.__write_vsimem__(self._simple_fn,vrt)
        return gdal.Open(self._simple_fn) 
Example 3
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_GDALIO.py    MIT License 5 votes vote down vote up
def GetGeoInfo(FileName):
    """This gets information from the raster file using gdal

    Args:
        FileName (str): The filename (with path and extension) of the raster.

    Return:
        float: A vector that contains:
            * NDV: the nodata values
            * xsize: cellsize in x direction
            * ysize: cellsize in y direction
            * GeoT: the tranform (a string)
            * Projection: the Projection (a string)
            * DataType: The type of data (an int explaing the bits of each data element)

    Author: SMM
    """


    if exists(FileName) is False:
            raise Exception('[Errno 2] No such file or directory: \'' + FileName + '\'')


    SourceDS = gdal.Open(FileName, gdal.GA_ReadOnly)
    if SourceDS == None:
        raise Exception("Unable to read the data file")

    NDV = SourceDS.GetRasterBand(1).GetNoDataValue()
    xsize = SourceDS.RasterXSize
    ysize = SourceDS.RasterYSize
    GeoT = SourceDS.GetGeoTransform()
    Projection = osr.SpatialReference()
    Projection.ImportFromWkt(SourceDS.GetProjectionRef())
    DataType = SourceDS.GetRasterBand(1).DataType
    DataType = gdal.GetDataTypeName(DataType)

    return NDV, xsize, ysize, GeoT, Projection, DataType
#==============================================================================

#==============================================================================
# This gets the UTM zone, if it exists 
Example 4
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: gdal_dataset.py    GNU General Public License v2.0 5 votes vote down vote up
def _create_simple_VRT(self,warped_ds,bands):
        ''' Create a simple VRT XML string from a warped VRT (GDALWarpOptions)'''

        vrt=[]
        vrt.append('<VRTDataset rasterXSize="%s" rasterYSize="%s">' % (warped_ds.RasterXSize,warped_ds.RasterYSize))
        vrt.append('  <SRS>%s</SRS>' % warped_ds.GetProjection())
        vrt.append('  <GeoTransform>%s</GeoTransform>' % ', '.join(map(str,warped_ds.GetGeoTransform())))
        for i,band in enumerate(bands):
            rb=warped_ds.GetRasterBand(band+1) #gdal band index start at 1
            nodata=rb.GetNoDataValue()
            path=warped_ds.GetDescription()
            rel=not os.path.isabs(path)
            vrt.append('  <VRTRasterBand dataType="%s" band="%s">' % (gdal.GetDataTypeName(rb.DataType), i+1))
            vrt.append('    <SimpleSource>')
            vrt.append('      <SourceFilename relativeToVRT="%s">%s</SourceFilename>' % (int(rel),path))
            vrt.append('      <SourceBand>%s</SourceBand>'%(band+1))
            vrt.append('      <SrcRect xOff="0" yOff="0" xSize="%s" ySize="%s" />' % (warped_ds.RasterXSize,warped_ds.RasterYSize))
            vrt.append('      <DstRect xOff="0" yOff="0" xSize="%s" ySize="%s" />' % (warped_ds.RasterXSize,warped_ds.RasterYSize))
            vrt.append('    </SimpleSource>')
            if nodata is not None: # 0 is a valid value
                vrt.append('    <NoDataValue>%s</NoDataValue>' % nodata)
            vrt.append('  </VRTRasterBand>')
        vrt.append('</VRTDataset>')

        vrt='\n'.join(vrt)
        vrttree=gdal.ParseXMLString(vrt)
        return vrttree 
Example 5
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: gdal_dataset.py    GNU General Public License v2.0 5 votes vote down vote up
def buildvrt(self, reference_ds, filepaths, band):
        ''' Create a simple VRT stack'''
        vrt=[]
        vrt.append('<VRTDataset rasterXSize="%s" rasterYSize="%s">' % (reference_ds.RasterXSize,reference_ds.RasterYSize))
        vrt.append('  <SRS>%s</SRS>' % reference_ds.GetProjection())
        vrt.append('  <GeoTransform>%s</GeoTransform>' % ', '.join(map(str,reference_ds.GetGeoTransform())))

        for f in filepaths:
            d=Dataset(f)
            reference_ds,d=reference_ds.apply_environment(d)
            self._datasets.append(d)

            rb=d.GetRasterBand(band+1) #gdal band index start at 1
            nodata=rb.GetNoDataValue()
            path=d.GetDescription()
            rel=not os.path.isabs(path)
            vrt.append('  <VRTRasterBand dataType="%s" band="%s">' % (gdal.GetDataTypeName(rb.DataType), band+1))
            vrt.append('    <SimpleSource>')
            vrt.append('      <SourceFilename relativeToVRT="%s">%s</SourceFilename>' % (int(rel),path))
            vrt.append('      <SourceBand>%s</SourceBand>'%(band+1))
            vrt.append('      <SrcRect xOff="0" yOff="0" xSize="%s" ySize="%s" />' % (d.RasterXSize,d.RasterYSize))
            vrt.append('      <DstRect xOff="0" yOff="0" xSize="%s" ySize="%s" />' % (d.RasterXSize,d.RasterYSize))
            vrt.append('    </SimpleSource>')
            if nodata is not None: # 0 is a valid value
                vrt.append('    <NoDataValue>%s</NoDataValue>' % nodata)
            vrt.append('  </VRTRasterBand>')
        vrt.append('</VRTDataset>')

        vrt='\n'.join(vrt)
        return vrt 
Example 6
Project: dask-geomodeling   Author: nens   File: utils.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def create_dataset(array, geo_transform=None, projection=None, no_data_value=None):
    """
    Create and return a gdal dataset.

    :param array: A numpy array.
    :param geo_transform: 6-tuple of floats
    :param projection: wkt projection string
    :param no_data_value: integer or float

    This is the fastest way to get a gdal dataset from a numpy array, but
    keep a reference to the array around, or a segfault will occur. Also,
    don't forget to call FlushCache() on the dataset after any operation
    that affects the array.
    """
    # prepare dataset name pointing to array
    datapointer = array.ctypes.data
    bands, lines, pixels = array.shape
    datatypecode = gdal_array.NumericTypeCodeToGDALTypeCode(array.dtype.type)
    datatype = gdal.GetDataTypeName(datatypecode)
    bandoffset, lineoffset, pixeloffset = array.strides
    # if projection is wrong there will be a segfault in RasterizeLayer
    projection = osr.GetUserInputAsWKT(str(projection))

    dataset_name_template = (
        "MEM:::"
        "DATAPOINTER={datapointer},"
        "PIXELS={pixels},"
        "LINES={lines},"
        "BANDS={bands},"
        "DATATYPE={datatype},"
        "PIXELOFFSET={pixeloffset},"
        "LINEOFFSET={lineoffset},"
        "BANDOFFSET={bandoffset}"
    )
    dataset_name = dataset_name_template.format(
        datapointer=datapointer,
        pixels=pixels,
        lines=lines,
        bands=bands,
        datatype=datatype,
        pixeloffset=pixeloffset,
        lineoffset=lineoffset,
        bandoffset=bandoffset,
    )

    # access the array memory as gdal dataset
    dataset = gdal.Open(dataset_name, gdal.GA_Update)

    # set additional properties from kwargs
    if geo_transform is not None:
        dataset.SetGeoTransform(geo_transform)
    if projection is not None:
        dataset.SetProjection(projection)
    if no_data_value is not None:
        for i in range(len(array)):
            dataset.GetRasterBand(i + 1).SetNoDataValue(no_data_value)

    return dataset 
Example 7
Project: pygeotools   Author: dshean   File: iolib.py    MIT License 4 votes vote down vote up
def get_ndv_b(b):
    """Get NoData value for GDAL band.

    If NoDataValue is not set in the band, 
    extract upper left and lower right pixel values.
    Otherwise assume NoDataValue is 0.
 
    Parameters
    ----------
    b : GDALRasterBand object 
        This is the input band.
 
    Returns
    -------
    b_ndv : float 
        NoData value 
    """

    b_ndv = b.GetNoDataValue()
    if b_ndv is None:
        #Check ul pixel for ndv
        ns = b.XSize
        nl = b.YSize
        ul = float(b.ReadAsArray(0, 0, 1, 1))
        #ur = float(b.ReadAsArray(ns-1, 0, 1, 1))
        lr = float(b.ReadAsArray(ns-1, nl-1, 1, 1))
        #ll = float(b.ReadAsArray(0, nl-1, 1, 1))
        #Probably better to use 3/4 corner criterion
        #if ul == ur == lr == ll:
        if np.isnan(ul) or ul == lr:
            b_ndv = ul
        else:
            #Assume ndv is 0
            b_ndv = 0
    elif np.isnan(b_ndv):
        b_dt = gdal.GetDataTypeName(b.DataType)
        if 'Float' in b_dt:
            b_ndv = np.nan
        else:
            b_ndv = 0
    return b_ndv

#Write out a recarray as a csv