diff --git a/packages/geotiff/src/gdal-metadata.ts b/packages/geotiff/src/gdal-metadata.ts new file mode 100644 index 00000000..e49b374c --- /dev/null +++ b/packages/geotiff/src/gdal-metadata.ts @@ -0,0 +1,83 @@ +export type BandStatistics = { + max: number | null; + min: number | null; + mean: number | null; + std: number | null; + validPercent: number | null; +}; + +export type GDALMetadata = { + /** Mapping of 1-based band index to statistics. */ + bandStatistics: Map; + offsets: number[]; + scales: number[]; +}; + +export function parseGDALMetadata( + gdalMetadata: string | null | undefined, + { count }: { count: number }, +): GDALMetadata | null { + if (gdalMetadata == null) return null; + + const parser = new DOMParser(); + const doc = parser.parseFromString(gdalMetadata, "text/xml"); + const root = doc.documentElement; + + if (root.tagName !== "GDALMetadata") { + throw new Error("Not a GDALMetadata XML block"); + } + + const bandStatistics = new Map(); + const offsets = Array(count).fill(0); + const scales = Array(count).fill(1); + + const getOrCreateBand = (sample: string): BandStatistics => { + const idx = parseInt(sample, 10) + 1; // 1-based + if (!bandStatistics.has(idx)) { + bandStatistics.set(idx, { + max: null, + min: null, + mean: null, + std: null, + validPercent: null, + }); + } + return bandStatistics.get(idx)!; + }; + + for (const elem of Array.from(root.querySelectorAll("Item"))) { + const name = elem.getAttribute("name"); + const sample = elem.getAttribute("sample"); + const text = elem.textContent ?? ""; + + if (sample === null) { + continue; + } + + switch (name) { + case "STATISTICS_MAXIMUM": + getOrCreateBand(sample).max = parseFloat(text); + break; + case "STATISTICS_MEAN": + getOrCreateBand(sample).mean = parseFloat(text); + break; + case "STATISTICS_MINIMUM": + getOrCreateBand(sample).min = parseFloat(text); + break; + case "STATISTICS_STDDEV": + getOrCreateBand(sample).std = parseFloat(text); + break; + case "STATISTICS_VALID_PERCENT": + getOrCreateBand(sample).validPercent = parseFloat(text); + break; + case "OFFSET": + offsets[parseInt(sample, 10)] = parseFloat(text); + break; + case "SCALE": + scales[parseInt(sample, 10)] = parseFloat(text); + break; + } + } + + return { bandStatistics, offsets, scales }; +} diff --git a/packages/geotiff/src/geotiff.ts b/packages/geotiff/src/geotiff.ts index a87e7f79..96d4725c 100644 --- a/packages/geotiff/src/geotiff.ts +++ b/packages/geotiff/src/geotiff.ts @@ -8,6 +8,8 @@ import type { Affine } from "@developmentseed/affine"; import type { ProjJson } from "./crs.js"; import { crsFromGeoKeys } from "./crs.js"; import { fetchTile } from "./fetch.js"; +import type { BandStatistics, GDALMetadata } from "./gdal-metadata.js"; +import { parseGDALMetadata } from "./gdal-metadata.js"; import type { CachedTags, GeoKeyDirectory } from "./ifd.js"; import { extractGeoKeyDirectory, prefetchTags } from "./ifd.js"; import { Overview } from "./overview.js"; @@ -58,6 +60,9 @@ export class GeoTIFF { /** The GeoKeyDirectory of the primary IFD. */ readonly gkd: GeoKeyDirectory; + /** Parsed GDALMetadata tag, if present. */ + readonly gdalMetadata: GDALMetadata | null; + private constructor( tiff: Tiff, image: TiffImage, @@ -66,6 +71,7 @@ export class GeoTIFF { overviews: Overview[], cachedTags: CachedTags, dataSource: Pick, + gdalMetadata: GDALMetadata | null, ) { this.tiff = tiff; this.image = image; @@ -74,6 +80,7 @@ export class GeoTIFF { this.overviews = overviews; this.cachedTags = cachedTags; this.dataSource = dataSource; + this.gdalMetadata = gdalMetadata; } /** @@ -155,6 +162,9 @@ export class GeoTIFF { }); const cachedTags = await prefetchTags(primaryImage); + const gdalMetadata = parseGDALMetadata(cachedTags.gdalMetadata, { + count: cachedTags.samplesPerPixel, + }); // Two-phase construction: create the GeoTIFF first (with empty overviews), // then build Overviews that reference back to it. @@ -166,6 +176,7 @@ export class GeoTIFF { [], cachedTags, dataSource, + gdalMetadata, ); const overviews: Overview[] = dataEntries.map(([key, dataImage]) => { @@ -284,6 +295,36 @@ export class GeoTIFF { return this.image.isTiled(); } + /** + * The pre-existing statistics for each band, if available. + * + * Extracted from the GDALMetadata TIFF tag; never computed on demand. + * Keys are **1-based** band indices to match GDAL's convention. + * Returns null if no statistics are stored in the file. + */ + get storedStats(): ReadonlyMap | null { + const stats = this.gdalMetadata?.bandStatistics; + return stats && stats.size > 0 ? stats : null; + } + + /** + * The offset for each band (0-indexed), defaulting to 0. + * + * Extracted from the GDALMetadata TIFF tag. + */ + get offsets(): number[] { + return this.gdalMetadata?.offsets ?? Array(this.count).fill(0); + } + + /** + * The scale for each band (0-indexed), defaulting to 1. + * + * Extracted from the GDALMetadata TIFF tag. + */ + get scales(): number[] { + return this.gdalMetadata?.scales ?? Array(this.count).fill(1); + } + /** Number of bands (samples per pixel). */ get count(): number { return this.image.value(TiffTag.SamplesPerPixel) ?? 1; diff --git a/packages/geotiff/tests/gdal-metadata.test.ts b/packages/geotiff/tests/gdal-metadata.test.ts new file mode 100644 index 00000000..3a158e0d --- /dev/null +++ b/packages/geotiff/tests/gdal-metadata.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { loadGeoTIFF } from "./helpers.js"; + +describe("test gdal metadata", () => { + it("parses correct stats", async () => { + const geotiff = await loadGeoTIFF("cog_rgb_with_stats", "rio-tiler"); + const expected = new Map([ + [ + 1, + { + max: 254, + min: 0, + mean: 99.615906635455, + std: 55.811140352764, + validPercent: 100, + }, + ], + [ + 2, + { + max: 254, + min: 0, + mean: 108.65261771856, + std: 50.561053632253, + validPercent: 100, + }, + ], + [ + 3, + { + max: 252, + min: 0, + mean: 110.68376924462, + std: 38.462500582021, + validPercent: 100, + }, + ], + ]); + expect(geotiff.storedStats).toEqual(expected); + }); + + it("parses correct scales and offsets", async () => { + const geotiff = await loadGeoTIFF("uint16_1band_scale_offset", "rasterio"); + expect(geotiff.scales).toEqual([0.01]); + expect(geotiff.offsets).toEqual([100]); + }); +}); diff --git a/packages/geotiff/tests/integration-rasterio.test.ts b/packages/geotiff/tests/integration-rasterio.test.ts index eaee3d34..a7201e91 100644 --- a/packages/geotiff/tests/integration-rasterio.test.ts +++ b/packages/geotiff/tests/integration-rasterio.test.ts @@ -9,10 +9,10 @@ import assert from "node:assert"; import { readFile } from "node:fs/promises"; import { TiffTag } from "@cogeotiff/core"; +import type { GeoTIFF } from "@developmentseed/geotiff"; import { beforeAll, describe, expect, it } from "vitest"; import type { RasterArray, RasterTypedArray } from "../src/array.js"; import { toBandSeparate } from "../src/array.js"; -import type { GeoTIFF } from "../src/geotiff.js"; import { fixturePath, loadGeoTIFF } from "./helpers.js"; import type { NPYTile } from "./utils/parse-npy.js"; import { parseNPY } from "./utils/parse-npy.js";