Ejemplo n.º 1
0
def test_gdaldem_lib_color_relief():

    src_ds = gdal.Open('../gdrivers/data/n43.dt0')
    ds = gdal.DEMProcessing('',
                            src_ds,
                            'color-relief',
                            format='MEM',
                            colorFilename='data/color_file.txt')
    assert ds is not None

    assert ds.GetRasterBand(1).Checksum() == 55009, 'Bad checksum'

    assert ds.GetRasterBand(2).Checksum() == 37543, 'Bad checksum'

    assert ds.GetRasterBand(3).Checksum() == 47711, 'Bad checksum'

    src_gt = src_ds.GetGeoTransform()
    dst_gt = ds.GetGeoTransform()
    for i in range(6):
        assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform'

    dst_wkt = ds.GetProjectionRef()
    assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection'

    ds = gdal.DEMProcessing('',
                            src_ds,
                            'color-relief',
                            format='MEM',
                            colorFilename='data/color_file.txt',
                            addAlpha=True)
    assert ds.RasterCount == 4, 'Bad RasterCount'

    src_ds = None
    ds = None
Ejemplo n.º 2
0
def test_gdaldem_lib_nodata():

    for (value, typ) in [(0, gdal.GDT_Byte), (1, gdal.GDT_Byte),
                         (255, gdal.GDT_Byte), (0, gdal.GDT_UInt16),
                         (1, gdal.GDT_UInt16), (65535, gdal.GDT_UInt16),
                         (0, gdal.GDT_Int16), (-32678, gdal.GDT_Int16),
                         (32767, gdal.GDT_Int16)]:
        src_ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 1, typ)
        src_ds.GetRasterBand(1).SetNoDataValue(value)
        src_ds.GetRasterBand(1).Fill(value)

        ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM')
        assert ds is not None

        cs = ds.GetRasterBand(1).Checksum()
        assert cs == 0, 'Bad checksum'

        src_ds = None
        ds = None

    src_ds = gdal.GetDriverByName('MEM').Create('', 3, 3, 1)
    src_ds.GetRasterBand(1).SetNoDataValue(0)
    src_ds.GetRasterBand(1).WriteRaster(1, 1, 1, 1, struct.pack('B', 255))

    ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM')
    cs = ds.GetRasterBand(1).Checksum()
    if cs != 0:
        print(ds.ReadAsArray())
        pytest.fail('Bad checksum')

    ds = gdal.DEMProcessing('',
                            src_ds,
                            'hillshade',
                            format='MEM',
                            computeEdges=True)
    cs = ds.GetRasterBand(1).Checksum()
    if cs != 10:
        print(ds.ReadAsArray())  # Should be 0 0 0 0 181 0 0 0 0
        pytest.fail('Bad checksum')

    # Same with floating point
    src_ds = gdal.GetDriverByName('MEM').Create('', 3, 3, 1, gdal.GDT_Float32)
    src_ds.GetRasterBand(1).SetNoDataValue(0)
    src_ds.GetRasterBand(1).WriteRaster(1, 1, 1, 1, struct.pack('f', 255))

    ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM')
    cs = ds.GetRasterBand(1).Checksum()
    if cs != 0:
        print(ds.ReadAsArray())
        pytest.fail('Bad checksum')

    ds = gdal.DEMProcessing('',
                            src_ds,
                            'hillshade',
                            format='MEM',
                            computeEdges=True)
    cs = ds.GetRasterBand(1).Checksum()
    if cs != 10:
        print(ds.ReadAsArray())  # Should be 0 0 0 0 181 0 0 0 0
        pytest.fail('Bad checksum')
Ejemplo n.º 3
0
def calculatingSlopeAspectNorthness(demFilename,slopeFileName,aspectFileName,elevationMissNoS0f):
    gdal.DEMProcessing(slopeFileName, demFilename, 'slope')
    with rasterio.open(slopeFileName) as datasets1:
        slope=datasets1.read(1) #slope in degree
    slope_rad = slope * 0.0174533 #slope in radian
    slope_sin = np.sin(slope_rad)

    gdal.DEMProcessing(aspectFileName, demFilename, 'aspect')
    with rasterio.open(aspectFileName) as dataseta:
        aspect=dataseta.read(1)
    aspect_rad = aspect * 0.0174533 #radian
    aspect_cos = np.cos(aspect_rad)
    
    northness=aspect_cos*slope_sin
    
    #elevation,nrows,ncols,lat,Long
    demset = gdal.Open(filenameIn)
    band = demset.GetRasterBand(1)
    elevation = band.ReadAsArray()
    elevation[elevation == -9999.] = elevationMissNoS0f
    elevation[elevation < 0] = elevationMissNoS0f
    elevation[elevation > 10000.] = elevationMissNoS0f

    x0, dx, dxdy, y0, dydx, dy = demset.GetGeoTransform()
    nrows, ncols = elevation.shape
    x1 = x0 + dx * ncols
    y1 = y0 + dy * nrows
    extent1=[x0, x1, y1, y0]
    
    latitude =[]
    for x in range (ncols):
        latitude.append(x+x0)
    longitude = []
    for y in range (nrows):
        longitude.append(y0-y)
Ejemplo n.º 4
0
def test_gdaldem_lib_color_relief():

    src_ds = gdal.Open('../gdrivers/data/n43.dt0')
    ds = gdal.DEMProcessing('',
                            src_ds,
                            'color-relief',
                            format='MEM',
                            colorFilename='data/color_file.txt')
    if ds is None:
        return 'fail'

    if ds.GetRasterBand(1).Checksum() != 55009:
        print(ds.GetRasterBand(1).Checksum())
        gdaltest.post_reason('Bad checksum')
        return 'fail'

    if ds.GetRasterBand(2).Checksum() != 37543:
        print(ds.GetRasterBand(2).Checksum())
        gdaltest.post_reason('Bad checksum')
        return 'fail'

    if ds.GetRasterBand(3).Checksum() != 47711:
        print(ds.GetRasterBand(3).Checksum())
        gdaltest.post_reason('Bad checksum')
        return 'fail'

    src_gt = src_ds.GetGeoTransform()
    dst_gt = ds.GetGeoTransform()
    for i in range(6):
        if abs(src_gt[i] - dst_gt[i]) > 1e-10:
            gdaltest.post_reason('Bad geotransform')
            return 'fail'

    dst_wkt = ds.GetProjectionRef()
    if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1:
        gdaltest.post_reason('Bad projection')
        return 'fail'

    ds = gdal.DEMProcessing('',
                            src_ds,
                            'color-relief',
                            format='MEM',
                            colorFilename='data/color_file.txt',
                            addAlpha=True)
    if ds.RasterCount != 4:
        gdaltest.post_reason('Bad RasterCount')
        return 'fail'

    src_ds = None
    ds = None

    return 'success'
Ejemplo n.º 5
0
def run_gdaldem(filepath: str, processing: str, options: str | None = None) -> np.ma.masked_array:
    """Run GDAL's DEMProcessing and return the read numpy array."""
    # Rasterio strongly recommends against importing gdal along rio, so this is done here instead.
    from osgeo import gdal

    # Converting string into gdal processing options here to avoid import gdal outside this function:
    # Riley or Wilson for Terrain Ruggedness, and Zevenberg or Horn for slope, aspect and hillshade
    gdal_option_conversion = {
        "Riley": gdal.DEMProcessingOptions(alg="Riley"),
        "Wilson": gdal.DEMProcessingOptions(alg="Wilson"),
        "Zevenberg": gdal.DEMProcessingOptions(alg="ZevenbergenThorne"),
        "Horn": gdal.DEMProcessingOptions(alg="Horn"),
        "hillshade_Zevenberg": gdal.DEMProcessingOptions(azimuth=315, altitude=45, alg="ZevenbergenThorne"),
        "hillshade_Horn": gdal.DEMProcessingOptions(azimuth=315, altitude=45, alg="Horn")
    }

    if options is None:
        gdal_option = gdal.DEMProcessingOptions(options=None)
    else:
        gdal_option = gdal_option_conversion[options]

    temp_dir = tempfile.TemporaryDirectory()
    temp_path = os.path.join(temp_dir.name, "output.tif")
    gdal.DEMProcessing(
        destName=temp_path,
        srcDS=filepath,
        processing=processing,
        options=gdal_option,
    )

    data = gu.Raster(temp_path).data
    temp_dir.cleanup()
    return data
Ejemplo n.º 6
0
def create_slope(folder, scr_filename):
    out_filename = folder + DemToTopoUtills.add_file_name_marker_tif(scr_filename, DemToTopoConsts.SLOPE_EXT)
    gdal.DEMProcessing(out_filename, folder + scr_filename, 'slope', format='GTiff',
                       scale=111120, azimuth=90, computeEdges=True)

    DemToTopoUtills.print_dot()
    return out_filename
Ejemplo n.º 7
0
def create_hill_shade(folder, scr_filename):
    out_filename = folder + DemToTopoUtills.add_file_name_marker_tif(scr_filename, DemToTopoConsts.HILL_SHADE_EXT)
    gdal.DEMProcessing(out_filename, folder + scr_filename, 'hillshade', format='GTiff',
                       zFactor=5, scale=111120, azimuth=90, computeEdges=True)

    DemToTopoUtills.print_dot()
    return out_filename
Ejemplo n.º 8
0
def create_color_relief(folder, scr_filename, color_altitude_file):
    out_filename = folder + DemToTopoUtills.add_file_name_marker_tif(scr_filename, DemToTopoConsts.COLOR_RELIEF_EXT)
    gdal.DEMProcessing(out_filename, folder + scr_filename, 'color-relief', format='GTiff',
                       colorFilename=color_altitude_file)

    DemToTopoUtills.print_dot()
    return out_filename
Ejemplo n.º 9
0
def test_gdaldem_lib_hillshade_azimuth():

    src_ds = gdal.GetDriverByName('MEM').Create('', 100, 100, 1)
    src_ds.SetGeoTransform([2, 0.01, 0, 49, 0, -0.01])
    sr = osr.SpatialReference()
    sr.ImportFromEPSG(4326)
    src_ds.SetProjection(sr.ExportToWkt())
    for j in range(100):
        data = ''
        for i in range(100):
            val = 255 - 5 * max(abs(50 - i), abs(50 - j))
            data = data + chr(val)
        data = data.encode('ISO-8859-1')
        src_ds.GetRasterBand(1).WriteRaster(0, j, 100, 1, data)

    # Light from the east
    ds = gdal.DEMProcessing('',
                            src_ds,
                            'hillshade',
                            format='MEM',
                            azimuth=90,
                            scale=111120,
                            zFactor=100)
    assert ds is not None
    ds_ref = gdal.Open('data/pyramid_shaded_ref.tif')
    assert gdaltest.compare_ds(ds, ds_ref, verbose=1) <= 1, 'Bad checksum'
    ds = None
    ds_ref = None
Ejemplo n.º 10
0
def gdal_dem_derivative(input_dem,
                        output_path,
                        derivative,
                        return_array=False,
                        *args):
    '''
    Take an input DEM and create a derivative product
    input_dem: DEM
    derivate: one of "hillshade", "slope", "aspect", "color-relief", "TRI", "TPI", "Roughness"
    return_array: optional argument to return the computed derivative as an array. (slow IO as it just loads the new file.)
    Example usage: slope_array = dem_derivative(dem, 'slope', array=True)
    '''

    supported_derivatives = [
        "hillshade", "slope", "aspect", "color-relief", "TRI", "TPI",
        "Roughness"
    ]
    if derivative not in supported_derivatives:
        logging.error('Unsupported derivative type. Must be one of: {}'.format(
            supported_derivatives))
        sys.exit()


#    out_name = '{}_{}.tif'.format(os.path.basename(input_dem).split('.')[0], derivative)
#    out_path = os.path.join(os.path.dirname(input_dem), out_name)

    gdal.DEMProcessing(output_path, input_dem, derivative, *args)

    if return_array:
        from RasterWrapper import Raster
        array = Raster(output_path).Array

        return array
Ejemplo n.º 11
0
def aspect_from_dem(dem_file_path, output=None):

    if not output:
        output = pth.splitext(dem_file_path)[0] + '_aspect.tif'

    gdal.DEMProcessing(output, dem_file_path, "aspect", computeEdges=True)
    return output
Ejemplo n.º 12
0
def slope_from_dem(dem_file_path, output=None):

    if not output:
        output = dem_file_path.replace('.tif', '_slope.tif')

    gdal.DEMProcessing(output, dem_file_path, "slope", computeEdges=True)
    return output
Ejemplo n.º 13
0
def gdal_dem_derivative(input_dem, output_path, derivative, return_array=False, **args):
    '''
    Take an input DEM and create a derivative product
    input_dem: DEM
    derivative: one of "hillshade", "slope", "aspect", "color-relief", "TRI", "TPI", "Roughness"
    return_array: optional argument to return the computed derivative as an array. (slow IO as it just loads the new file.)
    Example usage: slope_array = dem_derivative(dem, 'slope', array=True)
    '''

    supported_derivatives = ["hillshade", "slope", "aspect", "color-relief", 
                             "TRI", "TPI", "Roughness"]
    if derivative not in supported_derivatives:
        logger.error('Unsupported derivative type. Must be one of: {}'.format(supported_derivatives))
        raise Exception

#    out_name = '{}_{}.tif'.format(os.path.basename(input_dem).split('.')[0], derivative)
#    out_path = os.path.join(os.path.dirname(input_dem), out_name)

    # if args:
        # dem_options = gdal.DEMProcessingOptions(args)
    logger.info('Creating and writing {} to: {}'.format(derivative, output_path))
    status = gdal.DEMProcessing(output_path, input_dem, derivative, **args)
    # logger.info(status)

    if return_array:
        array = Raster(output_path).Array

        return array
Ejemplo n.º 14
0
def batch_gdaldem(inlist, prop='aspect'):
    """
    batch dem calculation a load of gdal files from some format to tif
    
    Parameters
    ----------
    
    inlist: string
        A list of raster paths
    
    prop: string
        one of "hillshade", "slope", "aspect", "color-relief", "TRI",
        "TPI", "Roughness"
    
    Returns
    -------
    
    List of file paths
    
    """

    outpths = []

    for i in tqdm(inlist):

        ootpth = i[:-4] + prop + ".tif"
        srcds = gdal.Open(i)
        out = gdal.DEMProcessing(ootpth, srcds, prop)
        out.FlushCache()
        out = None
        outpths.append(ootpth)
    return outpths
Ejemplo n.º 15
0
    def gdaldem(self, Input1, Operation, OutputFilePath):
        """
		Creates an aspect layer from a digital elevation model by identifing the compass
		direction that the downhill slope faces for each location (returns with a value between 0-360 degrees)


		Parameters:
			Input1: An SpaDatasetRaster object OR a string representing the path to the raster file
			OutputFilePath: A file path for the output raster
			
		Return:
			A SpaDatasetRaster object depicting aspect	
		"""
        Input1 = SpaBase.GetInput(Input1)

        NewDataset = None

        # if a file path is specified, use it.  Otherwise, use the regular TempFilePath
        TempFilePath = None
        if (OutputFilePath == None):
            TempFilePath = SpaBase.GetTempFolderPath()
            if not os.path.exists(TempFilePath): os.makedirs(TempFilePath)
            TempFilePath += "Test.tif"
        else:
            TempFilePath = OutputFilePath

        GDALDataset1 = Input1.GDALDataset
        gdal.DEMProcessing(TempFilePath, GDALDataset1, Operation)

        if (OutputFilePath == None):
            NewDataset = SpaRasters.SpaDatasetRaster()
            NewDataset.Load(TempFilePath)
            NewDataset.NoDataValue = -9999

        return (NewDataset)
Ejemplo n.º 16
0
def test_gdaldem_lib_hillshade_ZevenbergenThorne_combined():

    src_ds = gdal.Open('../gdrivers/data/n43.dt0')
    ds = gdal.DEMProcessing('',
                            src_ds,
                            'hillshade',
                            format='MEM',
                            alg='ZevenbergenThorne',
                            combined=True,
                            scale=111120,
                            zFactor=30)
    assert ds is not None

    cs = ds.GetRasterBand(1).Checksum()
    assert cs == 43112, 'Bad checksum'

    src_gt = src_ds.GetGeoTransform()
    dst_gt = ds.GetGeoTransform()
    for i in range(6):
        assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform'

    dst_wkt = ds.GetProjectionRef()
    assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection'

    assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value'

    src_ds = None
    ds = None
Ejemplo n.º 17
0
def test_gdaldem_lib_hillshade_float():

    src_ds = gdal.Translate('', gdal.Open('../gdrivers/data/n43.dt0'), format = 'MEM', outputType = gdal.GDT_Float32)
    ds = gdal.DEMProcessing('', src_ds, 'hillshade', format = 'MEM', scale = 111120, zFactor = 30)
    if ds is None:
        return 'fail'

    cs = ds.GetRasterBand(1).Checksum()
    if cs != 45587:
        gdaltest.post_reason('Bad checksum')
        print(cs)
        return 'fail'

    src_gt = src_ds.GetGeoTransform()
    dst_gt = ds.GetGeoTransform()
    for i in range(6):
        if abs(src_gt[i] - dst_gt[i]) > 1e-10:
            gdaltest.post_reason('Bad geotransform')
            return 'fail'

    dst_wkt = ds.GetProjectionRef()
    if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1:
        gdaltest.post_reason('Bad projection')
        return 'fail'

    if ds.GetRasterBand(1).GetNoDataValue() != 0:
        gdaltest.post_reason('Bad nodata value')
        return 'fail'

    src_ds = None
    ds = None

    return 'success'
Ejemplo n.º 18
0
def test_gdaldem_lib_hillshade_azimuth():

    from sys import version_info
    src_ds = gdal.GetDriverByName('MEM').Create('', 100, 100, 1)
    src_ds.SetGeoTransform([2,0.01,0,49,0,-0.01])
    sr = osr.SpatialReference()
    sr.ImportFromEPSG(4326)
    src_ds.SetProjection(sr.ExportToWkt())
    for j in range(100):
        data = ''
        for i in range(100):
            val = 255 - 5 * max(abs(50-i),abs(50-j))
            data = data + ('%c' % (val))
        if version_info >= (3,0,0):
            data = bytes(data, 'ISO-8859-1')
        src_ds.GetRasterBand(1).WriteRaster(0,j,100,1,data)

    # Light from the east
    ds = gdal.DEMProcessing('', src_ds, 'hillshade', format = 'MEM', azimuth = 90, scale = 111120, zFactor = 100)
    if ds is None:
        return 'fail'
    ds_ref = gdal.Open('data/pyramid_shaded_ref.tif')
    if gdaltest.compare_ds(ds, ds_ref, verbose = 1) > 1:
        gdaltest.post_reason('Bad checksum')
        return 'fail'
    ds = None
    ds_ref = None

    return 'success'
Ejemplo n.º 19
0
def test_gdaldem_lib_hillshade_compute_edges_float():

    src_ds = gdal.Translate('',
                            gdal.Open('../gdrivers/data/n43.dt0'),
                            format='MEM',
                            outputType=gdal.GDT_Float32)
    ds = gdal.DEMProcessing('',
                            src_ds,
                            'hillshade',
                            format='MEM',
                            computeEdges=True,
                            scale=111120,
                            zFactor=30)
    if ds is None:
        return 'fail'

    cs = ds.GetRasterBand(1).Checksum()
    if cs != 50239:
        gdaltest.post_reason('Bad checksum')
        print(cs)
        return 'fail'

    ds = None

    return 'success'
Ejemplo n.º 20
0
def dem_to_hillshade(src_raster, band=0, alg='Horn', azimuth=315, altitude=45):
    """Calculate the hillshade for the DEM.

    Parameters
    ----------
    src_raster : Raster
        The dem used to calculate the hillshade.
    band : int, optional, default: 0
        source band number to use.
    alg : {'ZevenbergenThorne' or 'Horn'}, optional, default: Horn
        The literature suggests Zevenbergen & Thorne to be more suited to smooth landscapes, 
        where Horn’s formula to perform better on rougher terrain.
    azimuth : int, optional, default 315
        Azimuth of the light, in degrees. 0 if it comes from the top of the raster, 90 from the east, ... 
        The default value, 315, should rarely be changed as it is the value generally used to generate shaded maps.
    altitude : int, optional, default 45
        Altitude of the light, in degrees. 90 if the light comes from above the DEM, 0 if it is raking light.

    Returns
    -------
    dst_raster: Raster
        Hillshade calculated from the DEM.
    """
    options = dict(band=band + 1,
                   alg=alg,
                   azimuth=azimuth,
                   altitude=altitude,
                   format='MEM')
    ds_src = src_raster.to_gdal_ds()
    ds = gdal.DEMProcessing('', ds_src, 'hillshade', **options)
    dst_raster = tgp.read_gdal_ds(ds)
    return dst_raster
Ejemplo n.º 21
0
def dem_to_aspect(src_raster, band=0, alg='Horn', trigonometric=False):
    """Calculate the aspect for the DEM.

    Parameters
    ----------
    src_raster : Raster
        The dem used to calculate the aspect.
    band : int, optional, default: 0
        source band number to use.
    alg : {'ZevenbergenThorne' or 'Horn'}, optional, default: Horn
        The literature suggests Zevenbergen & Thorne to be more suited to smooth landscapes, 
        where Horn’s formula to perform better on rougher terrain.
    trigonometric: bool, optional, default: False
        whether to return trigonometric angle instead of azimuth. 
        Thus 0deg means East, 90deg North, 180deg West, 270deg South.

    Returns
    -------
    dst_raster: Raster
        Aspect calculated from the DEM.
    """
    options = dict(band=band + 1,
                   alg=alg,
                   trigonometric=trigonometric,
                   format='MEM')
    ds_src = src_raster.to_gdal_ds()
    ds = gdal.DEMProcessing('', ds_src, 'aspect', **options)
    dst_raster = tgp.read_gdal_ds(ds)
    return dst_raster
Ejemplo n.º 22
0
def dem_to_slope(src_raster, band=0, alg='Horn', slope_format='degree'):
    """Calculate the slope for the DEM.

    Parameters
    ----------
    src_raster : Raster
        The dem used to calculate the slope.
    band : int, optional, default: 0
        source band number to use.
    alg : {'ZevenbergenThorne' or 'Horn'}, optional, default: Horn
        The literature suggests Zevenbergen & Thorne to be more suited to smooth landscapes, 
        where Horn’s formula to perform better on rougher terrain.
    slope_format: {"degree" or "percent"}, optional, default degree
        The format of the slope.

    Returns
    -------
    dst_raster: Raster
        Slope calculated from the DEM.
    """
    options = dict(band=band + 1,
                   alg=alg,
                   slopeFormat=slope_format,
                   format='MEM')
    ds_src = src_raster.to_gdal_ds()
    ds = gdal.DEMProcessing('', ds_src, 'slope', **options)
    dst_raster = tgp.read_gdal_ds(ds)
    return dst_raster
Ejemplo n.º 23
0
def test_gdaldem_lib_hillshade_float():

    src_ds = gdal.Translate('',
                            gdal.Open('../gdrivers/data/n43.dt0'),
                            format='MEM',
                            outputType=gdal.GDT_Float32)
    ds = gdal.DEMProcessing('',
                            src_ds,
                            'hillshade',
                            format='MEM',
                            scale=111120,
                            zFactor=30)
    assert ds is not None

    cs = ds.GetRasterBand(1).Checksum()
    assert cs == 45587, 'Bad checksum'

    src_gt = src_ds.GetGeoTransform()
    dst_gt = ds.GetGeoTransform()
    for i in range(6):
        assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform'

    dst_wkt = ds.GetProjectionRef()
    assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection'

    assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value'

    src_ds = None
    ds = None
Ejemplo n.º 24
0
def calculatingSlopeAspectNorthness(demFilename, elevationMissNoS0f,
                                    slopeFileName, aspectFileName):
    gdal.DEMProcessing(slopeFileName, demFilename, 'slope')
    with rasterio.open(slopeFileName) as datasets1:
        slope = datasets1.read(1)  #slope in degree
    slope_rad = slope * 0.0174533  #slope in radian
    slope_sin = np.sin(slope_rad)

    gdal.DEMProcessing(aspectFileName, demFilename, 'aspect')
    with rasterio.open(aspectFileName) as dataseta:
        aspect = dataseta.read(1)
    aspect_rad = aspect * 0.0174533  #radian
    aspect_cos = np.cos(aspect_rad)

    northness = aspect_cos * slope_sin

    #elevation,nrows,ncols,lat,Long
    demset = gdal.Open(filenameIn)
    band = demset.GetRasterBand(1)
    elevation = band.ReadAsArray()
    elevation[elevation == -9999.] = elevationMissNoS0f
    elevation[elevation < 0] = elevationMissNoS0f
    elevation[elevation > 10000.] = elevationMissNoS0f

    x0, dx, dxdy, y0, dydx, dy = demset.GetGeoTransform()
    nrows, ncols = elevation.shape

    latitude = []
    for x in range(ncols):
        latitude.append(x + x0)
    longitude = []
    for y in range(nrows):
        longitude.append(y0 - y)

    latitude_rp = (np.tile(latitude, nrows)).astype(int)
    longitude_rp = (np.repeat(longitude, ncols)).astype(int)

    northness_col = np.reshape(northness, (nrows * ncols)).T
    elevation_col = np.reshape(elevation, (nrows * ncols)).T
    slope_col = np.reshape(slope, (nrows * ncols)).T
    elevNrth_gp = np.vstack(
        [latitude_rp, longitude_rp, northness_col, elevation_col]).T
    index_ls = np.vstack([
        latitude_rp, longitude_rp, northness_col, elevation_col, slope_col,
        elevation_col
    ]).T
    return elevNrth_gp, index_ls
Ejemplo n.º 25
0
def calcular_aspect(mde, aspect):
    """Calcula la orientacion a partir del modelo digital de elevaciones

    Args:
        mde: nombre del fichero con el modelo digital de elevaciones
        aspect: nombre del fichero de salida con la orientacion
    """
    gdal.DEMProcessing(aspect, mde, 'aspect')
Ejemplo n.º 26
0
def calculate_slope(DEM):
    gdal.DEMProcessing('slope.tif', DEM,
                       'slope')  #expressed in degrees (? need to check)
    with rasterio.open('slope.tif') as dataset:
        show(dataset)
        slope = dataset.read(
            1)  #the read methods returns an array of all the pixel values
    return slope
Ejemplo n.º 27
0
def calcular_slope(mde, slope):
    """Calcula la pendiente a partir del modelo digital de elevaciones

    Args:
        mde: nombre del fichero con el modelo digital de elevaciones
        slope: nombre del fichero de salida con la pendiente
    """
    gdal.DEMProcessing(slope, mde, 'slope')
Ejemplo n.º 28
0
def test_gdaldem_lib_aspect_ZevenbergenThorne():

    src_ds = gdal.Open('../gdrivers/data/n43.dt0')
    ds = gdal.DEMProcessing('', src_ds, 'aspect', format='MEM', alg='ZevenbergenThorne', scale=111120, zFactor=30)
    assert ds is not None

    cs = ds.GetRasterBand(1).Checksum()
    assert cs == 50539, 'Bad checksum'
Ejemplo n.º 29
0
def exportSlope(raster, filename):

    # process slope raster and save it
    # IMPORTANT NOTE: DEMprocessing using the INTERNAL scale of the GeoTiff, so the
    # geo transform MUST BE CORRECT to obtain a reliable calculation of the slope !!
    gdal.DEMProcessing(filename, raster, 'slope')
    with rio.open(filename) as dataset:
        slope = dataset.read(1).astype(np.float32)
    return slope
Ejemplo n.º 30
0
def test_gdaldem_lib_roughness():

    src_ds = gdal.Open('../gdrivers/data/n43.dt0')
    ds = gdal.DEMProcessing('', src_ds, 'roughness', format='MEM')
    assert ds is not None

    cs = ds.GetRasterBand(1).Checksum()
    assert cs == 38624, 'Bad checksum'

    ds = None