GDAL可以支持多种影像格式,而OpenCV则可以对影像进行多种操作处理,所以将GDAL与OpenCV结合可以增强影像处理。虽然OpenCV可以读取tif等多种格式,但是在Java中涉及到读取hadoop的value值,读取内存中的影像数据GDAL仍然具有优势。所以本文给出Java操作GDAL读取本地图像、内存中图像的代码。作者本身利用以下代码在hadoop的map中读取value(存储的三波段遥感影像),转换成Mat格式,并使用OpenCV-2.4.9进行meanshift分割。
//使用OpenCV for Java
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//使用GDAL读取value中的遥感影像
byte[] bytes=value.getBytes();
gdal.AllRegister();
String memFileName="/vsimem/inmenfile";
gdal.FileFromMemBuffer(memFileName, bytes);
Dataset ds=gdal.Open(memFileName, gdalconstConstants.GA_ReadOnly);
//判断是否非空
if(ds==null||ds.GetRasterCount()==0){
return;
}
int xSize=ds.getRasterXSize();
int ySize=ds.getRasterYSize();
byte[] dataArrayR = new byte[xSize*ySize];
byte[] dataArrayG = new byte[xSize*ySize];
byte[] dataArrayB = new byte[xSize*ySize];
int[] bandR=new int[]{1};
int[] bandG=new int[]{2};
int[] bandB=new int[]{3};
int dataType = ds.GetRasterBand(1).GetRasterDataType();
ds.ReadRaster(0, 0, xSize, ySize, xSize, ySize, dataType, dataArrayR, bandR, 0);
ds.ReadRaster(0, 0, xSize, ySize, xSize, ySize, dataType, dataArrayG, bandG, 0);
ds.ReadRaster(0, 0, xSize, ySize, xSize, ySize, dataType, dataArrayB, bandB, 0);
//GDAL to Mat
Mat originalImage=new Mat(ySize, xSize, CvType.CV_8UC3);
for(int j=0;j
如果要读取本地文件则更为简单,读取使用以下代码:
String INPUT_PATH="/home/hadoop/Desktop/testTIF";
//使用OpenCV for Java
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//注册GDAL
gdal.AllRegister();
//支持中文路径
gdal.SetConfigOption("gdal_FILENAME_IS_UTF8", "YES");
//只读方式读取数据
Dataset ds=gdal.Open(INPUT_PATH,gdalconstConstants.GA_ReadOnly);
//判断是否非空
if(ds==null||ds.GetRasterCount()==0){
return;
}
int xSize=ds.getRasterXSize();
int ySize=ds.getRasterYSize();
byte[] dataArrayR = new byte[xSize*ySize];
byte[] dataArrayG = new byte[xSize*ySize];
byte[] dataArrayB = new byte[xSize*ySize];
int[] bandR=new int[]{1};
int[] bandG=new int[]{2};
int[] bandB=new int[]{3};
int dataType = ds.GetRasterBand(1).GetRasterDataType();
ds.ReadRaster(0, 0, xSize, ySize, xSize, ySize, dataType, dataArrayR, bandR, 0);
ds.ReadRaster(0, 0, xSize, ySize, xSize, ySize, dataType, dataArrayG, bandG, 0);
ds.ReadRaster(0, 0, xSize, ySize, xSize, ySize, dataType, dataArrayB, bandB, 0);
//GDAL to Mat
Mat originalImage=new Mat(ySize, xSize, CvType.CV_8UC3);
for(int j=0;j