Пример #1
0
def enmascarar_entrenamiento(vector_data_path,
                             cols,
                             rows,
                             geo_transform,
                             projection,
                             target_value=1):
    data_source = gdal.OpenEx(vector_data_path, gdal.OF_VECTOR)
    layer = data_source.GetLayer(0)
    driver = gdal.GetDriverByName('MEM')
    target_ds = driver.Create('', cols, rows, 1, gdal.GDT_UInt16)
    target_ds.SetGeoTransform(geo_transform)
    target_ds.SetProjection(projection)
    gdal.RasterizeLayer(target_ds, [1], layer, burn_values=[target_value])
    return target_ds
Пример #2
0
def basin_rasterize(geoj_path,
                    raster_path,
                    result_path,
                    value,
                    no_data,
                    shp_ex=0):
    print("GeoJson to GeoJSON")
    current_path = os.path.abspath(os.path.dirname(__file__))
    temp_folder = current_path + '/temp'
    if not os.path.exists(temp_folder):
        os.makedirs(temp_folder)
    shp_path = temp_folder + '/temp.shp'
    cu.geojson_to_shp(geoj_path, shp_path)

    print("Shapefile Rasterize.")

    ra_ds = gdal.Open(raster_path)
    shp = ogr.Open(shp_path, 0)
    shp_layer = shp.GetLayerByIndex(0)

    file_format = "GTiff"
    driver = gdal.GetDriverByName(file_format)
    full_geo_transform = ra_ds.GetGeoTransform()
    raster_x_size = ra_ds.RasterXSize
    raster_y_size = ra_ds.RasterYSize

    if shp_ex:
        # 得到范围分别为:left right bottom top
        shp_extent = shp_layer.GetExtent()
        full_geo_transform, raster_x_size, raster_y_size = shp_geo_transform(
            [full_geo_transform[0], full_geo_transform[3]],
            full_geo_transform[1], shp_extent)

    re_ds = driver.Create(result_path,
                          raster_x_size,
                          raster_y_size,
                          1,
                          gdal.GDT_Float32,
                          options=['COMPRESS=DEFLATE'])
    re_ds.SetGeoTransform(full_geo_transform)
    re_ds.SetProjection(ra_ds.GetProjection())
    re_ds.GetRasterBand(1).SetNoDataValue(float(no_data))

    # gdal.RasterizeLayer(re_ds, [1], shp_layer, options=["ATTRIBUTE=value"])
    gdal.RasterizeLayer(re_ds, [1], shp_layer, burn_values=[float(value)])

    ra_ds = None
    re_ds = None
    shp.Release()
    shutil.rmtree(temp_folder)
Пример #3
0
    def Rasterize(self, outputname, Nodata=0):

        targetDataSet = gdal.GetDriverByName('GTiff').Create(
            outputname, self.width, self.height, 1, gdal.GDT_Byte)
        targetDataSet.SetGeoTransform(self.geotransform)
        targetDataSet.SetProjection(self.projection)
        band = targetDataSet.GetRasterBand(1)
        band.SetNoDataValue(Nodata)
        band.FlushCache()
        gdal.RasterizeLayer(
            targetDataSet,
            [1],
            self.defaultlayer,
        )
        targetDataSet = None
Пример #4
0
def create_mask_from_vector(vector_data_path,
                            cols,
                            rows,
                            geo_transform,
                            projection,
                            target_value=1):
    """Rasterize the given vector (wrapper for gdal.RasterizeLayer)."""
    data_source = gdal.OpenEx(vector_data_path, gdal.OF_VECTOR)
    layer = data_source.GetLayer(0)
    driver = gdal.GetDriverByName('MEM')  # In memory dataset
    target_ds = driver.Create('', cols, rows, 1, gdal.GDT_UInt16)
    target_ds.SetGeoTransform(geo_transform)
    target_ds.SetProjection(projection)
    gdal.RasterizeLayer(target_ds, [1], layer, burn_values=[target_value])
    return target_ds
Пример #5
0
    def getInnerGeometry(self, geometry):
        #Compute pixels to take from image with geometry bbox
        minX, minY, maxX, maxY = getGeometryBbox(geometry)
        xoff = int((minX - self.xOrigin) / self.pixelWidth)
        yoff = int((self.yOrigin - maxY) / self.pixelWidth)
        xcount = int((maxX - minX) / self.pixelWidth) + 1
        ycount = int((maxY - minY) / self.pixelWidth) + 1

        # Create memory target raster to store result
        memRaster = gdal.GetDriverByName('MEM').Create('', xcount, ycount, 1,
                                                       gdal.GDT_Byte)
        memRaster.SetGeoTransform((
            minX,
            self.pixelWidth,
            0,
            maxY,
            0,
            self.pixelHeight,
        ))
        rasterSR = osr.SpatialReference()
        rasterSR.ImportFromWkt(self.gtif.GetProjectionRef())
        memRaster.SetProjection(rasterSR.ExportToWkt())

        # create temporary file to get layer from geometry
        outDriver = ogr.GetDriverByName("ESRI Shapefile")
        outDataSource = outDriver.CreateDataSource("tmp.shp")
        outLayer = outDataSource.CreateLayer(
            "./", geom_type=geometry.GetGeometryType())
        featureDefn = outLayer.GetLayerDefn()
        feature = ogr.Feature(featureDefn)
        feature.SetGeometry(geometry)
        outLayer.CreateFeature(feature)

        # create mask from layer
        gdal.RasterizeLayer(memRaster, [1], outLayer, burn_values=[1])
        band = self.gtif.GetRasterBand(1)
        dataRaster = band.ReadAsArray(xoff, yoff, xcount,
                                      ycount).astype(np.float)
        bandMask = memRaster.GetRasterBand(1)
        dataMask = bandMask.ReadAsArray(0, 0, xcount, ycount).astype(np.float)

        # Mask zone of raster
        zoneraster = np.ma.masked_array(dataRaster, np.logical_not(dataMask))

        # Delete temporary file
        outDriver.DeleteDataSource("tmp.shp")

        return zoneraster
Пример #6
0
def rasterize_polygons(polygons,
                       image_path,
                       class_name,
                       shapefile_path,
                       driver=gdal.GetDriverByName("MEM")):
    """
    Retuns a data set image with the bounding box dimensions and the polygon locations marked by 1.
    :param polygons: A list of polygons of the same class
    :param image_path The path to the image
    :return: Data set image
    """
    # Get meta data from the image
    image_ds = gdal.Open(image_path)
    geo_transform = image_ds.GetGeoTransform()
    projection = image_ds.GetProjection()
    n_pixels_north = image_ds.RasterYSize
    n_pixels_east = image_ds.RasterXSize
    image_ds = None
    # Create empty image
    output_path = image_path.replace(".tif", "")
    output_path += f"_temp_label_{class_name}.tif"
    label_raster = driver.Create(output_path, n_pixels_east, n_pixels_north, 1,
                                 gdal.GDT_Int16)
    label_raster.SetGeoTransform(geo_transform)
    label_raster.SetProjection(projection)

    # set up the shapefile driver
    shapefile_driver = ogr.GetDriverByName("Memory")
    # create the data source
    poly_ds = shapefile_driver.CreateDataSource(shapefile_path)
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(25833)
    layer = poly_ds.CreateLayer(
        os.path.split(shapefile_path.replace(".shp", ""))[-1], srs,
        ogr.wkbPolygon)
    # Add the polygons to the new layer
    for poly in polygons:
        feature = ogr.Feature(layer.GetLayerDefn())
        feature.SetGeometry(poly)
        layer.CreateFeature(feature)
        feature.Destroy()

    # Burn the polygons into the new image
    gdal.RasterizeLayer(label_raster, (1, ), layer, burn_values=(1, ))
    poly_ds.Destroy()

    # Save and close the image
    return label_raster
def rasterize(InputVector, OutputImage, RefImage):
    print('Rasterizing shapefile...')
    gdalformat = 'GTiff'
    datatype = gdal.GDT_Byte
    burnVal = 1  #value for the output image pixels

    # Get projection info from reference image
    Image = gdal.Open(RefImage, gdal.GA_ReadOnly)

    # Open Shapefile
    Shapefile = ogr.Open(InputVector)
    Shapefile_layer = Shapefile.GetLayer()

    # Chceck if raster exists. If yes, delete.
    if os.path.exists(OutputImage):
        print('Raster exists, deleting')
        os.remove(OutputImage)

    # Rasterise
    Output = gdal.GetDriverByName(gdalformat).Create(
        OutputImage,
        Image.RasterXSize,
        Image.RasterYSize,
        1,
        datatype,
        options=['COMPRESS=DEFLATE'])
    print('New raster created')
    Output.SetProjection(Image.GetProjectionRef())
    Output.SetGeoTransform(Image.GetGeoTransform())

    # Write data to band 1
    Band = Output.GetRasterBand(1)
    Band.SetNoDataValue(255)
    gdal.RasterizeLayer(Output, [1], Shapefile_layer, burn_values=[burnVal])

    # Close datasets
    Band = None
    Output = None
    Image = None
    Shapefile = None

    # Build image overviews
    subprocess.call("gdaladdo --config COMPRESS_OVERVIEW DEFLATE " +
                    OutputImage + " 2 4 8 16 32 64",
                    shell=True)
    print("Rasterized.")
def createROIImage(index, path):
    # 1) opening the shapefile
    # First we will open our raster image, to understand how we will want to rasterize our vector
    raster_ds = gdal.Open(path+index+'.tif', gdal.GA_ReadOnly)

    # Fetch projection and extent
    proj = raster_ds.GetProjectionRef()
    ext = raster_ds.GetGeoTransform()
    source_ds = ogr.Open('trainingData/21LYH2018_trainingData.shp')
    source_layer = source_ds.GetLayer()

    # 2) Creating the destination raster data source

    target_ds = gdal.GetDriverByName('GTiff').Create(
        path + 'training_data'+index+'.gtif', 3660, 3660, 1,
        gdal.GDT_Float32)  ##COMMENT 2

    target_ds.SetGeoTransform(ext)  # COMMENT 3
    target_ds.SetProjection(proj)

    band = target_ds.GetRasterBand(1)
    band.SetNoDataValue(-9999)  ##COMMENT 5

    status = gdal.RasterizeLayer(target_ds, [1], source_layer,
                                 options=['ALL_TOUCHED=TRUE',  # rasterize all pixels touched by polygons
                                          'ATTRIBUTE=id'])  ##COMMENT 6
    #out_img, out_transform = mask(status, shapes=bbox, crop=True) #How to cut the rasterlayer?

    target_ds = None  ##COMMENT 7

    if status != 0:
        print("I don't think it worked...")
    else:
        print("Success")

    roi_ds = gdal.Open(path + 'training_data'+index+'.gtif', gdal.GA_ReadOnly)
    roi = roi_ds.GetRasterBand(1).ReadAsArray()

    # How many pixels are in each class?
    classes = np.unique(roi)
    classes = classes
    # Iterate over all class labels in the ROI image, printing out some information
    for c in classes:
        print('Class {c} contains {n} pixels'.format(c=c,
                                                     n=(roi == c).sum()))
Пример #9
0
def rasterize(gdb_dir, resolution, raster_fn):
    '''Rasterize the groads database.'''

    # Define pixel_size and NoData value of new raster
    x_res = y_res = resolution
    nodata = -9999

    # Open the data source and read in the extent
    gdb = open_db(gdb_dir)
    source_layer = gdb.GetLayer()
    source_srs = source_layer.GetSpatialRef()
    x_min, x_max, y_min, y_max = source_layer.GetExtent()

    # Round bounds to a multiple of the resolution
    # FIXME: shoud I use round or ceil?
    x_min = round(x_min / x_res) * x_res
    x_max = round(x_max / x_res) * x_res
    y_min = round(y_min / y_res) * y_res
    y_max = round(y_max / y_res) * y_res

    # Create the destination data source
    x_size = int(round((x_max - x_min) / x_res))
    y_size = int(round((y_max - y_min) / y_res))
    target_ds = gdal.GetDriverByName('GTiff').Create(
        raster_fn,
        x_size,
        y_size,
        2,  # self + prox
        gdal.GDT_Float32,
        ['COMPRESS=lzw', 'PREDICTOR=2'])
    target_ds.SetGeoTransform((x_min, x_res, 0, y_max, 0, -y_res))
    target_ds.GetRasterBand(2).SetNoDataValue(nodata)
    if source_srs:
        target_ds.SetProjection(source_layer.GetSpatialRef().ExportToWkt())

    target_ds.GetRasterBand(2).Fill(-9999)

    # Rasterize (store rasterized data in band 2)
    err = gdal.RasterizeLayer(target_ds, [2],
                              source_layer,
                              burn_values=[1],
                              options=['ALL_TOUCHED=TRUE'])

    if err != 0:
        raise RuntimeError('error rasterizing layer: %s' % err)
Пример #10
0
def rasterize_shp(shp, output ,x_min, y_min , x_size, y_size, x_res, y_res):
    # tif = 'D:\\MODIS\\data_tif\\MOD11A2.006\\2003.01.09.LST_Day_1km.tif'
    # shp = 'D:\\MODIS\\shp\\china_dissolve.shp'
    # output = 'D:\\MODIS\\my.tif'
    # x_min, y_min, x_size, y_size, x_res, y_res = -179.875, -89.875, 1440, 720, 0.25, 0.25
    mb_v = ogr.Open(shp)
    mb_l = mb_v.GetLayer()

    target_ds = gdal.GetDriverByName('GTiff').Create(output, x_size, y_size, 1, gdal.GDT_Byte)
    target_ds.SetGeoTransform((x_min, x_res, 0, y_min, 0, y_res))
    band = target_ds.GetRasterBand(1)
    NoData_value = -999999
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(target_ds, [1], mb_l)
    # gdal.RasterizeLayer(target_ds, [1], mb_l, options=["ATTRIBUTE=hedgerow"])

    target_ds = None
Пример #11
0
def burn_without_add(in_raster, in_shape):
        '''
        Burn the values of a shapefile into a base raster. Replaces the values of the pixel in the raster rather then
        adding to them.
        :param in_raster: The path to the input raster.
        :param in_shape: The path to the shapefile with the geometries you care about.
        :return: Doesn't return anything.
        '''
        shape_source = ogr.Open(in_shape)
        layer = shape_source.GetLayer()

        raster_source = gdal.Open(in_raster, GA_Update)

        gdal.RasterizeLayer(raster_source, [1], layer, burn_values=[1], options=['ALL_TOUCHED=TRUE'])

        shape_source = None
        raster_source = None
        return
def vector2raster(vectorfn, rasterfn, newRasterfn):
    source_ds = ogr.Open(vectorfn)
    source_layer = source_ds.GetLayer()
    raster = gdal.Open(rasterfn)
    geotransform = raster.GetGeoTransform()
    originX = geotransform[0]
    originY = geotransform[3]
    pixelWidth = geotransform[1]
    pixelHeight = geotransform[5]
    band = raster.GetRasterBand(1)
    array = band.ReadAsArray()
    cols = array.shape[1]
    rows = array.shape[0]
    driver = gdal.GetDriverByName('GTiff')
    outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Byte)
    outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
    outband = outRaster.GetRasterBand(1)
    gdal.RasterizeLayer(outRaster, [1], source_layer, burn_values=[1])
Пример #13
0
def vector_to_raster(vector, output_path, x_size, y_size, options, data_type=gdal.GDT_Int32):
    '''
    This method creates a raster object by burning the values of this
    shape file into a raster with the given resolution.
    '''
    source_layer = vector.get_layer()
    x_min, x_max, y_min, y_max = source_layer.GetExtent()
    print source_layer.GetExtent()
    x_resolution = int((x_max - x_min) / x_size)
    y_resolution = int((y_max - y_min) / -y_size)  
    print x_resolution, y_resolution
    LOGGER.info(x_min, x_max, y_min, y_max)
    target_ds = gdal.GetDriverByName(str('GTiff')).Create(output_path, x_resolution, y_resolution, 1, data_type)
    spatial_reference = vector.get_spatial_reference()         
    target_ds.SetProjection(spatial_reference.ExportToWkt())
    target_ds.SetGeoTransform((x_min, x_size, 0, y_max, 0, -y_size))
    gdal.RasterizeLayer(target_ds, [1], source_layer, options=options)
    target_ds.FlushCache()
    return raster.Data(output_path)
Пример #14
0
def rasterize(shapefile, epsg, rasterfile, field, resolution):

    #making the shapefile as an object.
    input_shp = ogr.Open(shapefile)

    #getting layer information of shapefile.
    shp_layer = input_shp.GetLayer()

    #get extent values to set size of output raster.
    x_min, x_max, y_min, y_max = shp_layer.GetExtent()

    #calculate size/resolution of the raster.
    x_res = int((x_max - x_min) / resolution)
    y_res = int((y_max - y_min) / resolution)

    #get GeoTiff driver by
    image_type = 'GTiff'
    driver = gdal.GetDriverByName(image_type)

    #passing the filename, x and y direction resolution, no. of bands, new raster.
    new_raster = driver.Create(rasterfile, x_res, y_res, 1, gdal.GDT_Byte)

    #transforms between pixel raster space to projection coordinate space.
    new_raster.SetGeoTransform((x_min, resolution, 0, y_min, 0, resolution))

    #get required raster band.
    band = new_raster.GetRasterBand(1)

    #assign no data value to empty cells.
    no_data_value = 0
    band.SetNoDataValue(no_data_value)
    band.FlushCache()

    #adding a spatial reference
    new_rasterSRS = osr.SpatialReference()
    new_rasterSRS.ImportFromEPSG(epsg)
    new_raster.SetProjection(new_rasterSRS.ExportToWkt())

    #main conversion method
    OPTIONS = ['ATTRIBUTE=' + field]
    gdal.RasterizeLayer(new_raster, [1], shp_layer, None, options=OPTIONS)
    return
Пример #15
0
def shape_to_array(shape_file, envi_raster):
    """
    Function converts a shapefile into a numpy array.
    As an intermediate step the shapefile is exported as tiff using gdal.
    The dimensions and properties of this tif file are based on an existing EnviRaster.

    Only if a pixel center is covered by the shapefile, the respective shapefile ID is assigned to the pixel.
    The NA value is set to 0.
    Finally a numpy array is created from the tif file.


    :param shape_file: Path specification to shapefile
    :param envi_raster: Object of class Envi_Raster
    :return: numpy array
    """

    # Load the shapefile
    shape = ogr.Open(shape_file)
    shape_lyr = shape.GetLayer()

    # Extract the Envi_Raster ndarray
    array_stack = envi_raster.ndarray

    # Create an empty rasterfile in tif format
    [cols, rows] = array_stack.shape[0:2]
    outdriver = gdal.GetDriverByName("GTiff")
    outfile = shape_file.split(".")[0] + ".tif"
    outdata = outdriver.Create(str(outfile), rows, cols, 1, gdal.GDT_Float32)
    outdata.SetGeoTransform(envi_raster.trans)
    outdata.SetProjection(envi_raster.proj)

    # Export Raster Band & Rasterize shape_lyr by id if the pixel centre is covered by the shapefile
    band = outdata.GetRasterBand(1)
    band.SetNoDataValue(0)
    band.FlushCache()
    gdal.RasterizeLayer(outdata, [1], shape_lyr, options=["ATTRIBUTE=id"])

    # Read the raster and return as array
    shape_array = outdata.GetRasterBand(1).ReadAsArray()
    shape_array[shape_array == 0] = np.nan
    return shape_array
Пример #16
0
def vector2array(input_path, resolution, nodata):
    """
    Parameters:
        input_path : string
        resolution : float
        nodata : float

    Source:
        https://bit.ly/2HxeOng
    """
    # Open the data source and read in the extent
    source_ds = ogr.Open(input_path)
    source_layer = source_ds.GetLayer(0)
    xmin, xmax, ymin, ymax = source_layer.GetExtent()

    def round_mult(num, mult, to):
        if to == 'up':
            return (int(mult * round(float(num + mult) / mult)))

        elif to == 'down':
            return (int(mult * round(float(num - mult) / mult)))

    xmin = round_mult(num=xmin, mult=resolution, to='down')
    xmax = round_mult(num=xmax, mult=resolution, to='up')
    ymin = round_mult(num=ymin, mult=resolution, to='down')
    ymax = round_mult(num=ymax, mult=resolution, to='up')

    # Create the destination data source
    cols = int((xmax - xmin) / resolution)
    rows = int((ymax - ymin) / resolution)
    output_source = gdal.GetDriverByName('MEM').Create('', cols, rows,
                                                       gdal.GDT_Byte)
    output_source.SetGeoTransform((xmin, resolution, 0, ymax, 0, -resolution))
    output_band = output_source.GetRasterBand(1)
    output_band.SetNoDataValue(nodata)

    # Rasterize
    gdal.RasterizeLayer(output_source, [1], source_layer, burn_values=[1])

    # Read as array
    return (output_band.ReadAsArray().astype(int))
Пример #17
0
def rasterize(shapefile, exampletiff, outputfile, options=["ATTRIBUTE=val"]):
    src = gdal.Open(exampletiff, gdal.GA_ReadOnly)
    src_trfm = src.GetGeoTransform()
    src_proj = src.GetProjection()
    cols = _cols
    rows = _rows
    originX = src_trfm[0]
    originY = src_trfm[3]

    shp = ogr.Open(shapefile)
    layer = shp.GetLayer()

    dst = gdal.GetDriverByName('GTiff').Create(outputfile, cols, rows, 1,
                                               gdal.GDT_Float32)
    dst.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
    dst.SetProjection(src_proj)
    band = dst.GetRasterBand(1)
    NoData_value = -9999
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(dst, [1], layer, options=options)
Пример #18
0
def vec2raster(shp_file_path, template_path, out_raster_path, field, nodata=0):
    """
    shp:字符串,一个矢量,从0开始计数,整数
    templatePic:字符串,模板栅格,一个tif,地理变换信息从这里读,栅格大小与该栅格一致
    output:字符串,输出栅格,一个tif
    field:字符串,栅格值的字段
    nodata:整型或浮点型,矢量空白区转换后的值
    """
    ndsm = template_path
    data = gdal.Open(ndsm, gdalconst.GA_ReadOnly)
    geo_transform = data.GetGeoTransform()
    proj = data.GetProjection()
    #source_layer = data.GetLayer()
    x_min = geo_transform[0]
    y_max = geo_transform[3]
    x_max = x_min + geo_transform[1] * data.RasterXSize
    y_min = y_max + geo_transform[5] * data.RasterYSize
    x_res = data.RasterXSize
    y_res = data.RasterYSize
    mb_v = ogr.Open(shp_file_path)
    mb_l = mb_v.GetLayer()
    pixel_width = geo_transform[1]
    #输出影像为16位整型

    shp_file = os.path.basename(shp_file_path)
    shp_name, _ = os.path.splitext(shp_file)
    target_ds = gdal.GetDriverByName('GTiff').Create(
        out_raster_path + shp_name + '.tif', x_res, y_res, 1, gdal.GDT_Byte)

    target_ds.SetGeoTransform(geo_transform)
    target_ds.SetProjection(proj)
    band = target_ds.GetRasterBand(1)
    NoData_value = nodata
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(target_ds, [1],
                        mb_l,
                        options=["ATTRIBUTE=%s" % field, 'ALL_TOUCHED=TRUE'])

    target_ds = None
Пример #19
0
def rasterizeGeometry(geom, raster_ds, burn_value=1):
    # Reproject vector geometry to same projection as raster
    rasterSR = osr.SpatialReference()
    rasterSR.ImportFromWkt(raster_ds.GetProjectionRef()) 
    geom = reproject(geom, rasterSR)
    
    # Get raster georeference info
    transform = raster_ds.GetGeoTransform()
    xOrigin, pixelWidth, xSkew, yOrigin, ySkew, pixelHeight = transform

    # Get region boundary in raster-space
    xmin, xmax, ymin, ymax = getBounds(geom)

    # Figure out where the Upper Left corner is
    ULx = xmin if pixelWidth>0 else xmax
    ULy = ymin if pixelHeight>0 else ymax
        
    xoff = int((ULx - xOrigin)/pixelWidth)
    yoff = int((ULy - yOrigin)/pixelHeight)
    xcount = int((xmax - xmin)/abs(pixelWidth))+1
    ycount = int((ymax - ymin)/abs(pixelHeight))+1

    # Build an in-memory vector layer in order to rasterize it
    region_ds = ogr.GetDriverByName('Memory').CreateDataSource('memdata')
    region_lyr = region_ds.CreateLayer('region', srs=rasterSR )
    feat = ogr.Feature( region_lyr.GetLayerDefn() )
    feat.SetGeometryDirectly(geom)
    region_lyr.CreateFeature(feat)
    
    # Create in-memory target raster to burn the layer into
    mask_ds = gdal.GetDriverByName('MEM').Create('', xcount, ycount, 1, gdal.GDT_Byte)
    mask_ds.SetGeoTransform( ( xmin, pixelWidth, 0, ymax, 0, pixelHeight) )
    mask_ds.SetProjection(rasterSR.ExportToWkt())
    
    # Rasterize zone polygon to raster
    gdal.RasterizeLayer(mask_ds, [1], region_lyr, burn_values=[burn_value])
    mask = mask_ds.ReadAsArray(0, 0, xcount, ycount).astype(np.bool)
    
    return mask, (xoff, yoff)
Пример #20
0
def rasterize(input, output, xmin, ymin, xmax, ymax, pixel):
    # Open the data source
    orig_data_source = ogr.Open(input)
    # Make a copy of the layer's data source because we'll need to
    # modify its attributes table
    source_ds = ogr.GetDriverByName("Memory").CopyDataSource(
        orig_data_source, "")
    source_layer = source_ds.GetLayer(0)
    source_srs = source_layer.GetSpatialRef()

    # Create the destination data source
    x_res = int((xmax - xmin) / pixel)
    y_res = int((ymax - ymin) / pixel)

    target_ds = gdal.GetDriverByName('GTiff').Create(output, x_res, y_res, 3,
                                                     gdal.GDT_Byte)
    target_ds.SetGeoTransform((
        xmin,
        pixel,
        0,
        ymax,
        0,
        -pixel,
    ))
    target_ds.GetRasterBand(1).SetNoDataValue(0)
    target_ds.GetRasterBand(2).SetNoDataValue(0)
    target_ds.GetRasterBand(3).SetNoDataValue(0)
    if source_srs:
        # Make the target raster have the same projection as the source
        target_ds.SetProjection(source_srs.ExportToWkt())
    else:
        # Source has no projection (needs GDAL >= 1.7.0 to work)
        target_ds.SetProjection('LOCAL_CS["arbitrary"]')
    # Rasterize
    err = gdal.RasterizeLayer(target_ds, (3, 2, 1),
                              source_layer,
                              burn_values=(255, 255, 255))
    if err != 0:
        raise Exception("error rasterizing layer: %s" % err)
Пример #21
0
def burn_labels_to_image(image_path, shapefile_path, class_id):
    """
    Burn labels from the shapefile on the image. Will only override the values where the shapefile intersects, the rest
    will remain unchanged.

    :param image_path: Path to the raster label image.
    :param shapefile_path: Path to the shapefile.
    :param int: The class id of the shapefile.
    :return: Write the image to file (overriding). Return nothing.
    """
    # Get meta data from the image
    image_ds = gdal.Open(image_path, gdal.GA_Update)
    geo_transform = image_ds.GetGeoTransform()
    projection = image_ds.GetProjection()
    n_pixels_north = image_ds.RasterYSize
    n_pixels_east = image_ds.RasterXSize

    # Get geometries from shapefile
    driver = ogr.GetDriverByName("ESRI Shapefile")
    ds = driver.Open(shapefile_path, 0)
    layer = ds.GetLayer()
    gdal.RasterizeLayer(image_ds, (1, ), layer, burn_values=(class_id, ))
Пример #22
0
def ValidarClass(plyr, pValFilter, pAttrFil, pAttrAGB, geo_transform,
                 projection, kFoldImg):
    rows, cols = kFoldImg.shape
    labeled_pixels = np.zeros(
        (rows, cols))  # imagen base de zeros donde empieza a llenar
    plyr.SetAttributeFilter(pAttrFil + " = " + "'" + str(pValFilter) +
                            "'")  #### Con este filtra
    print("Nro Poligonos para el Kfold", str(pValFilter), " = ",
          plyr.GetFeatureCount())
    pClasesAGB = []
    for feature in plyr:
        pClasesAGB.append(feature.GetField(pAttrAGB))
    pClasesAGB = list(
        dict.fromkeys(pClasesAGB)
    )  # remueve Duplicados si hay dos o mas poligonos con el mismo AGB
    for val in pClasesAGB:
        plyr.SetAttributeFilter(pAttrAGB + " = " +
                                str(val))  #### Con este filtra
        print("AGB:", val, "nroPol:", plyr.GetFeatureCount())
        driver = gdal.GetDriverByName('MEM')
        target_ds = driver.Create('', cols, rows, 1, gdal.GDT_UInt16)
        target_ds.SetGeoTransform(geo_transform)
        target_ds.SetProjection(projection)
        gdal.RasterizeLayer(
            target_ds, [1], plyr,
            burn_values=[val])  ## Asigna el valor de label al poligono
        band = target_ds.GetRasterBand(1)
        ### Valida el poligono contra los datos del shape
        pImgPol = np.array(band.ReadAsArray())
        pClassImaKfold = np.array(kFoldImg)
        n_samples = rows * cols
        imagRes = np.where(
            pImgPol.reshape((n_samples, 1)) > 0,
            pClassImaKfold.reshape((n_samples, 1)), 0)
        print("AGB en Shp: ", str(val), "Media Calculada:",
              np.mean(imagRes[imagRes != 0]))
        labeled_pixels += imagRes.reshape((rows, cols))
    return labeled_pixels
Пример #23
0
def rasterize_shp(tif, shp, output):
    # tif = 'D:\\MODIS\\data_tif\\MOD11A2.006\\2003.01.09.LST_Day_1km.tif'
    # shp = 'D:\\MODIS\\shp\\china_dissolve.shp'
    # output = 'D:\\MODIS\\my.tif'

    data = gdal.Open(tif, gdalconst.GA_ReadOnly)
    geo_transform = data.GetGeoTransform()
    #source_layer = data.GetLayer()
    x_min = geo_transform[0]

    y_max = geo_transform[3]

    x_max = x_min - geo_transform[1] * data.RasterXSize
    y_min = y_max + geo_transform[5] * data.RasterYSize
    x_res = data.RasterXSize
    y_res = data.RasterYSize

    # print(x_min)
    # print(geo_transform[5])
    # print(data.RasterYSize)

    mb_v = ogr.Open(shp)
    mb_l = mb_v.GetLayer()
    pixel_width = geo_transform[1]
    print(x_min, pixel_width, 0, y_max, 0, pixel_width)

    # exit()
    target_ds = gdal.GetDriverByName('GTiff').Create(output, x_res, y_res, 1,
                                                     gdal.GDT_Byte)
    target_ds.SetGeoTransform((x_min, pixel_width, 0, y_max, 0, pixel_width))
    band = target_ds.GetRasterBand(1)
    NoData_value = -99
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(target_ds, [1], mb_l)
    # gdal.RasterizeLayer(target_ds, [1], mb_l, options=["ATTRIBUTE=hedgerow"])

    target_ds = None
Пример #24
0
def rasteriseVector(inVectorPath, inRasterPath, outRasterPath, champs, valeur, noDet):
    fileName = os.path.basename(inVectorPath)
    print("          Rasterisation du fichier " + fileName + "...")

    rasterRef = gdal.Open(inRasterPath, gdal.GA_ReadOnly)

    vectorData = ogr.Open(inVectorPath)
    vectorLayer = vectorData.GetLayer()

    out = gdal.GetDriverByName("GTiff").Create(outRasterPath, rasterRef.RasterXSize, rasterRef.RasterYSize, 1, gdal.GDT_Byte)
    out.SetProjection(rasterRef.GetProjectionRef())
    out.SetGeoTransform(rasterRef.GetGeoTransform())

    if type(valeur) == str:
        SQL = champs + "='" + valeur + "'"
        vectorLayer.SetAttributeFilter(SQL)

    band = out.GetRasterBand(1)
    band.Fill(-9999)
    band.SetNoDataValue(-9999)
    band.FlushCache()

    gdal.RasterizeLayer(out, [1], vectorLayer, None, None, [5 * noDet])
Пример #25
0
def F_shp2geotiff(shp_path, tiff_path_out, tiff_path_ref, burn_value=1):
    """
    rasterize shape file to match existing tiff file
    shp_path:
        absolute path to shape file, which has to be in the same spatial 
        reference/prejection as tiff_path_template
    tiff_path_out:
        output path of the tiff converted from shp file
    tiff_path_ref:
        the "reference" tiff file
    """
    gt, proj, xres, yres = F_tiff_info(tiff_path_ref)
    tiff_out = gdal.GetDriverByName('GTiff').Create(tiff_path_out,\
                                   xres,yres,1,gdal.GDT_Float32)
    tiff_out.SetGeoTransform(gt)
    tiff_out.SetProjection(proj)

    driver = ogr.GetDriverByName('ESRI Shapefile')
    dataSource = driver.Open(shp_path, 0)
    layer = dataSource.GetLayer()
    gdal.RasterizeLayer(tiff_out, [1], layer, burn_values=[burn_value])
    tiff_out.FlushCache()
    tiff_out = None
Пример #26
0
    def mask(self, ar=None, nodata=0, scale=10):
        import ogr
        import gdal
        from osgeo.gdalconst import GDT_Byte
        import numpy as np
        import numpy.ma as ma
        """Return an numpy array with a hard mask to exclude areas outside of the place"""
        srs_in = ogr.osr.SpatialReference()
        srs_in.ImportFromEPSG(self.row['srid'])

        aa = self.aa(scale)

        image = aa.get_memimage(data_type=GDT_Byte)

        ogr_ds = ogr.GetDriverByName('Memory').CreateDataSource('/tmp/foo')
        lyr = ogr_ds.CreateLayer('place', aa.srs)

        geometry = ogr.CreateGeometryFromWkt(self.row['wkt'])
        geometry.AssignSpatialReference(srs_in)
        geometry.TransformTo(aa.srs)

        feature = ogr.Feature(lyr.GetLayerDefn())
        feature.SetGeometryDirectly(geometry)

        lyr.CreateFeature(feature)

        gdal.RasterizeLayer(image, [1], lyr, burn_values=[1])
        feature.Destroy()

        mask = np.logical_not(
            np.flipud(
                np.array(image.GetRasterBand(1).ReadAsArray(), dtype=bool)))

        if ar is not None:
            return ma.masked_array(ar, mask=mask, nodata=nodata, hard=True)
        else:
            return mask
Пример #27
0
def create_building_mask(rasterSrc,
                         vectorSrc,
                         npDistFileName='',
                         noDataValue=0,
                         burn_values=1):
    '''
    Create building mask for rasterSrc,
    Similar to labeltools/createNPPixArray() in spacenet utilities
    '''

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

    ## create First raster memory layer, units are pixels
    # Change output to geotiff instead of memory
    memdrv = gdal.GetDriverByName('GTiff')
    dst_ds = memdrv.Create(npDistFileName,
                           cols,
                           rows,
                           1,
                           gdal.GDT_Byte,
                           options=['COMPRESS=LZW'])
    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])
    dst_ds = 0

    return
Пример #28
0
def rasterizar_entrenamiento(plyr, pValFilter, pAttrFil, pAttrAGB, rows, cols , geo_transform, projection):
    labeled_pixels = np.zeros((rows, cols)) # imagen base de zeros donde empieza a llenar
    plyr.SetAttributeFilter(pAttrFil + " <> " + "'" + str(pValFilter) + "'")  #### Con este filtra
    print("Nro de Pol Filtrados  <> de",str(pValFilter),":", plyr.GetFeatureCount())
    pClasesAGB = []
    for feature in plyr:
        pClasesAGB.append(feature.GetField(pAttrAGB))
        pClasesAGB = list(dict.fromkeys(pClasesAGB)) # remueve Duplicados si hay dos o mas poligonos con el mismo AGB
    print(pClasesAGB)
  
   #driver = gdal.GetDriverByName('MEM')
   #target_ds = driver.Create('', cols, rows, 1, gdal.GDT_UInt16)
    for val in pClasesAGB:
        plyr.SetAttributeFilter(pAttrAGB + " = " + str(val))  #### Con este filtra
        print("AGB:", val , "nroPol:", plyr.GetFeatureCount())
        driver = gdal.GetDriverByName('MEM')
        target_ds = driver.Create('', cols, rows, 1, gdal.GDT_UInt16)
        target_ds.SetGeoTransform(geo_transform)
        target_ds.SetProjection(projection)
        gdal.RasterizeLayer(target_ds, [1], plyr, burn_values=[val]) ## Asigna el valor de label al poligono 
      #return target_ds
        band = target_ds.GetRasterBand(1)
        labeled_pixels += band.ReadAsArray()
    return labeled_pixels
Пример #29
0
def vector2array(xmin, ymax, cols, rows, res_x, res_y, layer, nodata):
    # Create the destination data source
    targetDS = (
        gdal.GetDriverByName('MEM').Create(
            '', cols, rows, gdal.GDT_Byte
            )
        )

    targetDS.SetGeoTransform((
        xmin,  # Leftmost pixel position.
        res_x,  # The pixel width.
        0,
        ymax,  # Upper pixel position.
        0,
        -res_y  # The pixel height.
        ))
    band = targetDS.GetRasterBand(1)
    band.SetNoDataValue(nodata)

    # Rasterize
    err = gdal.RasterizeLayer(
        targetDS,
        [1],
        layer,
        burn_values=[1],
        options=['ALL_TOUCHED=TRUE']
        )

    if err != 0:
        print("error:", err)

    # Read as array
    array = band.ReadAsArray()
    array = array.astype(float)
    array[np.where(array == 0)] = np.nan
    return(np.flipud(array))
Пример #30
0
def RasterizeShapeMatchRaster(shape_file,raster_file,output_file):
    # open raster and obtain extent and properties
    data = gdal.Open(raster_file ,gdal.GA_ReadOnly)
    geo_transform = data.GetGeoTransform()
    #source_layer = data.GetLayer()
    x_min = geo_transform[0]
    y_max = geo_transform[3]
    x_max = x_min + geo_transform[1] * data.RasterXSize
    y_min = y_max + geo_transform[5] * data.RasterYSize
    x_len = data.RasterXSize
    y_len = data.RasterYSize
    mb_v = ogr.Open(shape_file)
    mb_l = mb_v.GetLayer()
    pixel_width = geo_transform[1]
    target_ds = gdal.GetDriverByName('GTiff').Create(output_file, x_len, y_len, 1, gdal.GDT_Byte)
    target_ds.SetGeoTransform(geo_transform)
    band = target_ds.GetRasterBand(1)
    NoData_value = -999999
    band.SetNoDataValue(NoData_value)
    target_ds.SetProjection(data.GetProjectionRef())
    band.FlushCache()
    gdal.RasterizeLayer(target_ds, [1], mb_l,burn_values=[255])

    target_ds = None