Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions packages/geotiff/src/gdal-metadata.ts
Original file line number Diff line number Diff line change
@@ -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<number, BandStatistics>;
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<number, BandStatistics>();
const offsets = Array<number>(count).fill(0);
const scales = Array<number>(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 };
}
41 changes: 41 additions & 0 deletions packages/geotiff/src/geotiff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand All @@ -66,6 +71,7 @@ export class GeoTIFF {
overviews: Overview[],
cachedTags: CachedTags,
dataSource: Pick<Source, "fetch">,
gdalMetadata: GDALMetadata | null,
) {
this.tiff = tiff;
this.image = image;
Expand All @@ -74,6 +80,7 @@ export class GeoTIFF {
this.overviews = overviews;
this.cachedTags = cachedTags;
this.dataSource = dataSource;
this.gdalMetadata = gdalMetadata;
}

/**
Expand Down Expand Up @@ -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.
Expand All @@ -166,6 +176,7 @@ export class GeoTIFF {
[],
cachedTags,
dataSource,
gdalMetadata,
);

const overviews: Overview[] = dataEntries.map(([key, dataImage]) => {
Expand Down Expand Up @@ -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<number, BandStatistics> | 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<number>(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<number>(this.count).fill(1);
}

/** Number of bands (samples per pixel). */
get count(): number {
return this.image.value(TiffTag.SamplesPerPixel) ?? 1;
Expand Down
47 changes: 47 additions & 0 deletions packages/geotiff/tests/gdal-metadata.test.ts
Original file line number Diff line number Diff line change
@@ -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]);
});
});
2 changes: 1 addition & 1 deletion packages/geotiff/tests/integration-rasterio.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Loading