package com.se.nsl.utils;
|
|
import org.gdal.gdal.Dataset;
|
import org.gdal.gdal.Driver;
|
import org.gdal.gdal.gdal;
|
import org.gdal.gdalconst.gdalconstConstants;
|
|
public class ZarrReader {
|
|
static {
|
// 注册GDAL驱动
|
try {
|
gdal.AllRegister();
|
} catch (Exception e) {
|
System.err.println("GDAL驱动注册失败: " + e.getMessage());
|
}
|
}
|
|
/**
|
* 读取Zarr数据集并打印基本信息
|
* @param zarrPath Zarr数据集路径(本地路径或URL)
|
*/
|
public static void readZarr(String zarrPath) {
|
// 打开Zarr数据集
|
Driver driver = gdal.GetDriverByName("Zarr");
|
if (driver == null) {
|
System.out.println("zarr驱动不可用");
|
}
|
Dataset dataset = gdal.Open(zarrPath, gdalconstConstants.GA_ReadOnly);
|
|
|
if (dataset == null) {
|
System.err.println("无法打开Zarr数据集: " + zarrPath);
|
System.err.println(gdal.GetLastErrorMsg());
|
return;
|
}
|
|
try {
|
// 打印数据集基本信息
|
System.out.println("数据集信息:");
|
System.out.println(" 驱动: " + dataset.GetDriver().getShortName());
|
System.out.println(" 宽度: " + dataset.GetRasterXSize() + " 像素");
|
System.out.println(" 高度: " + dataset.GetRasterYSize() + " 像素");
|
System.out.println(" 波段数: " + dataset.GetRasterCount());
|
|
// 获取地理变换参数
|
double[] geoTransform = dataset.GetGeoTransform();
|
if (geoTransform != null && geoTransform.length >= 6) {
|
System.out.println(" 地理变换参数:");
|
System.out.printf(" 左上角X: %.6f%n", geoTransform[0]);
|
System.out.printf(" 左上角Y: %.6f%n", geoTransform[3]);
|
System.out.printf(" X方向分辨率: %.6f%n", geoTransform[1]);
|
System.out.printf(" Y方向分辨率: %.6f%n", geoTransform[5]);
|
}
|
|
// 获取投影信息
|
String projection = dataset.GetProjection();
|
if (projection != null && !projection.isEmpty()) {
|
System.out.println(" 投影信息: " + projection.substring(0, Math.min(100, projection.length())) + "...");
|
}
|
|
// 读取第一个波段的数据
|
if (dataset.GetRasterCount() > 0) {
|
int width = dataset.GetRasterXSize();
|
int height = dataset.GetRasterYSize();
|
float[] buffer = new float[width * height];
|
|
// 读取波段数据
|
dataset.GetRasterBand(1).ReadRaster(0, 0, width, height, buffer);
|
|
// 统计基本信息
|
float min = Float.MAX_VALUE;
|
float max = Float.MIN_VALUE;
|
float sum = 0;
|
int validCount = 0;
|
|
for (float value : buffer) {
|
if (!Float.isNaN(value) && !Float.isInfinite(value)) {
|
min = Math.min(min, value);
|
max = Math.max(max, value);
|
sum += value;
|
validCount++;
|
}
|
}
|
|
if (validCount > 0) {
|
float mean = sum / validCount;
|
System.out.printf(" 第一个波段统计信息: 最小值=%.2f, 最大值=%.2f, 平均值=%.2f%n", min, max, mean);
|
}
|
}
|
|
} catch (Exception e) {
|
System.err.println("读取Zarr数据时发生错误: " + e.getMessage());
|
e.printStackTrace();
|
} finally {
|
// 释放资源
|
if (dataset != null) {
|
dataset.delete();
|
}
|
}
|
}
|
|
public static void main(String[] args) {
|
// 示例Zarr数据集路径 - 请替换为实际路径
|
// String zarrPath = "C:\\Users\\Deng\\Desktop\\just_test\\result.zarr";
|
String zarrPath = "D:\\other\\simu\\uwsolver\\20250516174452\\result.zarr";
|
|
// 读取并打印Zarr信息
|
readZarr(zarrPath);
|
|
}
|
}
|