SPB Git

Repository Public

geotiff_info.py 8.6 KB 186 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Cosmos10# File             : DataPipeline/textures/tools/geotiff_info.py11# Description      : Reads the georeferencing of a (Big)TIFF without12#                    third-party libraries: image size, pixel scale, tie point,13#                    GDAL metadata/nodata and the projection parameters stored14#                    in the GeoKey directory (central meridian, radii). Used to15#                    establish the longitude convention of USGS mosaics.16# Module           : DataPipeline17# Repository       : https://git.spboucher.ai/orix-cosmos18# Project Website  : https://www.orixlab.dev19# Created          : 2026-11-2420# Last Modified    : 2026-11-2421#22# =============================================================================23# AUTHOR & PROFESSIONAL AFFILIATION24# =============================================================================25#26# Author           : Simon-Pierre Boucher27# Position         : Professor of Finance28# Institution      : Université du Québec en Outaouais (UQO)29# Department       : Département des sciences administratives30# Organization     : SP Boucher31#32# Website          : https://spboucher.ai33# Git              : https://git.spboucher.ai34#35# =============================================================================36# OFFICIAL CONTACT DIRECTORY37# =============================================================================38#39# General          : info@spboucher.ai40# Professional     : contact@spboucher.ai41# Direct           : simon@spboucher.ai42# Research         : research@spboucher.ai43# Development      : dev@spboucher.ai44# Support          : support@spboucher.ai45# Security/Admin   : admin@spboucher.ai46# Notifications    : notifications@spboucher.ai47#48# Preferred Contact: support@spboucher.ai49#50# =============================================================================51# COPYRIGHT & INTELLECTUAL PROPERTY52# =============================================================================53#54# Copyright (c) 202655# Simon-Pierre Boucher56#57# All rights reserved where applicable.58#59# This file is governed by the applicable project license,60# copyright notices, institutional agreements and relevant law.61#62# Unless expressly authorized by the applicable license or63# rights holder, copying, redistribution, sublicensing,64# publication and commercial exploitation are not permitted.65#66# Existing third-party rights and notices remain unaffected.67#68# =============================================================================69# CONFIDENTIALITY & SECURITY70# =============================================================================71#72# Classification   : Public73# Distribution     : Public repository; use is governed by the project license74# Security Contact : admin@spboucher.ai75#76# Access to this source does not independently grant permission77# to redistribute or disclose confidential materials.78#79# Do not embed credentials, private keys, access tokens,80# certificates or confidential personal information.81#82# =============================================================================83# LICENSE & MAINTENANCE84# =============================================================================85#86# License          : None specified (no license file in this repository)87# Maintainer       : Simon-Pierre Boucher88# Technical Contact: dev@spboucher.ai89#90# =============================================================================91# END OF SP BOUCHER SOURCE HEADER92# =============================================================================9394"""Usage: geotiff_info.py <file.tif> [...]   (prints one JSON object per file)"""95import json96import struct97import sys9899TYPES = {1: "B", 2: "c", 3: "H", 4: "I", 5: "II", 11: "f", 12: "d", 16: "Q", 6: "b", 8: "h", 9: "i", 13: "I", 17: "q", 18: "Q"}100GEOKEYS = {1024: "GTModelType", 1025: "GTRasterType", 2048: "GeographicType", 2054: "GeogAngularUnits", 2057: "GeogSemiMajorAxis",101           2058: "GeogSemiMinorAxis", 2061: "GeogPrimeMeridianLong", 3072: "ProjectedCSType", 3074: "Projection", 3075: "ProjCoordTrans",102           3076: "ProjLinearUnits", 3078: "ProjStdParallel1", 3080: "ProjNatOriginLong", 3081: "ProjNatOriginLat", 3082: "ProjFalseEasting",103           3083: "ProjFalseNorthing", 3088: "ProjCenterLong", 3089: "ProjCenterLat", 1026: "GTCitation", 2049: "GeogCitation", 3073: "PCSCitation"}104105106def read(path):107    with open(path, "rb") as f:108        head = f.read(16)109        e = "<" if head[:2] == b"II" else ">"110        magic = struct.unpack(e + "H", head[2:4])[0]111        big = magic == 43112        if big:113            offset = struct.unpack(e + "Q", head[8:16])[0]114        else:115            offset = struct.unpack(e + "I", head[4:8])[0]116        f.seek(offset)117        n = struct.unpack(e + ("Q" if big else "H"), f.read(8 if big else 2))[0]118        entry = 20 if big else 12119        raw = f.read(n * entry)120        tags = {}121        for i in range(n):122            rec = raw[i * entry:(i + 1) * entry]123            tag, typ = struct.unpack(e + "HH", rec[:4])124            count = struct.unpack(e + ("Q" if big else "I"), rec[4:(12 if big else 8)])[0]125            fmt = TYPES.get(typ)126            if fmt is None:127                continue128            size = struct.calcsize("=" + fmt) * count129            inline = rec[(12 if big else 8):]130            if size <= len(inline):131                data = inline[:size]132            else:133                pos = struct.unpack(e + ("Q" if big else "I"), inline[:(8 if big else 4)])[0]134                here = f.tell()135                f.seek(pos)136                data = f.read(size)137                f.seek(here)138            if typ == 2:139                tags[tag] = data.decode("latin-1").rstrip("\x00")140            else:141                per = len(fmt)142                vals = struct.unpack(e + fmt * count, data)143                if typ == 5:144                    vals = tuple(vals[j] / vals[j + 1] if vals[j + 1] else 0 for j in range(0, len(vals), 2))145                tags[tag] = vals146                _ = per147    out = {"file": path, "bigtiff": big, "width": tags.get(256, [None])[0], "height": tags.get(257, [None])[0],148           "bitsPerSample": list(tags.get(258, [])), "samplesPerPixel": tags.get(277, [1])[0], "compression": tags.get(259, [None])[0],149           "pixelScale": list(tags.get(33550, [])), "tiePoint": list(tags.get(33922, [])), "nodata": tags.get(42113)}150    keys = tags.get(34735)151    if keys:152        doubles = tags.get(34736, ())153        ascii_params = tags.get(34737, "")154        geo = {}155        for i in range(1, keys[3] + 1):156            key, loc, count, value = keys[i * 4:i * 4 + 4]157            name = GEOKEYS.get(key, str(key))158            if loc == 0:159                geo[name] = value160            elif loc == 34736:161                geo[name] = doubles[value] if count == 1 else list(doubles[value:value + count])162            elif loc == 34737:163                geo[name] = ascii_params[value:value + count].rstrip("|")164        out["geokeys"] = geo165        scale, tie = out["pixelScale"], out["tiePoint"]166        radius = geo.get("GeogSemiMajorAxis")167        if scale and tie and radius and geo.get("GTModelType") == 1:168            import math169            centre = geo.get("ProjCenterLong", geo.get("ProjNatOriginLong", 0.0))170            cos_std = math.cos(math.radians(geo.get("ProjStdParallel1", 0.0) or 0.0))171            deg_per_m = 180.0 / (math.pi * radius * cos_std)172            left = centre + (tie[3] - tie[0] * scale[0]) * deg_per_m173            out["derived"] = {"centralMeridianDeg": centre, "leftEdgeEastLongitudeDeg": round(left, 4),174                              "rightEdgeEastLongitudeDeg": round(left + out["width"] * scale[0] * deg_per_m, 4),175                              "topLatitudeDeg": round((tie[4] + tie[1] * scale[1]) * 180.0 / (math.pi * radius), 4),176                              "bottomLatitudeDeg": round((tie[4] - (out["height"] - tie[1]) * scale[1]) * 180.0 / (math.pi * radius), 4)}177        elif scale and tie and geo.get("GTModelType") == 2:178            out["derived"] = {"leftEdgeEastLongitudeDeg": tie[3] - tie[0] * scale[0], "rightEdgeEastLongitudeDeg": tie[3] + (out["width"] - tie[0]) * scale[0],179                              "topLatitudeDeg": tie[4] + tie[1] * scale[1], "bottomLatitudeDeg": tie[4] - (out["height"] - tie[1]) * scale[1]}180    return out181182183if __name__ == "__main__":184    for p in sys.argv[1:]:185        print(json.dumps(read(p)))186
Files main
Menu

Theme