Exemple #1
0
    def polygonize(
        self,
        field_name="dn",
        vector_path="/vsimem/polygonized.shp",
        layer_name="poly",
        verbose=False,
        no_mask=False,
    ):
        global _mem_num
        prj = self.ds.GetProjection()
        vector_path = f"/vsimem/polygonized_{_mem_num}.shp"
        _mem_num = _mem_num + 1
        ds_vector = DRIVER_OGR_SHP.CreateDataSource(vector_path)
        srs = osr.SpatialReference(wkt=prj)
        layer_vector = ds_vector.CreateLayer(layer_name, srs=srs)
        raster_field = ogr.FieldDefn(field_name, type_mapping[self.band.DataType])
        layer_vector.CreateField(raster_field)

        if no_mask:
            no_data_band = None
        else:
            no_data_band = self.band.GetMaskBand()

        if verbose:
            gdal.Polygonize(self.band, no_data_band, layer_vector, 1, [])
        else:
            gdal.Polygonize(
                self.band, no_data_band, layer_vector, 1, [], callback=progress_callback
            )

        return ds_vector, layer_vector
    def polygonise_travel_times(self):
        """Function to polygonise binary raster using GDAL/OGR for input to PostGIS for Zonal statistics.

		Arguments:
		None

		Returns:
		None
		"""
        latlong = osr.SpatialReference()
        latlong.ImportFromEPSG(4326)  #Set SRS
        polygon = self.shp_bin.encode('utf-8')  #Set encodings
        in_poly_ds = gdal.Open(self.raster_bin)  #Get raster data
        polygon_band = in_poly_ds.GetRasterBand(1)
        drv = ogr.GetDriverByName(
            "ESRI Shapefile")  #Set output as ESRI Shp file
        dst_ds = drv.CreateDataSource(polygon)
        dst_layer = dst_ds.CreateLayer(polygon, srs=latlong)
        newField = ogr.FieldDefn(
            'Value', ogr.OFTInteger
        )  # Create field to hold raster binary values (PostGIS selects only 1 and NOT 0)
        dst_layer.CreateField(newField)
        #gdal.Polygonize(polygon_band, None, dst_layer, -1, ["value"], callback=None)
        gdal.Polygonize(polygon_band, None, dst_layer, 0, [],
                        callback=None)  #Polygonize raster
def polygonize_raster(img_path, outShp):
    """
    Generates a shapefile (outShp) from the input image (img_path).
    """
    try:
        sourceRaster = gdal.Open(img_path)
        band = sourceRaster.GetRasterBand(1)
        driver = ogr.GetDriverByName("ESRI Shapefile")
        # If shapefile already exist, delete it
        if os.path.exists(outShp):
            driver.DeleteDataSource(outShp)
        outDatasource = driver.CreateDataSource(outShp)
        # get proj from raster
        srs = osr.SpatialReference()
        srs.ImportFromWkt(sourceRaster.GetProjectionRef())
        # create layer with proj
        outLayer = outDatasource.CreateLayer(outShp, srs)
        # Add class column to shapefile
        newField = ogr.FieldDefn('DN', ogr.OFTInteger)
        outLayer.CreateField(newField)
        gdal.Polygonize(band, None, outLayer, 0, [], callback=None)
        outDatasource.Destroy()
        sourceRaster = None
    except Exception as e:
        print('gdal Polygonize Error: ' + str(e))
Exemple #4
0
def main():
    args = getArgs()

    if args.verbose:
        print args
    raster = gdal.Open(args.input, GA_ReadOnly)

    if args.band:
        band = raster.GetRasterBand(args.band)
    else:
        band = raster.GetRasterBand(1)

    driver = ogr.GetDriverByName("ESRI Shapefile")
    vector = driver.CreateDataSource(args.output)
    projection = osr.SpatialReference()
    projection.ImportFromWkt(raster.GetProjectionRef())
    layer = vector.CreateLayer("out", srs=projection)

    field = "class"
    field_def = ogr.FieldDefn(field, ogr.OFTInteger)
    layer.CreateField(field_def)
    field_type_example = 0

    maskband = None
    options = []
    output = gdal.Polygonize(band, maskband, layer, field_type_example,
                             options)

    band = None
    raster = None
    shapefile = None
Exemple #5
0
    def tiff_to_shp(tiff_path, shp_path, proj=None):
        """栅格转矢量"""
        # 袁小棋贡献
        # 参数类型检查
        if isinstance(tiff_path, gdal.Dataset):
            dataset = tiff_path
        else:
            dataset = gdal.Open(tiff_path)
        # -------------------------------------------------------
        input_band = dataset.GetRasterBand(1)
        #  create output datasource
        shp_driver = ogr.GetDriverByName("ESRI Shapefile")
        # 获取坐标
        if proj is None:
            proj = osr.SpatialReference()
            proj.SetWellKnownGeogCS("WGS84")

        # create output file name
        output_shapefile = shp_driver.CreateDataSource(shp_path)
        new_shapefile = output_shapefile.CreateLayer(shp_path[:-4], proj)
        gdal.Polygonize(input_band, None, new_shapefile, -1, [], callback=None)
        # 当输入格式是 float 需要用下面一个函数
        # gdal.FPolygonize(input_band, None, new_shapefile, -1, [], callback=None, )
        new_shapefile.SyncToDisk()
        logging.info('tiff_to_shp success')
def polygonize(input_tif, band, epsg):

    epsg_code = epsg.split(':')[1]

    srs = osr.SpatialReference()
    srs.ImportFromEPSG(int(epsg_code))

    source_raster = gdal.Open(input_tif)
    band = source_raster.GetRasterBand(band)
    band_array = band.ReadAsArray()

    out_vector_file = "polygonized.json"

    driver = ogr.GetDriverByName('GeoJSON')

    out_data_source = driver.CreateDataSource(out_vector_file + "")
    out_layer = out_data_source.CreateLayer(out_vector_file, srs=srs)

    new_field = ogr.FieldDefn('change_detection', ogr.OFTInteger)
    out_layer.CreateField(new_field)

    gdal.Polygonize(band, None, out_layer, 0, [], callback=None)

    out_data_source = None
    source_raster = None

    data = json.loads(open(out_vector_file).read())
    gdf = gp.GeoDataFrame.from_features(data['features'])

    gdf.crs = {'init': 'epsg:{}'.format(epsg_code)}
    gdf = gdf.to_crs(epsg=epsg_code)

    os.remove(out_vector_file)

    return gdf
Exemple #7
0
def polygonize_scene(f_img, f_vct):
    #-------------- generate original shaplefile, complex polygon and in a UTM projection
    f_temp = os.path.split(f_vct)[0] + '/lakes_ori.shp'
    ds_img = gdal.Open(f_img)
    band = ds_img.GetRasterBand(1)

    projection = ds_img.GetProjection()
    geo_transform = ds_img.GetGeoTransform()

    driver = ogr.GetDriverByName("ESRI Shapefile")
    if os.path.exists(f_temp):
        driver.DeleteDataSource(f_temp)

    ds_out = driver.CreateDataSource(f_temp)
    layer_out = ds_out.CreateLayer("polygonized", srs=None)
    field_new = ogr.FieldDefn('Code_uniq', ogr.OFTInteger)
    layer_out.CreateField(field_new)

    gdal.Polygonize(band, None, layer_out, 0, [], callback=None)

    ds_out.Destroy()
    del ds_img

    f_prj = f_temp[:-3] + 'prj'
    fo_prj = open(f_prj, 'w')
    fo_prj.write(projection)
    fo_prj.close()
    #-------------- simplify and reprojct
    cmd_ogr = 'ogr2ogr -overwrite -simplify 30 -where \"Code_uniq>0\"  -t_srs "+proj=aea +lat_1=25.0 +lat_2=47.0 +lon_0=105.0 +x_0=0 +y_0=0 +datum=WGS84" ' + f_vct + ' ' + f_temp

    _rs = lib_IO.run_exe(cmd_ogr)
    print f_vct

    driver = ogr.GetDriverByName("ESRI Shapefile")
    driver.DeleteDataSource(f_temp)
Exemple #8
0
def pcr2Shapefile(srcMap, dstShape, fieldName):
    """
    polygonize a pcraster map into a shapefile
    
    srcMap:       string, path to PCRaster map
    dstShape:     string, path to shapefile
    fieldName:    string, name of the item in the shapefile
    """
    gdal.UseExceptions()

    #-create a new shapefile
    driver = ogr.GetDriverByName("ESRI Shapefile")
    if os.path.exists(dstShape):
        driver.DeleteDataSource(dstShape)

    destinationDataSet = driver.CreateDataSource(dstShape)
    destinationLayer = destinationDataSet.CreateLayer('TEMP', srs=None)
    newField = ogr.FieldDefn(fieldName, ogr.OFTInteger)
    destinationLayer.CreateField(newField)

    #-open the source data and polygonize into new field
    sourceDataSet = gdal.Open(srcMap)
    sourceBand = sourceDataSet.GetRasterBand(1)
    gdal.Polygonize(sourceBand, None, destinationLayer, 0, [], callback=None)

    #-Destroy the destination dataset
    destinationDataSet.Destroy()
Exemple #9
0
def polygonize_to_shape(inraster, out_shape, out_epsg=4326, mask=None):
    """
    This function takes an input raster and polygonizes it.

    :param raster: input raster file
    :param mask: mask file
    :param out_shape: output shapefile
    :param srs: spatial reference system in EPSG code
    :return:
    """

    raster = gdal.Open(inraster)
    src_band = raster.GetRasterBand(1)

    if mask is not None:
        mask_file = gdal.Open(mask)
        mask_band = mask_file.GetRasterBand(1)
    else:
        mask_band = src_band

    srs = osr.SpatialReference()
    srs.ImportFromEPSG(out_epsg)

    dst_layername = out_shape
    drv = ogr.GetDriverByName("ESRI Shapefile")
    dstfile = drv.CreateDataSource(dst_layername)
    dst_layer = dstfile.CreateLayer(dst_layername, srs=srs)
    gdal.Polygonize(src_band, mask_band, dst_layer, -1, [], callback=None)
Exemple #10
0
def raster_to_vector_mask(raster_object, output_path, no_data=[0]):
    raster_array = raster_object.read_data_file_as_array()
    for i in no_data:
        raster_array[raster_array != i] = 0
        
    raster_array[raster_array != 0] = 1
    
    mask_file = create_filename(output_path, 'mask.tif')
    
    create_raster_from_reference(mask_file, raster_array, raster_object.get_file())
    
    mask_raster = raster.Data(mask_file)
    
    ds = mask_raster._open_file()
    
    rb = ds.GetRasterBand(1)
    
    
    
    dst_layername = 'POLYGONIZED_STUFF'
    drv = ogr.GetDriverByName(str('ESRI Shapefile'))
    dst_ds = drv.CreateDataSource(output_path)
    dst_layer = dst_ds.CreateLayer(dst_layername, srs = None )
    #dst_layer.SetSpatialRef(raster.get_spatial_reference())
    gdal.Polygonize(rb, None, dst_layer, -1, [])
    
    
def polygonize(url, date, originator):

    ds = gdal.Open(url)

    srs = osr.SpatialReference(wkt=ds.GetProjection())

    band = ds.GetRasterBand(1)
    band_array = band.ReadAsArray()

    out_geojson = 'polygonized.json'

    driver = ogr.GetDriverByName('GeoJSON')

    out_data_source = driver.CreateDataSource(out_geojson + "")
    out_layer = out_data_source.CreateLayer('polygonized', srs=srs)

    new_field = ogr.FieldDefn('hot_spot', ogr.OFTInteger)
    out_layer.CreateField(new_field)

    gdal.Polygonize(band, None, out_layer, 0, [], callback=None)

    out_data_source = None
    ds = None

    data = json.loads(open(out_geojson).read())
    gdf = gp.GeoDataFrame.from_features(data['features'])
    gdf = gdf[gdf['hot_spot'] == 1]
    gdf['date'] = date
    gdf['originator'] = originator

    gdf.crs = {'init': 'epsg:{}'.format(srs.GetAttrValue('AUTHORITY', 1))}

    os.remove(out_geojson)

    return gdf
Exemple #12
0
    def save_to_vector(self, fname):
        #create a temporary gdal raster to read from
        mem_driver = gdal.GetDriverByName('MEM')
        mem_ds = mem_driver.Create('', self.xsize(), self.ysize(), 1,
                                   GDT_Float32)

        src_band = mem_ds.GetRasterBand(1)
        src_band.WriteArray(self._raster, 0, 0)

        #convert to vector
        driver = ogr.GetDriverByName('ESRI Shapefile')
        dst_ds = driver.CreateDataSource(fname)

        #file already exists
        if dst_ds is None:
            raise IOError('File already exists. Please select another file.')

        dst_layer = dst_ds.CreateLayer('HRUs')

        fd = ogr.FieldDefn('DN', ogr.OFTInteger)
        dst_layer.CreateField(fd)
        dst_field = 0

        prog_func = gdal.TermProgress
        options = []
        #result = gdal.Polygonize( src_band, None, dst_layer, 0 )
        result = gdal.Polygonize(src_band,
                                 None,
                                 dst_layer,
                                 dst_field,
                                 options,
                                 callback=prog_func)
Exemple #13
0
def polygonize_scene(p_render,f_img,f_vct):
	#-------------- generate original shaplefile, complex polygon and in a UTM projection
	f_temp = p_render + '/lakes_ori.shp'
	ds_img = gdal.Open(f_img)
	band = ds_img.GetRasterBand(1)
	
	projection = ds_img.GetProjection()
	geo_transform = ds_img.GetGeoTransform()

	driver = ogr.GetDriverByName("ESRI Shapefile")
	if os.path.exists(f_temp):
		driver.DeleteDataSource(f_temp)
		
	sr_in = osr.SpatialReference()
	sr_in.ImportFromWkt(projection)
	ds_out = driver.CreateDataSource(f_temp)
	layer_out = ds_out.CreateLayer("polygonized", srs=sr_in)
	sub__add_fields(layer_out)
	
	gdal.Polygonize( band, None, layer_out, 0, [], callback=None )
	
	sub__update_field_value(f_vct,layer_out)
	
	ds_out.Destroy()
	del ds_img
	
	#-------------- simplify and reprojct
	cmd_ogr = 'ogr2ogr -overwrite -simplify 25 -where \"Code_uniq>0\" ' + f_vct + ' ' + f_temp

	_rs = lib_IO.run_exe(cmd_ogr)
	print f_vct
	
	driver = ogr.GetDriverByName("ESRI Shapefile")
Exemple #14
0
def mask_to_polygon_in_memory(original_data, array, field_name='label'):
    geotrans = original_data.GetGeoTransform()
    proj = original_data.GetProjection()

    driver = gdal.GetDriverByName('MEM')
    dataset = driver.Create('', array.shape[1], array.shape[0], 1,
                            gdal.GDT_Float32)
    dataset.GetRasterBand(1).WriteArray(array)
    dataset.SetProjection(proj)
    dataset.SetGeoTransform(geotrans)
    band = dataset.GetRasterBand(1)

    driver_mask = gdal.GetDriverByName('MEM')
    ds_mask = driver_mask.Create('', array.shape[1], array.shape[0], 1,
                                 gdal.GDT_Float32)
    ds_mask.SetGeoTransform(geotrans)
    ds_mask.SetProjection(proj)
    ds_mask_array = (array > 0).astype(np.int32)
    ds_mask.GetRasterBand(1).WriteArray(ds_mask_array)
    mask_band = ds_mask.GetRasterBand(1)

    srs = osr.SpatialReference(wkt=proj)
    driver = gdal.GetDriverByName("Memory")
    outDatasource = driver.Create('', 0, 0, 0, gdal.GDT_Float32)
    # outDatasource = driver.CreateDataSource('')
    outLayer = outDatasource.CreateLayer("polygonized", srs=srs)
    if field_name is None:
        field_name = 'MyFLD'
    newField = ogr.FieldDefn(field_name, ogr.OFTInteger)
    outLayer.CreateField(newField)

    gdal.Polygonize(band, mask_band, outLayer, 0, [], callback=None)
    return outDatasource
Exemple #15
0
def raster2vector(path_raster, path_vector, output_format):
    if output_format.lower() == 'kml':
        format = 'KML'
        ext = '.kml'
    elif output_format.lower() == 'geojson':
        format = 'Geojson'
        ext = '.json'
    elif output_format.lower() == 'shp':
        format = 'ESRI Shapefile'
        ext = '.shp'
    else:
        format = 'ESRI Shapefile'
        ext = '.shp'

    # Generate exceptions
    gdal.UseExceptions()

    src_ds = gdal.Open(path_raster)
    num_band = src_ds.RasterCount
    temp = []
    for i in range(1, num_band + 1):
        if src_ds is None:
            print('Unable to open %s' % src_fileName)
            sys.exit(1)

        srcband = src_ds.GetRasterBand(i)
        maskband = srcband.GetMaskBand()

        dst_layername = os.path.join(
            path_vector,
            os.path.splitext(os.path.basename(path_raster))[0] + '_b' +
            str(i) + ext)
        temp.append(dst_layername)
        dst_fieldname = 'value'

        drv = ogr.GetDriverByName(format)

        # Saving vectors by individual bands
        dst_ds = drv.CreateDataSource(dst_layername)

        source_srs = osr.SpatialReference()
        source_srs.ImportFromWkt(src_ds.GetProjectionRef())

        dst_layer = dst_ds.GetLayerByName(dst_layername)
        dst_layer = dst_ds.CreateLayer(dst_layername,
                                       geom_type=ogr.wkbPolygon,
                                       srs=source_srs)

        fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger)
        dst_layer.CreateField(fd)
        dst_field = 0
        gdal.Polygonize(srcband, maskband, dst_layer, dst_field, callback=None)
        srcband = None
        src_ds = None
        dst_ds = None
        mask_ds = None
    print('Vector successfully converted to %s' % (dst_layername))
    return temp
def classify(prepros_folder):
    for file in os.listdir(prepros_folder):

        ### Folder, date & timestamp
        classification = rootpath + "\\classification"
        scene_name = str(prepros_folder.split("\\")[X])[:32]  # [X] element of filepath, change this to match scene name. [:32] first caracters of element
        print("scene_name:", scene_name)
        output_folder = os.path.join(classification, scene_name)
        print("output_folder:", output_folder)
        polarization = str(file)[46:48] # polarization from filename

        if not os.path.exists(output_folder):
            os.mkdir(output_folder)

        GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis()
        HashMap = snappy.jpy.get_type('java.util.HashMap')
        gc.enable()

        sentinel_1 = ProductIO.readProduct(os.path.join(prepros_folder, file))

        res = [20, 50]  # parameters for CFAR
        for r in res:
            resolution = r

            gd_window = resolution * 12.0
            bg_window = resolution * 37.0

            # AdaptiveThresholding (Constant False Alarm Rate CFAR)
            parameters = HashMap()
            parameters.put('targetWindowSizeInMeter', resolution)
            parameters.put('guardWindowSizeInMeter', gd_window)
            parameters.put('backgroundWindowSizeInMeter', bg_window)
            parameters.put('pfa', 6.0)

            target_1 = GPF.createProduct("AdaptiveThresholding", parameters, sentinel_1)
            parameters = None

            # Subset (extracting classification band)
            parameters = HashMap()
            parameters.put('bandNames', 'Sigma0_' + polarization + '_ship_bit_msk')

            outfile = output_folder + "\\" + scene_name + "_" + polarization + "_cfar_" + str(resolution) + "m"
            target_2 = GPF.createProduct("Subset", parameters, target_1)
            ProductIO.writeProduct(target_2, outfile, 'GeoTIFF-BigTIFF', pm)

            # Classification to vector
            ds = gdal.Open(str(outfile + ".tif"))

            rasterband = ds.GetRasterBand(1)

            dst_layername = outfile + "_Iceberg_outline"
            drv = ogr.GetDriverByName("GeoJSON")
            dst_ds = drv.CreateDataSource(dst_layername + ".geojson")
            dest_srs = ogr.osr.SpatialReference()
            dest_srs.ImportFromEPSG(4326)
            dst_layer = dst_ds.CreateLayer(dst_layername, dest_srs)

            gdal.Polygonize(rasterband, rasterband, dst_layer, -1, [], callback=None) # (input, mask, dest_layer,,,) 
Exemple #17
0
def raster_to_shpfile(src_path, band_num, dst_layername):
    src_ds = gdal.Open( src_path)
    assert src_ds
    srcband = src_ds.GetRasterBand(band_num)
    drv = ogr.GetDriverByName("ESRI Shapefile")
    dst_ds = drv.CreateDataSource(dst_layername + ".shp" )
    dst_layer = dst_ds.CreateLayer(dst_layername, srs = None )
    gdal.Polygonize( srcband, None, dst_layer, -1, [], callback=None )
    return dst_layer
Exemple #18
0
def polygonize(rasterTemp, outShp, sieveSize=1):
    sourceRaster = gdal.Open(rasterTemp)
    band = sourceRaster.GetRasterBand(1)
    driver = ogr.GetDriverByName("ESRI Shapefile")
    # If shapefile already exist, delete it
    if os.path.exists(outShp):
        driver.DeleteDataSource(outShp)

    outDatasource = driver.CreateDataSource(outShp)
    # get proj from raster
    srs = osr.SpatialReference()
    srs.ImportFromWkt(sourceRaster.GetProjectionRef())
    # create layer with proj
    outLayer = outDatasource.CreateLayer(outShp, srs)
    # Add class column (1,2...) to shapefile

    newField = ogr.FieldDefn('grid_code', ogr.OFTInteger)
    outLayer.CreateField(newField)

    gdal.Polygonize(band, None, outLayer, 0, [], callback=None)

    outDatasource.Destroy()
    sourceRaster = None
    band = None

    try:
        # Add area for each feature
        ioShpFile = ogr.Open(outShp, update=1)

        lyr = ioShpFile.GetLayerByIndex(0)
        lyr.ResetReading()

        field_defn = ogr.FieldDefn("Area", ogr.OFTReal)
        lyr.CreateField(field_defn)
    except:
        print("Can not add filed of Area!")

    for i in lyr:
        # feat = lyr.GetFeature(i)
        geom = i.GetGeometryRef()
        area = round(geom.GetArea())

        lyr.SetFeature(i)
        i.SetField("Area", area)
        lyr.SetFeature(i)
        # if area is less than inMinSize or if it isn't forest, remove polygon
        if area < sieveSize:
            lyr.DeleteFeature(i.GetFID())
    ioShpFile.Destroy()

    del sourceRaster,band,outDatasource
    gc.collect()

    return outShp
def main(inraster, outshape):
    ## inraster = "/Carnegie/DGE/caodata/Scratch/dknapp/Fish/coral_keahou_mosaic_v1k_dep_masked"
    ## outshape = "/Carnegie/DGE/caodata/Scratch/dknapp/Fish/coral_keahou_mosaic_v1k_dep_masked.shp"

    inDS = gdal.Open(inraster, gdal.GA_ReadOnly)
    gt = inDS.GetGeoTransform()
    inproj = inDS.GetProjection()
    nodataval = inDS.GetRasterBand(1).GetNoDataValue()
    indata = inDS.GetRasterBand(1).ReadAsArray()
    if (nodataval is None):
        numzero = np.equal(indata, 0.0)
        if (np.sum(numzero) == 0):
            #  missing data value must be -9999
            nodataval = -9999.0
        else:
            nodataval = 0.0

    good = np.not_equal(indata, nodataval)

    mask = np.zeros_like(indata, dtype=np.dtype('B'))
    mask2 = np.zeros_like(indata, dtype=np.dtype('B'))
    mask[good] = 255
    mask2[good] = 1
    memdrv = gdal.GetDriverByName('MEM')
    tempDS = memdrv.Create('',
                           mask.shape[1],
                           mask.shape[0],
                           2,
                           eType=gdal.GDT_Byte)
    tempDS.SetGeoTransform(gt)
    tempDS.SetProjection(inproj)
    tempDS.GetRasterBand(1).WriteArray(mask)
    tempDS.GetRasterBand(2).WriteArray(mask2)
    tempDS.GetRasterBand(1).SetNoDataValue(0)
    tempDS.GetRasterBand(2).SetNoDataValue(0)
    tempDS.FlushCache()
    myBand = tempDS.GetRasterBand(1)
    ## gdal.FillNodata(targetBand=myBand, maskBand=None, maxSearchDist=5, smoothingIterations=0)
    myMask = tempDS.GetRasterBand(2)
    ## gdal.FillNodata(targetBand=myMask, maskBand=None, maxSearchDist=5, smoothingIterations=0)

    drv = ogr.GetDriverByName("ESRI Shapefile")
    dstDS = drv.CreateDataSource(outshape)
    mysrs = osr.SpatialReference()
    mysrs.ImportFromWkt(inproj)
    dst_layer = dstDS.CreateLayer("outline", srs=mysrs)
    newField = ogr.FieldDefn('MYFIELD', ogr.OFTInteger)
    dst_layer.CreateField(newField)
    gdal.Polygonize(myBand, myMask, dst_layer, 0, [], callback=None)

    dstDS.Destroy()
    tempDS = None
    inDS = None
def polygonise_travel_times(raster, shp_bin):
	latlong = osr.SpatialReference()
	latlong.ImportFromEPSG( 4326 )
	polygon = shp_bin.encode('utf-8')
	in_poly_ds = gdal.Open(raster)
	polygon_band = in_poly_ds.GetRasterBand(1)
	drv = ogr.GetDriverByName("ESRI Shapefile")
	dst_ds = drv.CreateDataSource(polygon)
	dst_layer = dst_ds.CreateLayer(polygon, srs=latlong)
	newField = ogr.FieldDefn('Value', ogr.OFTInteger)
	dst_layer.CreateField(newField)
	#gdal.Polygonize(polygon_band, None, dst_layer, -1, ["value"], callback=None)
	gdal.Polygonize(polygon_band, None, dst_layer, 0, [], callback=None)
Exemple #21
0
def vectorize_raster(source, gdal_band_number, target_vector_layer_filename, layer_name, field_name_of_layer):
    import os
    if os.path.isfile(source):
        ds = get_dataset(source)
    else:
        #TODO: test if is dataset
        LOGGER.info('dataset')
    projection_reference = ds.GetProjection()
    data_layer, ds_layer=create_empty_layer(target_vector_layer_filename, layer_name, projection_reference)
    band = ds.GetRasterBand(gdal_band_number)
    field = ogr.FieldDefn(field_name_of_layer, ogr.OFTInteger)
    data_layer.CreateField(field)
    return gdal.Polygonize(band, None, data_layer, 0, [])
def polygonize_to_shp(tif_path, shp_path):
    tif_ds = gdal.Open(tif_path)
    srcband = tif_ds.GetRasterBand(1)
    maskband = srcband.GetMaskBand()
    drv = ogr.GetDriverByName('ESRI Shapefile')
    shp_ds = drv.CreateDataSource(shp_path)
    project = tif_ds.GetProjection()
    srs = osr.SpatialReference(wkt=project)
    dst_layername = 'out'
    dst_layer = shp_ds.CreateLayer(dst_layername, srs=srs)
    dst_fieldname = 'DN'
    fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger)
    dst_layer.CreateField(fd)
    gdal.Polygonize(srcband, maskband, dst_layer, 0)
Exemple #23
0
def make_polygon(infile, outfile, name):
    print("Make polygon", infile)
    #input tif file
    ds = gdal.Open(infile)
    tree_band = ds.GetRasterBand(1)
    polylayer = name
    drv = ogr.GetDriverByName("ESRI Shapefile")
    dst_ds = drv.CreateDataSource(outfile)
    dst_layer = dst_ds.CreateLayer(polylayer, srs=None)
    #Create New Field in output shapefile to assign value to
    newField = ogr.FieldDefn('Value', ogr.OFTInteger)
    dst_layer.CreateField(newField)
    gdal.Polygonize(tree_band, None, dst_layer, 0, [], callback=None)
    return outfile
Exemple #24
0
 def raster2shp(rasterfile,
                vectorshp,
                layername=None,
                fieldname=None,
                band_num=1,
                mask='default'):
     """Convert raster to ESRI shapefile"""
     FileClass.remove_files(vectorshp)
     FileClass.check_file_exists(rasterfile)
     # this allows GDAL to throw Python Exceptions
     gdal.UseExceptions()
     src_ds = gdal.Open(rasterfile)
     if src_ds is None:
         print('Unable to open %s' % rasterfile)
         sys.exit(1)
     try:
         srcband = src_ds.GetRasterBand(band_num)
     except RuntimeError as e:
         # for example, try GetRasterBand(10)
         print('Band ( %i ) not found, %s' % (band_num, e))
         sys.exit(1)
     if mask == 'default':
         maskband = srcband.GetMaskBand()
     elif mask is None or mask.upper() == 'NONE':
         maskband = None
     else:
         mask_ds = gdal.Open(mask)
         maskband = mask_ds.GetRasterBand(1)
     #  create output datasource
     if layername is None:
         layername = FileClass.get_core_name_without_suffix(rasterfile)
     drv = ogr_GetDriverByName(str('ESRI Shapefile'))
     dst_ds = drv.CreateDataSource(vectorshp)
     srs = None
     if src_ds.GetProjection() != '':
         srs = osr_SpatialReference()
         srs.ImportFromWkt(src_ds.GetProjection())
     dst_layer = dst_ds.CreateLayer(str(layername), srs=srs)
     if fieldname is None:
         fieldname = layername.upper()
     fd = ogr_FieldDefn(str(fieldname), OFTInteger)
     dst_layer.CreateField(fd)
     dst_field = 0
     result = gdal.Polygonize(srcband,
                              maskband,
                              dst_layer,
                              dst_field, ['8CONNECTED=8'],
                              callback=None)
     return result
Exemple #25
0
def gdal_polygonize(src_gdal, dst_layer, verbose=False):
    '''run gdal.Polygonize on src_gdal and add polygon to dst_layer'''

    src_ds = gdal.Open(src_gdal)
    if src_ds is not None:
        srcband = src_ds.GetRasterBand(1)

        if verbose: sys.stderr.write('geomods: polygonizing grid...')
        try:
            gdal.Polygonize(srcband, None, dst_layer, 0, [])
        except KeyboardInterrupt, e:
            sys.exit(1)
        if verbose: sys.stderr.write('ok\n')
        src_ds = srcband = None
        return (0)
Exemple #26
0
def vectorize_data():

    setup_env()

    temp_path = os.getenv("TEMP_PATH")

    filelist = create_filelist()

    print("Starting vectorization...")
    for file in tqdm(filelist, unit=" file"):
        file_split = file.split("/")
        date_time_obj = datetime.strptime(
            file_split[len(file_split)-1], 'RW_%Y%m%d-%H%M.asc')

        filename_input = temp_path + "/cropped/{}".format(
            date_time_obj.strftime("%Y%m%d-%H%M"))
        filename_output = temp_path + "/vectorized/{}".format(
            date_time_obj.strftime("%Y%m%d-%H%M"))

        source = gdal.Open(filename_input + ".tif")
        band = source.GetRasterBand(1)
        _ = band.ReadAsArray()

        driver = ogr.GetDriverByName("ESRI Shapefile")

        if os.path.exists(filename_output + ".shp"):
            driver.DeleteDataSource(filename_output + ".shp")

        target = driver.CreateDataSource(filename_output + ".shp")

        srs = osr.SpatialReference()
        srs.ImportFromProj4(
            "+proj=stere +lon_0=10.0 +lat_0=90.0 +lat_ts=60.0 +a=6370040 +b=6370040 +units=m")

        targetLayer = target.CreateLayer("radolan", srs=srs)
        targetField = ogr.FieldDefn("rain", ogr.OFTInteger)
        targetLayer.CreateField(targetField)

        gdal.Polygonize(band, None, targetLayer, 0, [], callback=None)

        target.Destroy()
        source = None
        _ = None

    print("Vectorization complete.")
def CreateGeoJSON(fn, cluster):
    memdrv = gdal.GetDriverByName('MEM')
    src_ds = memdrv.Create('', cluster.shape[1], cluster.shape[0], 1)
    src_ds.SetGeoTransform([0, 1, 0, 0, 0, 1])
    band = src_ds.GetRasterBand(1)
    band.WriteArray(cluster)
    dst_layername = "BuildingID"
    drv = ogr.GetDriverByName("geojson")

    if os.path.exists('./geojson/' + fn + dst_layername + ".geojson"):
        drv.DeleteDataSource('./geojson/' + fn + dst_layername + ".geojson")

    dst_ds = drv.CreateDataSource('./geojson/' + fn + dst_layername +
                                  ".geojson")
    dst_layer = dst_ds.CreateLayer(dst_layername, srs=None)
    dst_layer.CreateField(ogr.FieldDefn("DN", ogr.OFTInteger))
    gdal.Polygonize(band, None, dst_layer, 0, ['8CONNECTED=8'], callback=None)
    return
Exemple #28
0
def rainfall_raster_ranks(path_rain_frame, path_ranks):
    # Reads a raster of the rainfall fields and creates a raster with the ranks
    m, p, epsg = read_raster(path_rain_frame)
    rank = np.arange(1, m.size + 1)
    rank = rank.reshape(m.shape)
    save_array2raster(rank, p, path_ranks + '.tif', EPSG=int(epsg))
    # Creates a ranks polygon based on the raster ranks.
    src_ds = gdal.Open(path_ranks + '.tif')
    srcband = src_ds.GetRasterBand(1)
    #Create output datasource
    spatialReference = osgeo.osr.SpatialReference()
    spatialReference.ImportFromEPSG(int(epsg))
    dst_layername = path_ranks
    drv = ogr.GetDriverByName("ESRI Shapefile")
    dst_ds = drv.CreateDataSource(dst_layername + ".shp")
    dst_layer = dst_ds.CreateLayer(dst_layername, spatialReference)
    gdal.Polygonize(srcband, None, dst_layer, -1, [], callback=None)
    dst_ds.Destroy()
Exemple #29
0
def mask_to_polygon(tif_file, array, output_shp_file, field_name=None):
    """
    Takes a numpy array, creates a shape file polygon with projections and coordinates info from tif_file
    saving values to field_name attribute.
    :param tif_file: tif_file with projection info
    :param array: the array to turn into polygons
    :param output_shp_file: path to save the shapefile
    :param field_name: field name to save values from array
    :return:
    """
    driver = gdal.GetDriverByName('MEM')
    dataset = driver.Create('', array.shape[1], array.shape[0], 1,
                            gdal.GDT_Float32)
    dataset.GetRasterBand(1).WriteArray(array)
    original_data = gdal.Open(tif_file, gdalconst.GA_ReadOnly)
    geotrans = original_data.GetGeoTransform()
    proj = original_data.GetProjection()
    dataset.SetGeoTransform(geotrans)
    dataset.SetProjection(proj)
    original_data = None
    band = dataset.GetRasterBand(1)
    driver = ogr.GetDriverByName("ESRI Shapefile")
    outDatasource = driver.CreateDataSource(output_shp_file)
    outLayer = outDatasource.CreateLayer("polygonized", srs=None)
    if field_name is None:
        field_name = 'MyFLD'
    newField = ogr.FieldDefn(field_name, ogr.OFTInteger)
    outLayer.CreateField(newField)

    driver_mask = gdal.GetDriverByName('MEM')
    ds_mask = driver_mask.Create('', array.shape[1], array.shape[0], 1,
                                 gdal.GDT_Float32)
    ds_mask.SetGeoTransform(geotrans)
    ds_mask.SetProjection(proj)
    ds_mask_array = (array > 0).astype(np.int32)
    ds_mask.GetRasterBand(1).WriteArray(ds_mask_array)
    mask_band = ds_mask.GetRasterBand(1)

    gdal.Polygonize(band, mask_band, outLayer, 0, [], callback=None)
    outDatasource.Destroy()
    sourceRaster = None
    dataset.FlushCache()
    dataset = None
def poligonizza_raster(nomefile, nomeoutput):
    sourceRaster = gdal.Open(nomefile)  #/Users/glicciardi/Desktop/ndvi3.tif'
    band = sourceRaster.GetRasterBand(1)
    #bandArray = band.ReadAsArray()
    #outShapefile = "polygonized"
    srs = osr.SpatialReference()
    srs.ImportFromWkt(sourceRaster.GetProjectionRef())
    driver = ogr.GetDriverByName("ESRI Shapefile")
    if os.path.exists(nomeoutput):  #outShapefile+".shp"):
        driver.DeleteDataSource(nomeoutput)  #outShapefile+".shp")
    outDatasource = driver.CreateDataSource(nomeoutput)  #outShapefile+ ".shp")
    outLayer = outDatasource.CreateLayer("polygonized", srs=None)
    fd = ogr.FieldDefn("DN", ogr.OFTInteger)
    outLayer.CreateField(fd)
    dst_field = outLayer.GetLayerDefn().GetFieldIndex("DN")
    gdal.Polygonize(band, None, outLayer, dst_field, [], callback=None)
    #gdal.Polygonize( band, None, outLayer, -1, [], callback=None )
    outDatasource.Destroy()
    sourceRaster = None