注:DEM坡度算法参考这里,具体使用geoTools实现
1.计算指定像素坐标点的坡度
public float calcSlope(int cellX, int cellY, PlanarImage image) throws IOException {
DecimalFormat df = new DecimalFormat("#.0000");
final int[] dest = null;
int e = image.getTile(image.XToTileX(cellX), image.YToTileY(cellY)).getPixel(cellX, cellY, dest)[0];
int e1 = image.getTile(image.XToTileX(cellX - 1), image.YToTileY(cellY)).getPixel(cellX - 1, cellY, dest)[0];
int e2 = image.getTile(image.XToTileX(cellX), image.YToTileY(cellY - 1)).getPixel(cellX, cellY - 1, dest)[0];
int e3 = image.getTile(image.XToTileX(cellX + 1), image.YToTileY(cellY)).getPixel(cellX + 1, cellY, dest)[0];
int e4 = image.getTile(image.XToTileX(cellX), image.YToTileY(cellY + 1)).getPixel(cellX, cellY + 1, dest)[0];
int e5 = image.getTile(image.XToTileX(cellX - 1), image.YToTileY(cellY - 1)).getPixel(cellX - 1, cellY - 1,
dest)[0];
int e6 = image.getTile(image.XToTileX(cellX + 1), image.YToTileY(cellY - 1)).getPixel(cellX + 1, cellY - 1,
dest)[0];
int e7 = image.getTile(image.XToTileX(cellX + 1), image.YToTileY(cellY + 1)).getPixel(cellX + 1, cellY + 1,
dest)[0];
int e8 = image.getTile(image.XToTileX(cellX - 1), image.YToTileY(cellY + 1)).getPixel(cellX - 1, cellY + 1,
dest)[0];
double slopeWE = ((e8 + 2 * e1 + e5) - (e7 + 2 * e3 + e6)) / (8 * 2041.823085);// 东西方向坡度
double slopeNW = ((e7 + 2 * e4 + e8) - (e6 + 2 * e2 + e5)) / (8 * 2041.823085);// 南北方向坡度
double slope = 100*(Math.sqrt(Math.pow(slopeWE, 2) + Math.pow(slopeNW, 2)));
return Float.parseFloat(df.format(slope));
}
2.DEM数据测试用例
@Test
public void testCalcSlope() throws NoSuchAuthorityCodeException, FactoryException, IOException {
String path = "D:\\workData\\geotiff\\testTiff.tif";
String outputPath = "D:\\workData\\geotiff\\output.tif";
File file = new File(path);
// 设置tiff影像默认设置
Hints tiffHints = new Hints();
tiffHints.add(new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
// 默认坐标系EPSG:3857
// tiffHints.add(new Hints(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, CRS.decode("EPSG:4326")));
tiffHints.add(new Hints(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, DefaultGeographicCRS.WGS84));
GeoTiffReader reader = new GeoTiffReader(file, tiffHints);
GridCoverage2D coverage = reader.read(null);
Envelope env = coverage.getEnvelope();
PlanarImage image = (PlanarImage) coverage.getRenderedImage();
int width = image.getWidth(); // Image Width
int height = image.getHeight(); // Image Height
// 计算每个栅格的坡度
float[][] slopeData = new float[height][width];
for (int i = 1; i < height + 1; i++) {
for (int j = 1; j < width + 1; j++) {
float slope = SlopeUtil.INSTANCE.calcSlope(j, i, image);
slopeData[i - 1][j - 1] = slope;
}
}
GridCoverageFactory factory = new GridCoverageFactory();
GridCoverage2D outputCoverage = factory.create("test", slopeData, env);
GeoTiffWriter writer = new GeoTiffWriter(new File(outputPath));
writer.write(outputCoverage, null);
writer.dispose();
}