载入栅格
首先加载需要矢量化的栅格数据集,读取栅格数据集的波段信息和空间信息。波段信息是矢量化的依据,读取空间信息则是为了保证创建的矢量数据集和栅格数据集的坐标系保持一致。注意:栅格数据集如果没有空间信息,则矢量化的结果会出现上下反转的现象。
伪代码:
Dataset dataset = gdal.Open(inRaster, gdalconstConstants.GA_ReadOnly);
Band band = dataset.GetRasterBand(1);//栅格转矢量需要的波段信息
SpatialReference prj = new SpatialReference();
if (!dataset.GetProjectionRef().isEmpty()) {
prj.ImportFromWkt(dataset.GetProjectionRef());//栅格数据的坐标系作为矢量化后的坐标系
}
创建矢量
创建一个新的、空的矢量数据集来接收栅格矢量化后的数据:
伪代码:
String fileName = outShp.substring(outShp.lastIndexOf("\\") + 1);//带后缀的文件名
String name = fileName.substring(0, fileName.lastIndexOf("."));//不带后缀
Layer layer = ShpProcessing.createLayer("ESRI Shapefile", outShp, name, prj);
FieldDefn field = new FieldDefn("value", ogr.OFTInteger);//创建一个字段用来存储栅格的像素值
layer.CreateField(field, 1);
矢量化
执行gdal内置的的矢量化方法:gdal.Polygonize()
伪代码:
gdal.Polygonize(band, null, layer, 0);
layer.SyncToDisk();
完整代码
/**
* 栅格矢量化
* @param inRaster:输入的栅格数据的文件路径
* @param outShp:输出的矢量数据保存位置
*/
public static void rasterToShp(String inRaster, String outShp) {
//载入栅格,读取相关信息
Dataset dataset = gdal.Open(inRaster, gdalconstConstants.GA_ReadOnly);
Band band = dataset.GetRasterBand(1);//栅格转矢量需要的波段信息
SpatialReference prj = new SpatialReference();
if (!dataset.GetProjectionRef().isEmpty()) {
prj.ImportFromWkt(dataset.GetProjectionRef());//栅格数据的坐标系作为矢量化后的坐标系
}
//创建输出矢量
String fileName = outShp.substring(outShp.lastIndexOf("\\") + 1);//带后缀的文件名
String name = fileName.substring(0, fileName.lastIndexOf("."));//不带后缀
Layer layer = ShpProcessing.createLayer("ESRI Shapefile", outShp, name, prj);
FieldDefn field = new FieldDefn("value", ogr.OFTInteger);//创建一个字段用来存储栅格的像素值
layer.CreateField(field, 1);
//矢量化
gdal.Polygonize(band, null, layer, 0);
layer.SyncToDisk();
}