0

I am trying to code gdal_polygonize source.png -f "GeoJSON" destination.geojson with the java-bindings of gdal. I don't know how to make gdal.Polygonize(...) create the "DN"-Fields one obtains when you use gdal_polygonize. Here is my code so far:

public static void gdalPolygonize(String[] args){

    gdal.AllRegister();
    ogr.RegisterAll();
    args = gdal.GeneralCmdLineProcessor(args);

    Dataset hDataset = gdal.Open(args[0], gdalconstConstants.GA_ReadOnly);
    Band rasterBand = hDataset.GetRasterBand(1);
    Driver driver = ogr.GetDriverByName("GeoJSON");
    DataSource dataSource =  driver.CreateDataSource("C:\\Users\\User\\Desktop\\destination.geojson");
    Layer outputLayer =dataSource.CreateLayer("destination");
    gdal.Polygonize(rasterBand, null, outputLayer, 0);

}

the created polygons in the geojsonfiles look like this:

{ "type": "Feature", "properties": { }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 7858.0, 964.0 ], [ 7858.0, 965.0 ], [ 7859.0, 965.0 ], [ 7858.0, 964.0 ] ] ] } }

but they should look like this:

{ "type": "Feature", "properties": {"DN": 2}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 7858.0, 964.0 ], [ 7858.0, 965.0 ], [ 7859.0, 965.0 ], [ 7858.0, 964.0 ] ] ] } }

So the difference it the "DN" in "properties".

1 Answer 1

2

I found the answer. I had to create a FieldDefn See code:

public static void gdalPolygonize(String[] args){

    gdal.AllRegister();
    ogr.RegisterAll();
    args = gdal.GeneralCmdLineProcessor(args);

    Dataset hDataset = gdal.Open(args[0], gdalconstConstants.GA_ReadOnly);
    Band rasterBand = hDataset.GetRasterBand(1);
    Driver driver = ogr.GetDriverByName("GeoJSON");
    DataSource dataSource =  driver.CreateDataSource("C:\\Users\\User\\Desktop\\destination.geojson");
    Layer outputLayer =dataSource.CreateLayer("destination");
    FieldDefn field_def = new FieldDefn("DN",4);
    outputLayer.CreateField(field_def);
    gdal.Polygonize(rasterBand, null, outputLayer, 0);

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.