示例#1
0
def proximity_raster(src_filename, dst_filename, values, compression):
    src_ds = gdal.Open(src_filename)
    srcband = src_ds.GetRasterBand(1)
    dst_filename = dst_filename

    drv = gdal.GetDriverByName('GTiff')
    dst_ds = drv.Create(dst_filename,
                        src_ds.RasterXSize,
                        src_ds.RasterYSize,
                        1,
                        gdal.GetDataTypeByName('Float32'),
                        options=['COMPRESS={}'.format(compression)])

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

    dstband = dst_ds.GetRasterBand(1)

    gdal.ComputeProximity(srcband, dstband, [
        "VALUES={}".format(','.join([str(i) for i in values])), "DISTUNITS=GEO"
    ])
    srcband = None
    dstband = None
    src_ds = None
    dst_ds = None
示例#2
0
def proximity_1():

    drv = gdal.GetDriverByName('GTiff')
    src_ds = gdal.Open('data/pat.tif')
    src_band = src_ds.GetRasterBand(1)

    dst_ds = drv.Create('tmp/proximity_1.tif', 25, 25, 1, gdal.GDT_Byte)
    dst_band = dst_ds.GetRasterBand(1)

    gdal.ComputeProximity(src_band, dst_band)

    cs_expected = 1941
    cs = dst_band.Checksum()

    dst_band = None
    dst_ds = None

    if cs == cs_expected \
       or gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON':
        drv.Delete('tmp/proximity_1.tif')

    if cs != cs_expected:
        print('Got: ', cs)
        gdaltest.post_reason('got wrong checksum')
        return 'fail'
    return 'success'
示例#3
0
def _computeProximityArrArgsFunc(argVals):
    """
This function is used internally within calcDist2Classes for the multiprocessing Pool
"""
    import rsgislib.imageutils
    try:
        import tqdm
        pbar = tqdm.tqdm(total=100)
        callback = lambda *args, **kw: pbar.update()
    except:
        callback = gdal.TermProgress
    classImgDS = gdal.Open(argVals[0], gdal.GA_ReadOnly)
    classImgBand = classImgDS.GetRasterBand(1)
    rsgislib.imageutils.createCopyImage(argVals[0], argVals[1], 1, argVals[3],
                                        argVals[4], rsgislib.TYPE_32FLOAT)
    distImgDS = gdal.Open(argVals[1], gdal.GA_Update)
    distImgBand = distImgDS.GetRasterBand(1)
    gdal.ComputeProximity(classImgBand,
                          distImgBand,
                          argVals[2],
                          callback=callback)
    distImgBand = None
    distImgDS = None
    classImgBand = None
    classImgDS = None
示例#4
0
def proximity_2():

    drv = gdal.GetDriverByName('GTiff')
    src_ds = gdal.Open('data/pat.tif')
    src_band = src_ds.GetRasterBand(1)

    dst_ds = drv.Create('tmp/proximity_2.tif', 25, 25, 1, gdal.GDT_Float32)
    dst_band = dst_ds.GetRasterBand(1)

    gdal.ComputeProximity(src_band,
                          dst_band,
                          options=[
                              'VALUES=65,64', 'MAXDIST=12', 'NODATA=-1',
                              'FIXED_BUF_VAL=255'
                          ])

    cs_expected = 3256
    cs = dst_band.Checksum()

    dst_band = None
    dst_ds = None

    if cs == cs_expected \
       or gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON':
        drv.Delete('tmp/proximity_2.tif')

    if cs != cs_expected:
        print('Got: ', cs)
        gdaltest.post_reason('got wrong checksum')
        return 'fail'
    return 'success'
示例#5
0
文件: proximity.py 项目: ahhz/gdal
def proximity_3():

    drv = gdal.GetDriverByName('GTiff')
    src_ds = gdal.Open('data/pat.tif')
    src_band = src_ds.GetRasterBand(1)

    dst_ds = drv.Create('tmp/proximity_3.tif', 25, 25, 1, gdal.GDT_Byte)
    dst_band = dst_ds.GetRasterBand(1)

    gdal.ComputeProximity(src_band,
                          dst_band,
                          options=[
                              'VALUES=65,64', 'MAXDIST=12',
                              'USE_INPUT_NODATA=YES', 'NODATA=0'
                          ])

    cs_expected = 1465
    cs = dst_band.Checksum()

    dst_band = None
    dst_ds = None

    if cs == cs_expected \
       or gdal.GetConfigOption( 'CPL_DEBUG', 'OFF' ) != 'ON':
        drv.Delete('tmp/proximity_3.tif')

    if cs != cs_expected:
        print('Got: ', cs)
        gdaltest.post_reason('got wrong checksum')
        return 'fail'
    else:
        return 'success'
    def get_distance_raster(self,
                            base_layer,
                            output_path=None,
                            create_raster=True):
        if self.distance == 'proximity':
            with rasterio.open(base_layer) as src:
                bounds = src.bounds
                width = src.width
                height = src.height
                crs = src.crs
                transform = src.transform

            data, meta = self.rasterize(value=1,
                                        width=width,
                                        height=height,
                                        transform=transform)

            drv = gdal.GetDriverByName('MEM')
            src_ds = drv.Create('', width, height, 1,
                                gdal.GetDataTypeByName('Float32'))
            src_ds.SetGeoTransform(transform.to_gdal())
            src_ds.SetProjection(crs.wkt)
            src_ds.WriteArray(data)
            srcband = src_ds.GetRasterBand(1)

            drv = gdal.GetDriverByName('MEM')
            dst_ds = drv.Create('', width, height, 1,
                                gdal.GetDataTypeByName('Float32'))

            dst_ds.SetGeoTransform(transform.to_gdal())
            dst_ds.SetProjection(crs.wkt)

            dstband = dst_ds.GetRasterBand(1)

            gdal.ComputeProximity(srcband, dstband,
                                  ["VALUES=1", "DISTUNITS=GEO"])
            data = dstband.ReadAsArray()

            meta.update(nodata=np.nan, dtype='float32')

            if create_raster:
                self.distance_raster = RasterLayer(
                    self.category,
                    self.name + '_dist',
                    distance_limit=self.distance_limit,
                    inverse=self.inverse,
                    normalization=self.normalization)
                self.distance_raster.layer = data
                self.distance_raster.meta = meta
                self.distance_raster.bounds = bounds
                if output_path:
                    self.distance_raster.save(output_path)
            else:
                return data, meta

        elif self.distance == 'travel_time':
            self.travel_time(output_path)
示例#7
0
def calculateProximity(src_filename, dst_filename):
    src_ds = gdal.Open( src_filename)
    srcband = src_ds.GetRasterBand(1)
    target_ds = createRaster(src_filename, dst_filename,gdal.GDT_Int32  )
    dstband = target_ds.GetRasterBand(1)    
    options = []    
    options.append( 'DISTUNITS=PIXEL' )
    options.append( 'NODATA=noDataValue')
    gdal.ComputeProximity( srcband, dstband, options)
    target_ds = None
示例#8
0
def proximity_rast_ds(ds_raster_in, val=1):

    drv = gdal.GetDriverByName('MEM')
    proxy_ds = drv.Create('', ds_raster_in.RasterXSize,
                          ds_raster_in.RasterYSize, 1,
                          gdal.GetDataTypeByName('Float32'))

    gdal.ComputeProximity(ds_raster_in.GetRasterBand(1),
                          proxy_ds.GetRasterBand(1),
                          ["VALUES=" + str(val), "DISTUNITS=GEO"])

    return proxy_ds
示例#9
0
    def __getNearestNeighbors__(self):
        '''
        Find the nearest neighbors of particular component amongst other components.
        '''
        #Initialize list of vertices
        vertices = []

        mem_drv = gdal.GetDriverByName('MEM')
        for compNumber in range(1, self.nComponents + 1):
            options = []
            options.append('NODATA=0')
            options.append('VALUES=%d' % (compNumber))

            dst_ds = mem_drv.Create('', self.cc_ds.RasterXSize,
                                    self.cc_ds.RasterYSize, 1, gdal.GDT_Int16)
            dst_ds.SetGeoTransform(self.cc_ds.GetGeoTransform())
            dst_ds.SetProjection(self.cc_ds.GetProjectionRef())
            dstband = dst_ds.GetRasterBand(1)
            print('Estimating neighbors of component : %d' % (compNumber))

            gdal.ComputeProximity(self.ccband,
                                  dstband,
                                  options,
                                  callback=gdal.TermProgress)
            width = self.cc_ds.RasterXSize
            dist = dstband.ReadAsArray()

            #For each components, find the closest neighbor
            #from the other components
            ptList = []
            for comp in range(1, self.nComponents + 1):
                if comp != compNumber:
                    marr = np.ma.array(
                        dist, mask=(self.conncompAcc != comp)).argmin()
                    point = Vertex()
                    point.y, point.x = np.unravel_index(
                        marr, self.conncompAcc.shape)
                    point.compNumber = comp
                    point.source = compNumber
                    point.dist = dist[point.y, point.x]
                    ptList.append(point)

            vertices += ptList

            # Emptying dst_ds
            dst_ds = None

        # Emptying src_ds
        src_ds = None
        uniqVertices = self.__getUniqueVertices__(vertices)

        return uniqVertices
示例#10
0
    def generateMask(self):

        resol = self.resol
        pointRaster = self.pointRaster

        pointBand = pointRaster.GetRasterBand(1)
        array = pointBand.ReadAsArray()

        #plt.imshow(array)
        #plt.show()

        cols = pointRaster.RasterXSize
        rows = pointRaster.RasterYSize

        geoTrans = pointRaster.GetGeoTransform()
        geoTrans = list(geoTrans)
        x_min = geoTrans[0]
        pixelWidth = geoTrans[1]
        y_max = geoTrans[3]
        pixelHeight = geoTrans[5]

        #Generate distance layer
        #-----------------------
        driver = gdal.GetDriverByName('MEM')
        distRaster = driver.Create('memory', cols, rows, 1, gdal.GDT_UInt16)
        distRaster.SetGeoTransform(
            (x_min, pixelWidth, 0, y_max, 0, pixelHeight))
        outband = distRaster.GetRasterBand(1)
        #outband.WriteArray(boolMat)
        outRasterSRS = osr.SpatialReference()
        outRasterSRS.ImportFromEPSG(self.epsg)
        distRaster.SetProjection(outRasterSRS.ExportToWkt())
        outband.FlushCache()

        gdal.ComputeProximity(pointRaster.GetRasterBand(1), outband)

        distBand = distRaster.GetRasterBand(1)
        array = distBand.ReadAsArray()

        #plt.imshow(array)
        #plt.show()

        idDel = np.nonzero(array >= resol)
        mask = np.zeros(array.shape)
        mask[idDel] = 1

        #plt.imshow(mask)
        #plt.show()

        self.mask = mask
def distRasters(rst, outnme):
    ref = gdal.Open(rst, GA_ReadOnly)
    band = ref.GetRasterBand(1)
    proj = ref.GetProjection()
    geotransform = ref.GetGeoTransform()
    xsize = band.XSize
    ysize = band.YSize
    
    gtiff = gdal.GetDriverByName('GTiff')
    DataSet = gtiff.Create(outnme, xsize, ysize, 1, gdal.GDT_UInt16)
    DataSet.SetGeoTransform(geotransform)
    DataSet.SetProjection(proj)
    
    options = []
    
    gdal.ComputeProximity(band, DataSet.GetRasterBand(1), options, callback = None)
示例#12
0
def proximity_raster(src_raster_path: str,
                     out_raster_path: str,
                     dist_units="PIXEL",
                     preserve_nodata=True):
    """Create a proximity raster

    Args:
        src_raster_path ([type]): [description]
        out_raster_path ([type]): [description]
        dist_units (str, optional): set to "GEO" for distance in length . Defaults to "PIXEL".
    """
    log = Logger('proximity_raster')
    tmr = Timer()
    src_ds = gdal.Open(src_raster_path)
    srcband = src_ds.GetRasterBand(1)

    drv = gdal.GetDriverByName('GTiff')
    with TempRaster('vbet_proximity_raster') as tempfile:
        dst_ds = drv.Create(tempfile.filepath, 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)

        log.info('Creating proximity raster')
        gdal.ComputeProximity(
            srcband, dstband,
            ["VALUES=1", f"DISTUNITS={dist_units}", "COMPRESS=DEFLATE"])

        srcband = None
        dstband = None
        src_ds = None
        dst_ds = None

        # Preserve the nodata from the source
        if preserve_nodata:
            mask_rasters_nodata(tempfile.filepath, src_raster_path,
                                out_raster_path)
        else:
            shutil.copyfile(tempfile.filepath, out_raster_path)

        log.info('completed in {}'.format(tmr.toString()))
def createDistanceTransform(rasterSrc,
                            vectorSrc,
                            npDistFileName='',
                            units='pixels'):

    ## 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
    noDataValue = 0

    if units == 'meters':
        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()
    else:
        metersIndex = 1

    ## create First raster memory layer
    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=[255])
    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)
    options = ['NODATA=0']

    ##compute distance to non-zero pixel values and scrBand and store in proxBand
    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)
    options = ['NODATA=0', 'VALUES=0']

    ##compute distance to zero pixel values and scrBand and store in proxInBand
    gdal.ComputeProximity(srcBand, proxInBand, options)

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

    ##distance tranform is the distance to zero pixel values minus distance to non-zero pixel values
    proxTotal = proxIn.astype(float) - proxOut.astype(float)
    proxTotal = proxTotal * metersIndex

    if npDistFileName != '':
        np.save(npDistFileName, proxTotal)

    return proxTotal
def createDistanceTransformByFeatureIndex(feature_index,
                                          rasterSrc,
                                          vectorSrc,
                                          npDistFileName='',
                                          units='pixels'):
    ## open source vector file that truth data
    source_ds = ogr.Open(vectorSrc)
    source_layer = source_ds.GetLayer()

    #Define feature
    my_feature = source_layer[feature_index]

    #Spatial Reference
    srs = source_layer.GetSpatialRef()

    #Create feature Layer
    outDriver = ogr.GetDriverByName('MEMORY')
    outDataSource = outDriver.CreateDataSource('memData')
    Feature_Layer = outDataSource.CreateLayer("this_feature",
                                              srs,
                                              geom_type=ogr.wkbPolygon)

    #Add feature to layer
    Feature_Layer.CreateFeature(my_feature)

    ## 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
    noDataValue = 0
    metersIndex = 1

    ## create First raster memory layer
    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], Feature_Layer, burn_values=[255])
    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)

    options = ['NODATA=0']

    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)
    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

    if npDistFileName != '':
        np.save(npDistFileName, proxTotal)

    return proxTotal
示例#15
0
def main(argv):
    frmt = None
    creation_options = []
    options = []
    src_filename = None
    src_band_n = 1
    dst_filename = None
    dst_band_n = 1
    creation_type = 'Float32'
    quiet_flag = 0

    gdal.AllRegister()
    argv = gdal.GeneralCmdLineProcessor(argv)
    if argv is None:
        sys.exit(0)

    # Parse command line arguments.
    i = 1
    while i < len(argv):
        arg = argv[i]

        if arg == '-of' or arg == '-f':
            i = i + 1
            frmt = argv[i]

        elif arg == '-co':
            i = i + 1
            creation_options.append(argv[i])

        elif arg == '-ot':
            i = i + 1
            creation_type = argv[i]

        elif arg == '-maxdist':
            i = i + 1
            options.append('MAXDIST=' + argv[i])

        elif arg == '-values':
            i = i + 1
            options.append('VALUES=' + argv[i])

        elif arg == '-distunits':
            i = i + 1
            options.append('DISTUNITS=' + argv[i])

        elif arg == '-nodata':
            i = i + 1
            options.append('NODATA=' + argv[i])

        elif arg == '-use_input_nodata':
            i = i + 1
            options.append('USE_INPUT_NODATA=' + argv[i])

        elif arg == '-fixed-buf-val':
            i = i + 1
            options.append('FIXED_BUF_VAL=' + argv[i])

        elif arg == '-srcband':
            i = i + 1
            src_band_n = int(argv[i])

        elif arg == '-dstband':
            i = i + 1
            dst_band_n = int(argv[i])

        elif arg == '-q' or arg == '-quiet':
            quiet_flag = 1

        elif src_filename is None:
            src_filename = argv[i]

        elif dst_filename is None:
            dst_filename = argv[i]

        else:
            Usage()

        i = i + 1

    if src_filename is None or dst_filename is None:
        Usage()

    # =============================================================================
    #    Open source file
    # =============================================================================

    src_ds = gdal.Open(src_filename)

    if src_ds is None:
        print('Unable to open %s' % src_filename)
        sys.exit(1)

    srcband = src_ds.GetRasterBand(src_band_n)

    # =============================================================================
    #       Try opening the destination file as an existing file.
    # =============================================================================

    try:
        driver = gdal.IdentifyDriver(dst_filename)
        if driver is not None:
            dst_ds = gdal.Open(dst_filename, gdal.GA_Update)
            dstband = dst_ds.GetRasterBand(dst_band_n)
        else:
            dst_ds = None
    except:
        dst_ds = None

    # =============================================================================
    #     Create output file.
    # =============================================================================
    if dst_ds is None:
        if frmt is None:
            frmt = GetOutputDriverFor(dst_filename)

        drv = gdal.GetDriverByName(frmt)
        dst_ds = drv.Create(dst_filename, src_ds.RasterXSize,
                            src_ds.RasterYSize, 1,
                            gdal.GetDataTypeByName(creation_type),
                            creation_options)

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

        dstband = dst_ds.GetRasterBand(1)

    # =============================================================================
    #    Invoke algorithm.
    # =============================================================================

    if quiet_flag:
        prog_func = None
    else:
        prog_func = gdal.TermProgress_nocb

    gdal.ComputeProximity(srcband, dstband, options, callback=prog_func)

    srcband = None
    dstband = None
    src_ds = None
    dst_ds = None
示例#16
0
rasterizedDS.GetRasterBand(1).SetNoDataValue(nodata)
rasterizedDS.SetGeoTransform(transform)
rasterizedDS.SetProjection(srs.ExportToWkt())
rasterizedDS.GetRasterBand(1).Fill(nodata)
gdal.RasterizeLayer(rasterizedDS, [1], ogr_vector_layer, burn_values=[1])

# =============================================================================
# 4. compute proximity from rasterized dataset
# =============================================================================
options = []
if Max_Distance > 0:
    options.append('MAXDIST=' + str(Max_Distance))

proximityDs = driver.Create(Output, raster_width, raster_height, 1,
                            gdal.GetDataTypeByName(TYPES[Raster_Type]))
proximityDs.GetRasterBand(1).SetNoDataValue(nodata)
proximityDs.SetGeoTransform(transform)
proximityDs.SetProjection(srs.ExportToWkt())
proximityDs.GetRasterBand(1).Fill(nodata)
gdal.ComputeProximity(rasterizedDS.GetRasterBand(1),
                      proximityDs.GetRasterBand(1),
                      options,
                      callback=None)

# =============================================================================
# 5. cleanup
# =============================================================================
rasterizedDS = None
proximityDs = None
ogr_vector_datasource = None
示例#17
0
# Create an empty raster to hold the rasterized roads.
road_ds = tif_driver.Create(road_raster_fn, cols, rows)
road_ds.SetProjection(road_lyr.GetSpatialRef().ExportToWkt())
road_ds.SetGeoTransform((minx, cellsize, 0, maxy, 0, -cellsize))

# Burn the roads into the raster.
gdal.RasterizeLayer(road_ds, [1],
                    road_lyr,
                    burn_values=[1],
                    callback=gdal.TermProgress)

# Burn proximity to roads into a new raster.
prox_ds = tif_driver.Create(proximity_fn, cols, rows, 1, gdal.GDT_Int32)
prox_ds.SetProjection(road_ds.GetProjection())
prox_ds.SetGeoTransform(road_ds.GetGeoTransform())
gdal.ComputeProximity(road_ds.GetRasterBand(1), prox_ds.GetRasterBand(1),
                      ['DISTUNITS=GEO'], gdal.TermProgress)

# Burn the wilderness area into a temporary raster.
wild_ds = gdal.GetDriverByName('MEM').Create('tmp', cols, rows)
wild_ds.SetProjection(prox_ds.GetProjection())
wild_ds.SetGeoTransform(prox_ds.GetGeoTransform())
gdal.RasterizeLayer(wild_ds, [1],
                    wild_lyr,
                    burn_values=[1],
                    callback=gdal.TermProgress)

# Use the temporary wilderness raster to set the proximity one
# to NoData everywhere that is outside the wilderness area.
wild_data = wild_ds.ReadAsArray()
prox_data = prox_ds.ReadAsArray()
prox_data[wild_data == 0] = -99
示例#18
0
def gdal_proximity(
    src_filename: Optional[str] = None,
    src_band_n: int = 1,
    dst_filename: Optional[str] = None,
    dst_band_n: int = 1,
    driver_name: Optional[str] = None,
    creation_type: str = 'Float32',
    creation_options: Optional[Sequence[str]] = None,
    alg_options: Optional[Sequence[str]] = None,
    quiet: bool = False):

    # =============================================================================
    #    Open source file
    # =============================================================================
    creation_options = creation_options or []
    alg_options = alg_options or []
    src_ds = gdal.Open(src_filename)

    if src_ds is None:
        print('Unable to open %s' % src_filename)
        return 1

    srcband = src_ds.GetRasterBand(src_band_n)

    # =============================================================================
    #       Try opening the destination file as an existing file.
    # =============================================================================

    try:
        driver_name = gdal.IdentifyDriver(dst_filename)
        if driver_name is not None:
            dst_ds = gdal.Open(dst_filename, gdal.GA_Update)
            dstband = dst_ds.GetRasterBand(dst_band_n)
        else:
            dst_ds = None
    except:
        dst_ds = None

    # =============================================================================
    #     Create output file.
    # =============================================================================
    if dst_ds is None:
        if driver_name is None:
            driver_name = GetOutputDriverFor(dst_filename)

        drv = gdal.GetDriverByName(driver_name)
        dst_ds = drv.Create(dst_filename,
                            src_ds.RasterXSize, src_ds.RasterYSize, 1,
                            gdal.GetDataTypeByName(creation_type), creation_options)

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

        dstband = dst_ds.GetRasterBand(1)

    # =============================================================================
    #    Invoke algorithm.
    # =============================================================================

    if quiet:
        prog_func = None
    else:
        prog_func = gdal.TermProgress_nocb

    gdal.ComputeProximity(srcband, dstband, alg_options,
                          callback=prog_func)

    srcband = None
    dstband = None
    src_ds = None
    dst_ds = None
示例#19
0
                                             transform=out.transform)
        out.write_band(1, burned)

# Proximité (distance raster) depuis les équipements rastérisés
if not equip_zone.empty:
    src_ds = gdal.Open('structure_zone_r.tif')
    srcband = src_ds.GetRasterBand(1)
    dst_filename = 'prox_r.tif'
    drv = gdal.GetDriverByName('GTiff')
    dst_ds = drv.Create(dst_filename, 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)
    gdal.ComputeProximity(
        srcband, dstband,
        ["DISTUNITS=GEO"])  #Algo de proximité (distance géo et non en pixels)

# Note intéressante : le fichier ne s'écrit totalement QUE quand le traitement est relancé, c'est pourquoi
# Je recopie le MÊME CODE deux fois pour écrire un .tif pourri qui ne servira à rien
if not equip_zone.empty:
    src_ds = gdal.Open('structure_zone_r.tif')
    srcband = src_ds.GetRasterBand(1)
    dst_filename = 'prox_r_useless.tif'
    drv = gdal.GetDriverByName('GTiff')
    dst_ds = drv.Create(dst_filename, 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)
    gdal.ComputeProximity(
示例#20
0
def main(args):

    # --------------------------------------------------------------------------- #
    #   Parse arguments
    # --------------------------------------------------------------------------- #

    parser = argparse.ArgumentParser(prog=__program_name__, )

    # Help arguments
    parser.add_argument('--help-info',
                        dest='help_info',
                        action='store_true',
                        help='Display more detailed help information')

    # Output options
    parser.add_argument('-of',
                        '--output-format',
                        dest='driver_name',
                        type=str,
                        action='store',
                        default='GTiff',
                        metavar='driver',
                        help='Output raster driver name')
    parser.add_argument('-tr',
                        '--target-res',
                        required=True,
                        dest='target_resolution',
                        type=int,
                        nargs=2,
                        action='store',
                        metavar=('xres', 'yres'),
                        help='Target pixel resolution in georeferenced units')
    parser.add_argument(
        '-at',
        '--all-touched',
        dest='all_touched',
        action='store_true',
        default=False,
        help=
        "Rasterizes features into all touched pixels instead of just those on the line render path or whose center point is within the polygon"
    )
    parser.add_argument('-nd',
                        '--nodata',
                        dest='nodata',
                        default=0,
                        type=int,
                        action='store',
                        help='Destination nodata value')
    parser.add_argument(
        '-md',
        '--max-distance',
        dest='max_distance',
        type=int,
        action='append',
        help=
        'Maximum search distance for non-nodata pixels when computing distance'
    )
    parser.add_argument(
        '-du',
        '-dist-units',
        dest='distance_units',
        choices=('GEO', 'PIXEL'),
        default='GEO',
        type=str,
        action='store',
        help=
        'Values to write when computing distance - num pixels or georeferenced units'
    )
    parser.add_argument(
        '-fbv',
        '--fixed-buff-val',
        dest='fixed_buffer_val',
        type=int,
        action='store',
        help=
        'Write this value instead of distance for all pixels that are within the max distance'
    )
    parser.add_argument('-l',
                        '--layers',
                        dest='layers_to_process',
                        type=str,
                        nargs='+',
                        action='append',
                        help='Layers to process')
    parser.add_argument('-co',
                        '--creation-option',
                        dest='creation_options',
                        type=str,
                        default=[],
                        action='append',
                        metavar='OPTION=VAL',
                        help='Output format supported creation option')
    parser.add_argument('-ovr',
                        '--overview',
                        dest='overviews',
                        type=int,
                        nargs='+',
                        metavar='level',
                        help='Overview levels')
    parser.add_argument('-or',
                        '--ovr-resampling',
                        dest='overview_resampling',
                        choices=('nearest', 'average', 'gauss', 'cubic',
                                 'average_mp', 'average_magphase', 'mode'),
                        default='nearest',
                        help='Overview resampling method')
    parser.add_argument('--overwrite',
                        dest='overwrite_mode',
                        action='store_true',
                        default=False,
                        help='Blindly overwrite the output file if it exists')
    # Positional arguments and errors
    parser.add_argument('input_vector',
                        metavar='src_vector',
                        type=str,
                        action='store',
                        help='Vector to calculate distance against')
    parser.add_argument('output_raster',
                        metavar='dst_raster',
                        type=str,
                        action='store',
                        help='Output raster containing distance values')

    pargs = parser.parse_args(args=args)

    # --------------------------------------------------------------------------- #
    #   Adjust and validate parameters
    # --------------------------------------------------------------------------- #

    # Force cell sizes to be positive
    pargs.target_resolution = [abs(i) for i in pargs.target_resolution]

    bail = False

    # Check input vector
    try:
        ds = ogr.Open(pargs.input_vector, 0)
        if ds is None:
            del ds
            bail = True
            print("ERROR: Can't access input vector: %s" % pargs.input_vector)
    except RuntimeError:
        pass

    # Check output raster
    try:
        ds = gdal.Open(pargs.output_raster, 0)
        if ds is not None and not pargs.overwrite_mode:
            ds = None
            bail = True
            print("ERROR: Overwrite=%s and output raster exists: %s" %
                  (pargs.overwrite_mode, pargs.output_raster))
    except RuntimeError:
        pass

    if bail:
        return 1

    # --------------------------------------------------------------------------- #
    #   Prep workspace
    # --------------------------------------------------------------------------- #

    vds = ogr.Open(pargs.input_vector)

    # Get full extent of all vector layers being processed and make sure all layers are in the same spatial reference
    print("Computing input vector extent ...")
    vds_srs = None
    vds_extent = []
    for layer in vds:
        if pargs.layers_to_process is None or layer.GetName(
        ) in pargs.layers_to_process:

            # Check SRS
            if vds_srs is None:
                vds_srs = layer.GetSpatialRef()
            elif not vds_srs.IsSame(layer.GetSpatialRef()):
                vds = None
                print(
                    "ERROR: One or more input layers do not have the same SRS")
                return 1

            # Update extent
            min_x, max_x, min_y, max_y = layer.GetExtent()
            if len(vds_extent) is 0:
                vds_extent = [min_x, min_y, max_x, max_y]
            else:
                if min_x < vds_extent[0]:
                    vds_extent[0] = min_x
                if min_y < vds_extent[1]:
                    vds_extent[1] = min_y
                if max_x > vds_extent[2]:
                    vds_extent[2] = max_x
                if max_y > vds_extent[3]:
                    vds_extent[3] = max_y

    # Construct an in-memory raster that will store the rasterized vectors
    print("Building an in-memory raster for rasterization ...")
    vds_geotransform = (vds_extent[0], pargs.target_resolution[0], 0,
                        vds_extent[3], 0, -pargs.target_resolution[1])
    x_res = int((vds_extent[2] - vds_extent[0]) / pargs.target_resolution[0])
    y_res = int((vds_extent[3] - vds_extent[1]) / pargs.target_resolution[1])
    rize_ds = gdal.GetDriverByName(str('MEM')).Create(
        str('rasterization_memory_ds'), x_res, y_res, 1, gdal.GDT_Byte)
    rize_ds.SetGeoTransform(vds_geotransform)
    rize_ds.SetProjection(vds_srs.ExportToWkt())
    band = rize_ds.GetRasterBand(1)
    band.SetNoDataValue(pargs.nodata)
    band = None

    # Create output datasource
    rdriver = gdal.GetDriverByName(str(pargs.driver_name))
    if rdriver is None:
        vds = None
        rize_ds = None
        print("ERROR: Invalid driver: '%s'" % pargs.driver_name)
        return 1
    rds = rdriver.Create(str(pargs.output_raster),
                         rize_ds.RasterXSize,
                         rize_ds.RasterYSize,
                         1,
                         gdal.GDT_Float32,
                         options=pargs.creation_options)
    if rds is None:
        vds = None
        rize_ds = None
        print("ERROR: Could not create output raster: %s" %
              pargs.output_raster)
        return 1
    rdriver = None

    rds.SetGeoTransform(vds_geotransform)
    rds.SetProjection(vds_srs.ExportToWkt())

    # --------------------------------------------------------------------------- #
    #   Rasterize input layers
    # --------------------------------------------------------------------------- #

    if pargs.all_touched:
        rize_options = ['ALL_TOUCHED=TRUE']
    else:
        rize_options = []
    rize_options.append('MERGE_ALG=REPLACE')
    rize_options = [str(opt) for opt in rize_options]
    for layer in vds:
        if pargs.layers_to_process is None or layer.GetName(
        ) in pargs.layers_to_process:
            print("Rasterizing layer '%s' ..." % layer.GetName())
            gdal.RasterizeLayer(rize_ds, [1],
                                layer,
                                options=rize_options,
                                burn_values=[1],
                                callback=gdal.TermProgress)

    # --------------------------------------------------------------------------- #
    #   Compute proximity
    # --------------------------------------------------------------------------- #

    # Assemble options for proximity calculation
    proximity_options = []
    if pargs.max_distance:
        proximity_options.append('MAXDIST=%s' % pargs.max_distance)
    if pargs.distance_units:
        proximity_options.append('DISTUNITS=%s' % pargs.distance_units)
    if pargs.fixed_buffer_val:
        proximity_options.append('FIXED_BUF_VAL=%s' % pargs.fixed_buffer_val)
    proximity_options.append('VALUES=1')
    proximity_options.append('NODATA=0')
    proximity_options = [str(opt) for opt in proximity_options]

    # Compute proximity
    print("Computing proximity ...")
    output_band = rds.GetRasterBand(1)
    output_band.SetNoDataValue(pargs.nodata)
    gdal.ComputeProximity(rize_ds.GetRasterBand(1),
                          output_band,
                          options=proximity_options,
                          callback=gdal.TermProgress)

    # --------------------------------------------------------------------------- #
    #   Generate overviews
    # --------------------------------------------------------------------------- #

    if pargs.overviews:
        print("Generating overview: %s" %
              ', '.join([str(o) for o in pargs.overviews]))
        rds.BuildOverviews(resampling=str(pargs.overview_resampling),
                           overviewlist=pargs.overviews,
                           callback=gdal.TermProgress)

    # Cleanup
    band = None
    output_band = None
    vds_srs = None
    vds = None
    layer = None
    rize_ds = None
    rds = None

    return 0
示例#21
0
    target_ds.SetGeoTransform((x_min, pixel_size, 0, y_max, 0, -pixel_size))
    band = target_ds.GetRasterBand(1)
    band.SetNoDataValue(NoData_value)

    ##
    ### Rasterize
    gdal.RasterizeLayer(target_ds, [1], source_layer, burn_values=[1])
    ##
    ###Find Distance
    target2_ds = gdal.GetDriverByName('GTiff').Create(raster2_fn, x_res, y_res,
                                                      2, gdal.GDT_Int16)
    target2_ds.SetGeoTransform((x_min, pixel_size, 0, y_max, 0, -pixel_size))
    ##
    srcband = target_ds.GetRasterBand(1)
    dstband = target2_ds.GetRasterBand(1)
    gdal.ComputeProximity(srcband, dstband)
    ##
    ###Convert to Array
    myarray = np.array(target2_ds.GetRasterBand(1).ReadAsArray())

    newarray = 500 - myarray

    outputar = np.where(newarray < 0, 0, newarray)

    arraylist.append(outputar[:])
    print np.max(outputar)

    outBand = target2_ds.GetRasterBand(2)
    outBand.WriteArray(outputar)

totalarray = arraylist[0] * 0
示例#22
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsVectorLayer(parameters, self.INPUT, context)
        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))

        max_distance = self.parameterAsDouble(parameters, self.MAX_DISTANCE,
                                              context)
        raster_type = self.RASTER_TYPES[self.parameterAsEnum(
            parameters, self.RASTER_TYPE, context)]

        extent = self.parameterAsExtent(parameters, self.EXTENT, context,
                                        source.sourceCrs())
        if extent is None or extent.width() == 0 or extent.height() == 0:
            extent = source.sourceExtent()

        cell_size = self.parameterAsDouble(parameters, self.CELL_SIZE, context)
        if cell_size <= 0:
            cell_size = int(min(extent.width(), extent.height()) / 250.0)

        output_raster = self.parameterAsOutputLayer(parameters, self.OUTPUT,
                                                    context)

        # open ogr vector layer from qgs map layer
        ogrLayer, layerName = self.getOgrCompatibleSource(
            self.INPUT, parameters, context, feedback, True)
        if ogrLayer is None:
            raise QgsProcessingException('Cannot connect OGR driver!')

        ogr_vector_datasource = ogr.Open(ogrLayer)
        ogr_vector_layer = ogr_vector_datasource.GetLayer(layerName)

        feedback.pushInfo('Raster Type = {0}'.format(raster_type))
        feedback.pushInfo('Cell Size = {0}'.format(cell_size))
        feedback.pushInfo('Extent = {0}'.format(extent))

        nodata = -9999
        srs = osr.SpatialReference()
        srs.ImportFromWkt(source.crs().toWkt())
        transform = [
            extent.xMinimum(), cell_size, 0.0,
            extent.yMaximum(), 0.0, -cell_size
        ]
        raster_width = int(
            math.ceil(abs(extent.xMaximum() - extent.xMinimum()) / cell_size))
        raster_height = int(
            math.ceil(abs(extent.yMaximum() - extent.yMinimum()) / cell_size))

        # rasterize temporary raterdataset from vector layer, extent, cellsize
        temporary_path = os.path.join(
            QgsProcessingUtils.tempFolder(),
            'euc_distance_{}.tif'.format(uuid.uuid4().hex))
        feedback.pushInfo('Temporary path = {0}'.format(temporary_path))

        driver = gdal.GetDriverByName('GTiff')
        rasterizedDS = driver.Create(temporary_path, raster_width,
                                     raster_height, 1, gdal.GDT_Byte)
        rasterizedDS.GetRasterBand(1).SetNoDataValue(nodata)
        rasterizedDS.SetGeoTransform(transform)
        rasterizedDS.SetProjection(srs.ExportToWkt())
        rasterizedDS.GetRasterBand(1).Fill(nodata)
        gdal.RasterizeLayer(rasterizedDS, [1],
                            ogr_vector_layer,
                            burn_values=[1])

        # compute proximity from rasterized dataset
        options = ['DISTUNITS=GEO']
        if max_distance > 0:
            options.append('MAXDIST=' + str(max_distance))

        proximityDs = driver.Create(output_raster, raster_width, raster_height,
                                    1, gdal.GetDataTypeByName(raster_type))
        proximityDs.GetRasterBand(1).SetNoDataValue(nodata)
        proximityDs.SetGeoTransform(transform)
        proximityDs.SetProjection(srs.ExportToWkt())
        proximityDs.GetRasterBand(1).Fill(nodata)
        gdal.ComputeProximity(rasterizedDS.GetRasterBand(1),
                              proximityDs.GetRasterBand(1),
                              options,
                              callback=None)

        # cleanup
        rasterizedDS = None
        proximityDs = None
        ogr_vector_datasource = None

        return {self.OUTPUT: output_raster}
示例#23
0
def calc_proximity(
    input_rasters,
    target_value=1,
    out_path=None,
    max_dist=1000,
    add_border=False,
    weighted=False,
    invert=False,
    return_array=False,
    postfix="_proximity",
    uuid=False,
    overwrite=True,
    skip_existing=False,
):
    """
    Calculate the proximity of input_raster to values
    """
    raster_list, path_list = ready_io_raster(input_rasters,
                                             out_path,
                                             overwrite,
                                             postfix=postfix,
                                             uuid=uuid)

    output = []
    for index, input_raster in enumerate(raster_list):
        out_path = path_list[index]

        if skip_existing and os.path.exists(out_path):
            output.append(out_path)
            continue

        in_arr = raster_to_array(input_raster, filled=True)
        bin_arr = (in_arr != target_value).astype("uint8")
        bin_raster = array_to_raster(bin_arr, reference=input_raster)

        in_raster = open_raster(bin_raster)
        in_raster_path = bin_raster

        if add_border:
            border_size = 1
            border_raster = add_border_to_raster(
                in_raster,
                border_size=border_size,
                border_value=0,
                overwrite=True,
            )

            in_raster = open_raster(border_raster)

            gdal.Unlink(in_raster_path)
            in_raster_path = border_raster

        src_band = in_raster.GetRasterBand(1)

        driver_name = "GTiff" if out_path is None else path_to_driver_raster(
            out_path)
        if driver_name is None:
            raise ValueError(f"Unable to parse filetype from path: {out_path}")

        driver = gdal.GetDriverByName(driver_name)
        if driver is None:
            raise ValueError(
                f"Error while creating driver from extension: {out_path}")

        mem_path = f"/vsimem/raster_proximity_tmp_{uuid4().int}.tif"

        dest_raster = driver.Create(
            mem_path,
            in_raster.RasterXSize,
            in_raster.RasterYSize,
            1,
            gdal.GetDataTypeByName("Float32"),
        )

        dest_raster.SetGeoTransform(in_raster.GetGeoTransform())
        dest_raster.SetProjection(in_raster.GetProjectionRef())
        dst_band = dest_raster.GetRasterBand(1)

        gdal.ComputeProximity(
            src_band,
            dst_band,
            [
                f"VALUES='1'",
                "DISTUNITS=GEO",
                f"MAXDIST={max_dist}",
            ],
        )

        dst_arr = dst_band.ReadAsArray()
        gdal.Unlink(mem_path)
        gdal.Unlink(in_raster_path)

        dst_arr = np.where(dst_arr > max_dist, max_dist, dst_arr)

        if invert:
            dst_arr = max_dist - dst_arr

        if weighted:
            dst_arr = dst_arr / max_dist

        if add_border:
            dst_arr = dst_arr[border_size:-border_size,
                              border_size:-border_size]

        src_band = None
        dst_band = None
        in_raster = None
        dest_raster = None

        if return_array:
            output.append(dst_arr)
        else:
            array_to_raster(dst_arr, reference=input_raster, out_path=out_path)
            output.append(out_path)

        dst_arr = None

    if isinstance(input_rasters, list):
        return output

    return output[0]
示例#24
0
def create_dist_map(rasterSrc, vectorSrc, npDistFileName='',
                           noDataValue=0, burn_values=255,
                           dist_mult=1, vmax_dist=64):

    source_ds = ogr.Open(vectorSrc)
    source_layer = source_ds.GetLayer()

    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]

    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

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

    if npDistFileName != '':
        np.save(npDistFileName, proxTotal)
示例#25
0
            # Create temporal raster
            rasterize_options = gdal.RasterizeOptions(
                xRes=xres, yRes=yres, allTouched=True, burnValues=[1]
            )
            temp1 = gdal.Rasterize(
                "/vsimem/temp", feature.get("path"), options=rasterize_options
            )
            temp1_band = temp1.GetRasterBand(1)

            # Create temporal proximity raster
            driver = gdal.GetDriverByName("MEM")
            temp2 = driver.Create("temp2", temp1.RasterXSize, temp1.RasterYSize)
            temp2.SetGeoTransform(temp1.GetGeoTransform())
            temp2.SetProjection(temp1.GetProjection())
            temp2_band = temp2.GetRasterBand(1)
            gdal.ComputeProximity(temp1_band, temp2_band, ["VALUES=1"])
            temp2_band.FlushCache()

            # Clip to region area
            warp_options = gdal.WarpOptions(
                outputBounds=match_ds.rio.bounds(),
                creationOptions=["COMPRESS=LZW"],
                outputType=gdal.GDT_Int16,
                dstNodata=NODATA_VALUE,
                cutlineDSName=region.get("path"),
            )
            dst_fn = os.path.join(output_folder, f"{feature.get('name')}_proximity.tif")
            temp3 = gdal.Warp(dst_fn, temp2, options=warp_options)
            stack.append(temp3.ReadAsArray())

        stack = np.stack(stack)
示例#26
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
示例#27
0
# =============================================================================
if dst_ds is None:
    if format is None:
        format = GetOutputDriverFor(dst_filename)

    drv = gdal.GetDriverByName(format)
    dst_ds = drv.Create(dst_filename, src_ds.RasterXSize, src_ds.RasterYSize,
                        1, gdal.GetDataTypeByName(creation_type),
                        creation_options)

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

    dstband = dst_ds.GetRasterBand(1)

# =============================================================================
#    Invoke algorithm.
# =============================================================================

if quiet_flag:
    prog_func = None
else:
    prog_func = gdal.TermProgress_nocb

gdal.ComputeProximity(srcband, dstband, options, callback=prog_func)

srcband = None
dstband = None
src_ds = None
dst_ds = None
示例#28
0
def proximity_shp(fn_shp, raster_ref, type_prox='both'):

    # create memory raster based on reference raster
    raster_ds = create_mem_raster_on_ref(raster_ref)
    # open .shp with GDAL
    shp_ds = gdal.OpenEx(fn_shp, gdal.OF_VECTOR)
    # rasterize
    opts = gdal.RasterizeOptions(burnValues=[1], bands=[1])
    gdal.Rasterize(raster_ds, shp_ds, options=opts)
    # close shp
    shp_ds = None

    drv = gdal.GetDriverByName('MEM')
    proxy_ds = drv.Create('', raster_ds.RasterXSize, raster_ds.RasterYSize, 1,
                          gdal.GetDataTypeByName('Float32'))

    if type_prox == 'exterior':

        gdal.ComputeProximity(raster_ds.GetRasterBand(1),
                              proxy_ds.GetRasterBand(1),
                              ["VALUES=1", "DISTUNITS=GEO"])

        proxy_array = proxy_ds.GetRasterBand(1).ReadAsArray()

    elif type_prox == 'interior':

        raster_arr = raster_ds.GetRasterBand(1).ReadAsArray()
        mask = (raster_arr == 1)
        raster_arr[mask] = raster_ds.GetRasterBand(1).GetNoDataValue()
        raster_arr[~mask] = 1
        raster_ds.GetRasterBand(1).WriteArray(raster_arr)

        gdal.ComputeProximity(raster_ds.GetRasterBand(1),
                              proxy_ds.GetRasterBand(1),
                              ["VALUES=1", "DISTUNITS=GEO"])

        proxy_array = proxy_ds.GetRasterBand(1).ReadAsArray()

    elif type_prox == 'both':

        gdal.ComputeProximity(raster_ds.GetRasterBand(1),
                              proxy_ds.GetRasterBand(1),
                              ["VALUES=1", "DISTUNITS=GEO"])

        proxy_ext = proxy_ds.GetRasterBand(1).ReadAsArray()

        raster_arr = raster_ds.GetRasterBand(1).ReadAsArray()
        mask = (raster_arr == 1)
        raster_arr[mask] = raster_ds.GetRasterBand(1).GetNoDataValue()
        raster_arr[~mask] = 1
        raster_ds.GetRasterBand(1).WriteArray(raster_arr)

        gdal.ComputeProximity(raster_ds.GetRasterBand(1),
                              proxy_ds.GetRasterBand(1),
                              ["VALUES=1", "DISTUNITS=GEO"])

        proxy_int = proxy_ds.GetRasterBand(1).ReadAsArray()

        proxy_array = proxy_ext + proxy_int

    else:
        sys.exit('Type of proximity:' + type_prox +
                 ' not recognized. Must be "interior", "exterior" or "both".')

    return proxy_array
示例#29
0
    def __call__(self, maxdepth, pickle_name=None):
        """
        Traverse the landcover array.  For every point of type
        'water', calculate the distance to the nearest non-water
        point, stopping at maxdepth.

        Keyword arguments:
        maxdepth -- maximum value for depth

        """

        if self.canCL and self.wantCL:
            # Create working array
            xlen, ylen = self.lcarray.shape
            workingarr = np.array(self.lcarray.ravel(), dtype=np.int32)
            # These values do not change from run to run.
            ylen_arg = np.uint32(ylen)
            maxdepth_arg = np.uint32(maxdepth)
            # Calculate how many base elements can be evaluated per run.
            # Each run requires xlen, ylen, currdepth, and maxdepth -- all 32bit.
            static_data = 4 * 4
            # Each base element requires two 32bit integers.
            bytes_per_elem_single = 2 * 4
            bytes_per_elem_total = bytes_per_elem_single
            # Use rows instead of elems for two-dimensional arrays.
            bytes_per_row_single = bytes_per_elem_single * ylen
            bytes_per_row_total = bytes_per_elem_total * ylen
            # Check both single and total limits on rows-per-slice.
            rps_single = [
                int(0.95 * device.max_mem_alloc_size / bytes_per_row_single)
                for device in self.devices
            ]
            rps_total = [
                int((0.95 * device.global_mem_size - static_data) /
                    bytes_per_row_total) for device in self.devices
            ]
            row_limits = [
                min(rps_single[x], rps_total[x])
                for x in xrange(len(self.devices))
            ]
            # NB: Only supporting one device for now.
            best_device = np.argmax(row_limits)
            best_rows = row_limits[best_device]
            global_size = self.global_size[self.devices[best_device]]
            local_size = self.local_size[self.devices[best_device]]
            # For now, at least, do not create retval or chunk buffer here.
            # Iterate through this entire mess once per depth level
            row_list = np.array([x for x in xrange(xlen)])
            negfound = False
            for row_chunk in chunks(row_list, best_rows):
                # Do not prepend buffer rows for first row.
                realfirst = row_chunk[0]
                if (row_chunk[0] != row_list[0]):
                    realfirst -= maxdepth
                # Do not postpend buffer rows for last row.
                reallast = row_chunk[-1]
                if (row_chunk[-1] != row_list[-1]):
                    reallast += maxdepth
                # Create retvals and chunk buffer here instead of above.
                chunk = np.copy(workingarr[realfirst * ylen:reallast * ylen])
                outchunk_buf = cla.empty(self.queue, chunk.shape, chunk.dtype)
                inchunk_buf = cla.to_device(self.queue, chunk)
                newxlen = reallast - realfirst
                newxlen_arg = np.uint32(newxlen)
                lenchunk = newxlen * ylen
                lenchunk_arg = np.uint32(lenchunk)
                currdepth = 0
                while (currdepth <= maxdepth):
                    currdepth_arg = np.uint32(currdepth)
                    if (currdepth % 2 == 0):
                        event = self.program.bathy(self.queue, global_size,
                                                   local_size,
                                                   outchunk_buf.data,
                                                   inchunk_buf.data,
                                                   newxlen_arg, ylen_arg,
                                                   currdepth_arg, maxdepth_arg)
                    else:
                        event = self.program.bathy(self.queue, global_size,
                                                   local_size,
                                                   inchunk_buf.data,
                                                   outchunk_buf.data,
                                                   newxlen_arg, ylen_arg,
                                                   currdepth_arg, maxdepth_arg)
                    event.wait()
                    currdepth += 1
                # Copy relevant part of outchunk_buf to workingarr.
                chunk_arr = outchunk_buf.get()
                copytop = 0
                if (row_chunk[0] != row_list[0]):
                    copytop += maxdepth
                copybot = len(row_chunk) - 1
                workingarr[row_chunk[0] * ylen:row_chunk[-1] *
                           ylen] = chunk_arr[copytop * ylen:copybot * ylen]
            results = workingarr.reshape(
                (self.lcarray.shape))[maxdepth:-1 * maxdepth,
                                      maxdepth:-1 * maxdepth]
        else:
            (depthz, depthx) = self.lcarray.shape
            drv = gdal.GetDriverByName('MEM')
            depthds = drv.Create('', depthx, depthz, 1,
                                 gdal.GetDataTypeByName('Byte'))
            depthds.SetGeoTransform(self.geotrans)
            depthds.SetProjection(self.projection)
            depthband = depthds.GetRasterBand(1)
            depthband.WriteArray(self.lcarray)
            # create a duplicate dataset called bathyds
            bathyds = drv.Create('', depthx, depthz, 1,
                                 gdal.GetDataTypeByName('Byte'))
            bathyds.SetGeoTransform(self.geotrans)
            bathyds.SetProjection(self.projection)
            bathyband = bathyds.GetRasterBand(1)
            # run compute proximity
            values = ','.join([str(x) for x in xrange(256) if x is not 11])
            options = [
                'MAXDIST=%d' % maxdepth,
                'NODATA=%d' % maxdepth,
                'VALUES=%s' % values
            ]
            gdal.ComputeProximity(depthband, bathyband, options)
            # extract array
            results = bathyband.ReadAsArray(maxdepth, maxdepth,
                                            bathyds.RasterXSize - 2 * maxdepth,
                                            bathyds.RasterYSize - 2 * maxdepth)

        if pickle_name is not None:
            # Pickle variables for testing purposes.
            picklefilename = 'bathy-%s.pkl.gz' % pickle_name
            print 'Pickling to %s...' % picklefilename
            f = gzip.open(picklefilename, 'wb')
            pickle.dump(self.lcarray, f, -1)
            pickle.dump(self.geotrans, f, -1)
            pickle.dump(self.projection, f, -1)
            pickle.dump(maxdepth, f, -1)
            # pickle.dump(results, f, -1)
        return results
示例#30
0
def calcDist2ImgVals(inputValsImg,
                     outputDistImg,
                     pxlVals,
                     valsImgBand=1,
                     gdalformat='KEA',
                     maxDist=None,
                     noDataVal=None,
                     unitGEO=True):
    """ 
A function to calculate the distance to the nearest pixel value with one of the specified values.

Where:

:param inputValsImg: is a string specifying the input image file.
:param outputDistImg: is a string specfiying the output image file.
:param pxlVals: is a number of list of numbers specifying the features to which the distance from should be calculated.
:param valsImgBand: is an integer specifying the image band of the input image to be used (Default = 1).
:param gdalformat: is a string specifying the output image format (Default = KEA)
:param maxDist: is a number specifying the maximum distance to be calculated, if None not max value is used (Default = None).
:param noDataVal: is the no data value in the input image for which distance should not be calculated for (Default = None; None = no specified no data value).
:param unitGEO: is a boolean specifying the output distance units. True = Geographic units (e.g., metres), False is in Pixels (Default = True).

Example::

    import rsgislib.imagecalc
    cloudsImg = 'LS5TM_20110701_lat52lon421_r24p204_clouds.kea'
    dist2Clouds = 'LS5TM_20110701_lat52lon421_r24p204_distclouds.kea'
    # Pixel value 1 == Clouds
    # Pixel value 2 == Cloud Shadows
    rsgislib.imagecalc.calcDist2ImgVals(cloudsImg, dist2Clouds, pxlVals=[1,2])
    
"""
    # Check gdal is available
    if not haveGDALPy:
        raise ImportError("The GDAL python bindings are required for "
                          "calcDist2ImgVals function could not be imported")
    import rsgislib.imageutils

    haveListVals = False
    if type(pxlVals) is list:
        haveListVals = True

    proxOptions = []

    if maxDist is not None:
        proxOptions.append('MAXDIST=' + str(maxDist))
    if noDataVal is not None:
        proxOptions.append('NODATA=' + str(noDataVal))
    if unitGEO:
        proxOptions.append('DISTUNITS=GEO')
    else:
        proxOptions.append('DISTUNITS=PIXEL')

    if haveListVals:
        strVals = ''
        first = True
        for val in pxlVals:
            if first:
                strVals = str(val)
                first = False
            else:
                strVals = strVals + "," + str(val)
        proxOptions.append('VALUES=' + strVals)
    else:
        proxOptions.append('VALUES=' + str(pxlVals))

    valsImgDS = gdal.Open(inputValsImg, gdal.GA_ReadOnly)
    valsImgBand = valsImgDS.GetRasterBand(valsImgBand)
    rsgislib.imageutils.createCopyImage(inputValsImg, outputDistImg, 1, 0.0,
                                        gdalformat, rsgislib.TYPE_32FLOAT)
    distImgDS = gdal.Open(outputDistImg, gdal.GA_Update)
    distImgBand = distImgDS.GetRasterBand(1)
    gdal.ComputeProximity(valsImgBand,
                          distImgBand,
                          proxOptions,
                          callback=gdal.TermProgress)
    distImgBand = None
    distImgDS = None
    classImgBand = None
    classImgDS = None