dem数据矢量化,并获取矢量化后每个点的海拔值存入矢量文件,Java代码
时间: 2024-05-04 14:15:21 浏览: 211
DEM数据加载的实现代码
3星 · 编辑精心推荐
以下是使用Java进行DEM数据矢量化并获取每个点的海拔值存入矢量文件的示例代码:
```java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Driver;
import org.gdal.ogr.Feature;
import org.gdal.ogr.FieldDefn;
import org.gdal.ogr.Geometry;
import org.gdal.ogr.Layer;
import org.gdal.ogr.ogr;
public class DEMtoVector {
public static void main(String[] args) {
// Load GDAL library
gdal.AllRegister();
// Input DEM file
String demFile = "inputDEM.tif";
// Output vector file
String vectorFile = "outputVector.shp";
// Open DEM file
Dataset demDataset = gdal.Open(demFile, gdalconstConstants.GA_ReadOnly);
// Get DEM metadata
int width = demDataset.getRasterXSize();
int height = demDataset.getRasterYSize();
double[] geotransform = demDataset.GetGeoTransform();
// Create output vector file
Driver driver = ogr.GetDriverByName("ESRI Shapefile");
File vectorFileObj = new File(vectorFile);
if (vectorFileObj.exists()) {
driver.DeleteDataSource(vectorFile);
}
DataSource vectorDataset = driver.CreateDataSource(vectorFile);
// Create output layer
Layer vectorLayer = vectorDataset.CreateLayer("elevation", null, ogr.wkbPoint, null);
// Add elevation field to layer
FieldDefn elevationField = new FieldDefn("elevation", ogr.OFTReal);
vectorLayer.CreateField(elevationField);
// Loop through DEM pixels and create point features for each pixel
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// Get elevation value for pixel
double[] pixelValue = new double[1];
demDataset.GetRasterBand(1).RasterIO(gdalconstConstants.GF_Read, x, y, 1, 1, pixelValue, 1, 1, gdalconstConstants.GDT_Float64, 0, 0);
// Convert pixel coordinates to map coordinates
double xMap = geotransform[0] + x * geotransform[1] + y * geotransform[2];
double yMap = geotransform[3] + x * geotransform[4] + y * geotransform[5];
// Create point geometry
Geometry pointGeom = ogr.CreateGeometryFromWkt("POINT(" + xMap + " " + yMap + ")");
// Create feature and set elevation field value
Feature pointFeature = new Feature(vectorLayer.GetLayerDefn());
pointFeature.SetGeometry(pointGeom);
pointFeature.SetField("elevation", pixelValue[0]);
// Add feature to layer
vectorLayer.CreateFeature(pointFeature);
pointFeature.delete();
pointGeom.delete();
}
}
// Clean up
vectorDataset.delete();
demDataset.delete();
ogr.RegisterAll();
}
}
```
在代码中,我们首先加载了GDAL库,然后指定了输入DEM文件和输出矢量文件的路径。接着,我们打开了DEM文件并获取了其元数据。然后,我们创建了输出矢量文件和输出图层,并添加了一个海拔字段到图层中。接下来,我们循环遍历DEM像素并为每个像素创建一个点特征。我们获取了像素的海拔值,并将像素坐标转换为地图坐标。然后,我们创建了一个点几何体并将其添加到特征中。最后,我们将特征添加到图层中。在代码的结尾,我们清理了GDAL资源并完成了DEM数据矢量化过程。
阅读全文