- 本次使用的影像是某個(gè)地區(qū)的土地利用影像暮胧,該影像已經(jīng)處理過锐借,7個(gè)像素分別代表7種土地利用。
分兩步往衷,第一步使用某縣鄉(xiāng)的shp文件切割影像钞翔,獲取該縣鄉(xiāng)的土地利用影像(該縣鄉(xiāng)shp是影像區(qū)域的子集);
第二步統(tǒng)計(jì)切割后的影像席舍,各土地種類像元個(gè)數(shù)和每個(gè)像元的面積布轿,進(jìn)而獲取各土地利用的面積。
- 程序代碼如下
package com.aerors.etl.utils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.WarpOptions;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconst;
import org.gdal.ogr.ogr;
public class RasterClip {
public static void main(String[] args) {
gdal.AllRegister();
ogr.RegisterAll();
String inTiff = "E:\\data_sjy\\sjy_landuse\\qinghai2017";
String inShp = "E:\\data_sjy\\xiang_shp\\chengduoxianxiang.shp";
Dataset src = gdal.Open(inTiff);
//單個(gè)像元寬度来颤,高度和寬度一致
double[] geotran = src.GetGeoTransform();
System.out.println("geotran[1]:"+geotran[1]);
Dataset[] src_array = { src };
Vector<String> options = new Vector<>();
options.add("-of");
options.add("GTiff");
options.add("-cutline");
options.add(inShp);
options.add("-crop_to_cutline");
options.add("-dstalpha");
WarpOptions warpOptions = new WarpOptions(options);
Dataset warp = gdal.Warp("warp.vrt", src_array, warpOptions);
long startTime = System.currentTimeMillis();
//統(tǒng)計(jì)
int bandCount = warp.getRasterCount();
System.out.println("bandCount:"+bandCount);
int width = warp.GetRasterBand(1).getXSize();
int height = warp.GetRasterBand(1).getYSize();
int blockX = warp.GetRasterBand(1).GetBlockXSize();
int blockY = warp.GetRasterBand(1).GetBlockYSize();
System.out.println("blockX:" + blockX);
System.out.println("blockY:" + blockY);
//map存放土地類別和像元總個(gè)數(shù)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//逐行掃描統(tǒng)計(jì)
for(int i=0;i<height;i++) {
int[] lineBuffer = new int[width * bandCount];
warp.ReadRaster(0, 0, width, 1, width, 1,gdalconst.GDT_Int32, lineBuffer, new int[] {1});
//System.out.println(lineBuffer.length);
int lbefore = lineBuffer[0];
for(int j=0; j<lineBuffer.length;j++) {
if(lineBuffer[j] != lbefore) {
if(lineBuffer[j] != 0) {
if(map.containsKey(lineBuffer[j])){
map.put(lineBuffer[j], map.get(lineBuffer[j])+1);
}else {
map.put(lineBuffer[j], 1);
}
}
}
lbefore = lineBuffer[j];
}
}
//map存放土地類別和土地面積
Map<Integer, Double> areaMap = new HashMap<Integer, Double>();
Iterator<Entry<Integer, Integer>> mi = map.entrySet().iterator();
while(mi.hasNext()) {
Entry<Integer, Integer> element = mi.next();
double area = element.getValue()*geotran[1]*geotran[1];
areaMap.put(element.getKey(), area);
System.out.println("reulst area: "+element.getKey() +": "+area);
}
long endTime = System.currentTimeMillis();
System.out.println("dur:"+(endTime-startTime));
// Driver tiffDriver = gdal.GetDriverByName("GTiff");
// Dataset warp_out = tiffDriver.CreateCopy(outTiff, warp);
src.delete();
warp.delete();
// warp_out.delete();
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者