Exemple #1
0
def create_proximity_raster(src, dst, values, units='PIXEL'):
    """
    Creates a proximity raster using gdal.ComputeProximity. NoData pixels in
    the src raster will be considered NoData pixels in the dst raster.
    :param src: source raster filename
    :param dst: dest raster filename
    :return:    None
    """
    # open src raster
    ds = gdal.Open(src, 0)
    gt = ds.GetGeoTransform()
    sr = ds.GetProjection()
    cols = ds.RasterXSize
    rows = ds.RasterYSize

    # create dst raster
    driver = gdal.GetDriverByName('GTiff')
    out_ds = driver.Create(dst, cols, rows, 1, gdal.GDT_Int16)
    out_ds.SetGeoTransform(gt)
    out_ds.SetProjection(sr)

    # define options for gdal.ComputeProximity and execute it
    options = [
        f'VALUES={",".join(map(str, values))}', f'DISTUNITS={units}',
        'USE_INPUT_NODATA=YES'
    ]
    gdal.ComputeProximity(ds.GetRasterBand(1), out_ds.GetRasterBand(1),
                          options)

    del ds, out_ds
Exemple #2
0
def gdal_proximity(src_fn, dst_fn):
    '''Compute a proximity grid via GDAL'''

    prog_func = None

    src_ds = gdal.Open(src_fn)
    dst_ds = None

    if src_ds is not None:
        src_band = src_ds.GetRasterBand(1)
        ds_config = _gather_infos(src_ds)

        if dst_ds is None:
            drv = gdal.GetDriverByName('GTiff')
            dst_ds = drv.Create(dst_fn, ds_config['nx'], ds_config['ny'], 1,
                                ds_config['dt'], [])

        dst_ds.SetGeoTransform(ds_config['geoT'])
        dst_ds.SetProjection(ds_config['proj'])

        dst_band = dst_ds.GetRasterBand(1)
        dst_band.SetNoDataValue(ds_config['ndv'])

        gdal.ComputeProximity(src_band,
                              dst_band, ['DISTUNITS=PIXEL'],
                              callback=prog_func)
        dst_band = src_band = dst_ds = src_ds = None

        return (0)
    else:
        return (None)
Exemple #3
0
def proximitize(raster_fn, src_band, dst_band):
    target_ds = gdal.Open(raster_fn, gdal.GA_Update)
    if target_ds is None:
        print("Error: could not open raster file '%s'" % raster_fn)
    src = target_ds.GetRasterBand(src_band)
    dst = target_ds.GetRasterBand(dst_band)
    options = ['NODATA=-9999', 'DISTUNITS=GEO', 'VALUES=1']
    gdal.ComputeProximity(src, dst, options)
Exemple #4
0
    def create_proximity_raster(self, input_type):

        # Valider si c'est wetland ou water et règle le chemin de sortie pour le raster qui sera créé.
        if (input_type == "wetland"):
            self.communications.show_message(
                "info", u"Création du raster de proximité wetland")
            temp_write_path = self.output_path + os.sep + 'create_prox_raster_wl.tif'
        if (input_type == "water"):
            self.communications.show_message(
                "info", u"Création du raster de proximité water")
            temp_write_path = self.output_path + os.sep + 'create_prox_raster_w.tif'

        # Créer l'image en sortie et ouvrir la bande de gris
        proximity_img = self.writeDriver.Create(temp_write_path, self.cols,
                                                self.rows, 1, GDT_Float32)
        proximity_img.SetGeoTransform(self.input_geot)
        proximity_img.SetProjection(self.input_prj)
        proximity_img_band1 = proximity_img.GetRasterBand(1)

        # Retourne un raster du calcul de proximité
        self.water_rast_img_band1 = self.water_rast_img.GetRasterBand(1)
        if (input_type == "wetland"):
            self.wetland_prox = temp_write_path
            gdal.ComputeProximity(self.wetland_rast_img_band1,
                                  proximity_img_band1, [])
            self.wetland_prox_data = proximity_img_band1.ReadAsArray(
                0, 0, self.cols, self.rows)
            self.reclass_proximity("wetland", self.wetland_prox_data)

        if (input_type == "water"):
            self.water_prox = temp_write_path
            gdal.ComputeProximity(self.water_rast_img_band1,
                                  proximity_img_band1, [])
            self.water_prox_data = proximity_img_band1.ReadAsArray(
                0, 0, self.cols, self.rows)
            self.reclass_proximity("water", self.water_prox_data)
    road_proj_lyr.CreateFeature(outFeat)
    # Get the next feature
    inFeat = road_lyr.GetNextFeature()
# adjust the geotranform to achieve a finer resolution at first
in_gt = FL.GetGeoTransform()
out_gt = [in_gt[0], in_gt[1] / 10, 0, in_gt[3], 0, in_gt[5] / 10]

# (1) Rasterize the projected road shapefile
road_ras = drvMemR.Create('', FL.RasterXSize * 10, FL.RasterYSize * 10, 1,
                          gdal.GDT_Byte)
road_ras.SetProjection(FL.GetProjection())
road_ras.SetGeoTransform(out_gt)
gdal.RasterizeLayer(road_ras, [1], road_proj_lyr, options=["ATTRIBUTE=Value"])
# (2) Calculate the distance raster
road_dist = drvMemR.Create('', FL.RasterXSize * 10, FL.RasterYSize * 10, 1,
                           gdal.GDT_Float32)
road_dist.SetProjection(FL.GetProjection())
road_dist.SetGeoTransform(out_gt)
gdal.ComputeProximity(road_ras.GetRasterBand(1),
                      road_dist.GetRasterBand(1),
                      options=['VALUES=1', 'DISTUNITS=GEO'])
# (4) Copy new raster to disc
drvR.CreateCopy(workFolder + "DistanceToRoad_1km.tif", road_dist)
# ####################################### END TIME-COUNT AND PRINT TIME STATS################################## #
print("")
endtime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
print("--------------------------------------------------------")
print("--------------------------------------------------------")
print("start: " + starttime)
print("end: " + endtime)
print("")
    def processAlgorithm(self, parameters, context, feedback):

        source = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        PINF = -3.402823466e+38

        outRasterSRS = osr.SpatialReference()
        srs = source.crs()
        wkt = srs.toWkt()
        outRasterSRS.ImportFromWkt(wkt)

        src_ds = gdal.Open(source.dataProvider().dataSourceUri())
        srcband = src_ds.GetRasterBand(1)

        StepX = src_ds.GetGeoTransform()[1]

        drv = gdal.GetDriverByName('GTiff')

        outdist = '/Users/tsamsonov/GitHub/raster-space/dist.tif'
        dst_ds = drv.Create(outdist, src_ds.RasterXSize, src_ds.RasterYSize, 1,
                            gdal.GetDataTypeByName('Float32'))

        dst_ds.SetGeoTransform(src_ds.GetGeoTransform())
        dst_ds.SetProjection(src_ds.GetProjectionRef())

        dstband = dst_ds.GetRasterBand(1)

        # In this example I'm using target pixel values of 100 and 300. I'm also using Distance units as GEO but you can change that to PIXELS.
        gdal.ComputeProximity(srcband, dstband, ["DISTUNITS=GEO"])
        dstband.FlushCache()

        dist = gdal.Open(outdist)

        if dist is None:
            QgsMessageLog.logMessage('Unable to open ' + outdist)
        else:
            QgsMessageLog.logMessage(str(dist.RasterCount))
            npblocks = np.array(srcband.ReadAsArray())  # length testing
            npdist = np.array(dstband.ReadAsArray())  # length testing

            npwid0 = np.full(npdist.shape, 0)
            nplen0 = np.full(npdist.shape, 0)

            nodata = -1

            npwid = rspace.estimate_width(npdist, npwid0, StepX, nodata)
            nplen = np.array(
                rspace.estimate_length(npblocks, npwid, StepX, nodata, 720,
                                       12000)).reshape((4, npdist.shape[0],
                                                        npdist.shape[1]))

            QgsMessageLog.logMessage(rspace.__file__)

            res = drv.Create(output, src_ds.RasterXSize, src_ds.RasterYSize, 5,
                             gdal.GetDataTypeByName('Float32'))

            res.SetGeoTransform(src_ds.GetGeoTransform())
            res.SetProjection(src_ds.GetProjectionRef())

            outband = res.GetRasterBand(1)
            outband.WriteArray(npwid, 0, 0)

            outband = res.GetRasterBand(2)
            outband.WriteArray(nplen[0, :], 0, 0)

            outband = res.GetRasterBand(3)
            outband.WriteArray(nplen[1, :], 0, 0)

            outband = res.GetRasterBand(4)
            outband.WriteArray(nplen[2, :], 0, 0)

            outband = res.GetRasterBand(5)
            outband.WriteArray(nplen[3, :], 0, 0)

            outband.FlushCache()
            outband.SetNoDataValue(-1)

        return {self.OUTPUT: source}
    def processAlgorithm(self, parameters, context, feedback):

        source = self.parameterAsSource(parameters, self.INPUT, context)
        res = self.parameterAsDouble(parameters, self.RES, context)
        outwidth = self.parameterAsOutputLayer(parameters, self.OUTPUT,
                                               context)

        PINF = -3.402823466e+38

        ext = source.sourceExtent()
        Xmin = ext.xMinimum() + res
        Xmax = ext.xMaximum() - res
        Ymin = ext.yMinimum() + res
        Ymax = ext.yMaximum() - res
        SizeX = Xmax - Xmin
        SizeY = Ymax - Ymin
        Nx = int(round(SizeX / res) + 1)
        Ny = int(round(SizeY / res) + 1)
        StepX = SizeX / (Nx - 1)
        StepY = SizeY / (Ny - 1)

        outRasterSRS = osr.SpatialReference()
        srs = source.sourceCrs()
        wkt = srs.toWkt()
        outRasterSRS.ImportFromWkt(wkt)

        opts = gdal.RasterizeOptions(outputBounds=[Xmin, Ymin, Xmax, Ymax],
                                     xRes=res,
                                     yRes=res,
                                     format="GTiff",
                                     burnValues=[1],
                                     outputSRS=outRasterSRS)

        QgsMessageLog.logMessage(outwidth)

        QgsMessageLog.logMessage(source.sourceName())

        rasterized = "/Users/tsamsonov/GitHub/raster-space/rasterized.tif"
        gdal.Rasterize(
            rasterized,
            "/Users/tsamsonov/GitHub/raster-space/output/buildings_dem_s.shp",
            options=opts)

        src_ds = gdal.Open(rasterized)
        srcband = src_ds.GetRasterBand(1)

        drv = gdal.GetDriverByName('GTiff')

        outdist = '/Users/tsamsonov/GitHub/raster-space/dist.tif'
        dst_ds = drv.Create('/Users/tsamsonov/GitHub/raster-space/dist.tif',
                            src_ds.RasterXSize, src_ds.RasterYSize, 1,
                            gdal.GetDataTypeByName('Float32'))

        dst_ds.SetGeoTransform(src_ds.GetGeoTransform())
        dst_ds.SetProjection(src_ds.GetProjectionRef())

        dstband = dst_ds.GetRasterBand(1)

        # In this example I'm using target pixel values of 100 and 300. I'm also using Distance units as GEO but you can change that to PIXELS.
        gdal.ComputeProximity(srcband, dstband, ["DISTUNITS=GEO"])
        dstband.FlushCache()

        dist = gdal.Open(outdist)

        if dist is None:
            QgsMessageLog.logMessage('Unable to open ' + outwidth)
        else:
            QgsMessageLog.logMessage(str(dist.RasterCount))
            # npdist = np.array(dstband.ReadAsArray())
            npdist = np.array(srcband.ReadAsArray())  # length testing

            QgsMessageLog.logMessage(str(npdist.shape))

            npwid = np.full(npdist.shape, 0)
            QgsMessageLog.logMessage(str(npwid.shape))

            nodata = -1

            # npres = rspace.estimate_width(npdist, npwid, StepX, nodata)
            npres = rspace.estimate_length(npdist, npwid, StepX, nodata, 2048,
                                           2000)
            QgsMessageLog.logMessage(str(StepX))
            QgsMessageLog.logMessage(str(np.min(npdist)))
            QgsMessageLog.logMessage(str(np.max(npdist)))

            QgsMessageLog.logMessage(rspace.__file__)

            res = drv.Create(outwidth, src_ds.RasterXSize, src_ds.RasterYSize,
                             1, gdal.GetDataTypeByName('Float32'))

            res.SetGeoTransform(src_ds.GetGeoTransform())
            res.SetProjection(src_ds.GetProjectionRef())

            outband = res.GetRasterBand(1)
            outband.WriteArray(npres, 0, 0)
            outband.FlushCache()
            outband.SetNoDataValue(-1)

        return {self.OUTPUT: source}
Exemple #8
0
# =============================================================================
# Date:     June, 2019
# Author:   Marcelo Villa P.
# Purpose:  Creates a raster with the (pixel) distance to the closest target.
# Notes:    Uses gdal.ComputeProximity() function to compute the distance.
# =============================================================================
import gdal

# open rasterized file and get information
fn = '../data/raster/COL_rails.tif'
ds = gdal.Open(fn, 0)
band = ds.GetRasterBand(1)
gt = ds.GetGeoTransform()
sr = ds.GetProjection()
cols = ds.RasterXSize
rows = ds.RasterYSize

# create empty proximity raster
out_fn = '../data/raster/COL_rails_proximity.tif'
driver = gdal.GetDriverByName('GTiff')
out_ds = driver.Create(out_fn, cols, rows, 1, gdal.GDT_Float32)
out_ds.SetGeoTransform(gt)
out_ds.SetProjection(sr)
out_band = out_ds.GetRasterBand(1)

# compute proximity
gdal.ComputeProximity(band, out_band, ['VALUES=1', 'DISTUNITS=PIXEL'])

# delete input and output rasters
del ds, out_ds
Exemple #9
0
def create_dist_map(rasterSrc,
                    vectorSrc,
                    npDistFileName='',
                    noDataValue=0,
                    burn_values=1,
                    dist_mult=1,
                    vmax_dist=64):
    '''
    Create building signed distance transform from Yuan 2016 
    (https://arxiv.org/pdf/1602.06564v1.pdf).
    vmax_dist: absolute value of maximum distance (meters) from building edge
    Adapted from createNPPixArray in labeltools
    '''

    ## open source vector file that truth data
    source_ds = ogr.Open(vectorSrc)
    source_layer = source_ds.GetLayer()

    ## extract data from src Raster File to be emulated
    ## open raster file that is to be emulated
    srcRas_ds = gdal.Open(rasterSrc)
    cols = srcRas_ds.RasterXSize
    rows = srcRas_ds.RasterYSize

    geoTrans, poly, ulX, ulY, lrX, lrY = gT.getRasterExtent(srcRas_ds)
    transform_WGS84_To_UTM, transform_UTM_To_WGS84, utm_cs \
                                        = gT.createUTMTransform(poly)
    line = ogr.Geometry(ogr.wkbLineString)
    line.AddPoint(geoTrans[0], geoTrans[3])
    line.AddPoint(geoTrans[0] + geoTrans[1], geoTrans[3])

    line.Transform(transform_WGS84_To_UTM)
    metersIndex = line.Length()

    memdrv = gdal.GetDriverByName('MEM')
    dst_ds = memdrv.Create('', cols, rows, 1, gdal.GDT_Byte)
    dst_ds.SetGeoTransform(srcRas_ds.GetGeoTransform())
    dst_ds.SetProjection(srcRas_ds.GetProjection())
    band = dst_ds.GetRasterBand(1)
    band.SetNoDataValue(noDataValue)

    gdal.RasterizeLayer(dst_ds, [1], source_layer, burn_values=[burn_values])
    srcBand = dst_ds.GetRasterBand(1)

    memdrv2 = gdal.GetDriverByName('MEM')
    prox_ds = memdrv2.Create('', cols, rows, 1, gdal.GDT_Int16)
    prox_ds.SetGeoTransform(srcRas_ds.GetGeoTransform())
    prox_ds.SetProjection(srcRas_ds.GetProjection())
    proxBand = prox_ds.GetRasterBand(1)
    proxBand.SetNoDataValue(noDataValue)

    opt_string = 'NODATA=' + str(noDataValue)
    options = [opt_string]

    gdal.ComputeProximity(srcBand, proxBand, options)

    memdrv3 = gdal.GetDriverByName('MEM')
    proxIn_ds = memdrv3.Create('', cols, rows, 1, gdal.GDT_Int16)
    proxIn_ds.SetGeoTransform(srcRas_ds.GetGeoTransform())
    proxIn_ds.SetProjection(srcRas_ds.GetProjection())
    proxInBand = proxIn_ds.GetRasterBand(1)
    proxInBand.SetNoDataValue(noDataValue)
    opt_string2 = 'VALUES=' + str(noDataValue)
    options = [opt_string, opt_string2]
    #options = ['NODATA=0', 'VALUES=0']

    gdal.ComputeProximity(srcBand, proxInBand, options)

    proxIn = gdalnumeric.BandReadAsArray(proxInBand)
    proxOut = gdalnumeric.BandReadAsArray(proxBand)

    proxTotal = proxIn.astype(float) - proxOut.astype(float)
    proxTotal = proxTotal * metersIndex
    proxTotal *= dist_mult

    # clip array
    proxTotal = np.clip(proxTotal, -1 * vmax_dist, 1 * vmax_dist)

    if npDistFileName != '':
        # save as numpy file since some values will be negative
        np.save(npDistFileName, proxTotal)
        #cv2.imwrite(npDistFileName, proxTotal)

    #return proxTotal
    return