Skip to content

georeader.save

This module provides functions to save GeoTensor and other geospatial data to GeoTIFF files, including Cloud Optimized GeoTIFF (COG) format.

Overview

The save module supports:

  • Tiled GeoTIFF: Save large rasters with internal tiling for efficient access
  • Cloud Optimized GeoTIFF (COG): Industry-standard format optimized for cloud storage and HTTP range requests
  • Automatic overviews: Generate pyramid overviews for fast visualization at different zoom levels

Quick Start

from georeader import save, read
from georeader.geotensor import GeoTensor
import numpy as np

# Load or create a GeoTensor
gt = GeoTensor(np.random.rand(3, 1000, 1000), 
               transform=rasterio.Affine(10, 0, 0, 0, -10, 0),
               crs="EPSG:4326")

# Save as tiled GeoTIFF
save.save_tiled_geotiff(gt, "output.tif", descriptions=["Red", "Green", "Blue"])

# Save as Cloud Optimized GeoTIFF
save.save_cog(gt, "output_cog.tif", descriptions=["Red", "Green", "Blue"])

Key Functions

Function Description
save_tiled_geotiff Save data as internally tiled GeoTIFF
save_cog Save data as Cloud Optimized GeoTIFF with overviews

Save Module: Export GeoTensor data to geospatial file formats.

This module provides functions to save GeoTensor and GeoData objects to various raster file formats, with special support for Cloud Optimized GeoTIFFs (COGs) - the standard format for cloud-native geospatial data.

Cloud Optimized GeoTIFF (COG) Overview

COGs are GeoTIFFs organized for efficient HTTP range requests::

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              CLOUD OPTIMIZED GEOTIFF STRUCTURE                           β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                                          β”‚
β”‚  Traditional GeoTIFF            Cloud Optimized GeoTIFF (COG)           β”‚
β”‚  ────────────────────           ─────────────────────────────           β”‚
β”‚                                                                          β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                     β”‚
β”‚  β”‚ Header (end)    β”‚            β”‚ Header (start)  β”‚ ← HTTP range 0-N   β”‚
β”‚  β”‚                 β”‚            β”‚ ─────────────── β”‚                     β”‚
β”‚  β”‚                 β”‚            β”‚ Overview 8x     β”‚ ← Pyramid layers   β”‚
β”‚  β”‚    Full        β”‚            β”‚ Overview 4x     β”‚   for fast zoom    β”‚
β”‚  β”‚    Resolution  β”‚            β”‚ Overview 2x     β”‚                     β”‚
β”‚  β”‚    Data        β”‚            β”‚ ─────────────── β”‚                     β”‚
β”‚  β”‚                 β”‚            β”‚ β”Œβ”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”  β”‚ ← Tiled structure  β”‚
β”‚  β”‚                 β”‚            β”‚ β”‚256β”‚256β”‚256β”‚  β”‚   (default 256x256)β”‚
β”‚  β”‚                 β”‚            β”‚ β”œβ”€β”€β”€β”Όβ”€β”€β”€β”Όβ”€β”€β”€β”€  β”‚                     β”‚
β”‚  β”‚                 β”‚            β”‚ β”‚256β”‚256β”‚256β”‚  β”‚                     β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜            β”‚ β””β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”˜  β”‚                     β”‚
β”‚                                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                     β”‚
β”‚                                                                          β”‚
β”‚  Benefits:                                                               β”‚
β”‚  β€’ Read any region without downloading whole file                       β”‚
β”‚  β€’ Fast preview via overviews (pyramid layers)                          β”‚
β”‚  β€’ Efficient streaming for web mapping applications                     β”‚
β”‚  β€’ Compatible with all GeoTIFF readers                                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Compression Options

Choose compression based on data type::

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    COMPRESSION RECOMMENDATIONS                           β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                                          β”‚
β”‚  Compression    Best For                    Speed    Size                β”‚
β”‚  ───────────    ────────                    ─────    ────                β”‚
β”‚  lzw           General purpose (DEFAULT)    Fast     Medium             β”‚
β”‚  deflate       Better compression ratio     Medium   Small              β”‚
β”‚  zstd          Modern, fast + small         Fast     Small              β”‚
β”‚  lzma          Maximum compression          Slow     Smallest           β”‚
β”‚  jpeg          RGB imagery (lossy)          Fast     Tiny               β”‚
β”‚  webp          RGB imagery (lossy/lossless) Fast     Tiny               β”‚
β”‚  none          Already compressed data      N/A      Original           β”‚
β”‚                                                                          β”‚
β”‚  For scientific data: Use lzw or zstd (lossless)                        β”‚
β”‚  For visualization: Consider jpeg or webp (lossy ok)                    β”‚
β”‚  For integer masks: Use deflate with predictor=2                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Data Type Mapping

NumPy to GeoTIFF dtype mapping::

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  NumPy dtype     GeoTIFF dtype    Notes                                 β”‚
β”‚  ────────────    ─────────────    ─────                                 β”‚
β”‚  uint8           Byte             8-bit unsigned (0-255)                β”‚
β”‚  uint16          UInt16           16-bit unsigned (0-65535)             β”‚
β”‚  int16           Int16            16-bit signed                         β”‚
β”‚  uint32          UInt32           32-bit unsigned                       β”‚
β”‚  int32           Int32            32-bit signed                         β”‚
β”‚  float32         Float32          32-bit floating point                 β”‚
β”‚  float64         Float64          64-bit floating point                 β”‚
β”‚  complex64       CFloat32         Complex 32-bit                        β”‚
β”‚  bool            Byte             Converted to 0/1                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Module Functions Overview

Primary Functions
  • :func:save_cog: Save as Cloud Optimized GeoTIFF with overviews
  • :func:save_tiled_geotiff: Save as tiled GeoTIFF (no overviews)
Format Detection
  • :func:profile_from_dtype: Get rasterio profile for numpy dtype
  • :func:profile_dtype_cog: Default COG profile
Cloud Storage Support
  • Supports gs://, s3://, az://, abfs://, oss:// paths
  • Automatically handles temp file creation for remote writes
  • Pass fs parameter for custom filesystem (e.g., gcsfs, s3fs)

Quick Start

Save a GeoTensor as COG::

from georeader import save
from georeader.geotensor import GeoTensor
import numpy as np
from rasterio.transform import from_bounds

# Create example data
data = np.random.rand(3, 256, 256).astype(np.float32)
transform = from_bounds(-122.5, 37.0, -122.0, 37.5, 256, 256)
gt = GeoTensor(data, transform=transform, crs="EPSG:4326")

# Save as COG (creates overviews automatically)
save.save_cog(gt, "output.tif")

Save with band descriptions and custom compression::

save.save_cog(
    gt,
    "output.tif",
    descriptions=["Red", "Green", "Blue"],
    profile_arg={"compress": "zstd"},
    tags={"source": "Sentinel-2", "date": "2024-01-15"}
)

See Also

georeader.geotensor : GeoTensor class (input to save functions) georeader.rasterio_reader : Reading saved files back rasterio.profiles : Profile documentation

References

  • COG specification: https://www.cogeo.org/
  • Rasterio profiles: https://rasterio.readthedocs.io/en/latest/topics/profiles.html
  • GDAL COG driver: https://gdal.org/drivers/raster/cog.html

save_tiled_geotiff(data_save, path_tiff_save, profile_arg=None, descriptions=None, tags=None, dir_tmpfiles='.', blocksize=BLOCKSIZE_DEFAULT, fs=None)

Save a GeoData object as a tiled GeoTIFF file.

Tiled GeoTIFFs store data in blocks (tiles) rather than strips, enabling efficient random access to subregions. This is the standard format for large rasters but does NOT include overviews. For cloud-optimized files with overviews, use :func:save_cog instead.

The function handles both local and cloud storage paths (gs://, s3://, az://). For remote paths, data is written to a local temp file first, then uploaded.

Parameters:

Name Type Description Default
data_save GeoData

Raster data in (C, H, W) or (H, W) format with geospatial metadata (crs and transform). Can be a GeoTensor or any object implementing the AbstractGeoData protocol.

required
path_tiff_save str

Output file path. Supports local paths and cloud storage URIs: gs://, s3://, az://, abfs://, oss://.

required
profile_arg Optional[Dict[str, Any]]

Rasterio profile options to customize output. Common options:

  • compress: Compression method ('lzw', 'deflate', 'zstd', 'none').
  • dtype: Output data type (auto-detected if not provided).
  • nodata: NoData value (uses fill_value_default if not set).

The crs and transform are always set from data_save.

None
descriptions Optional[List[str]]

Band names/descriptions. Length must match number of bands. Shows in GIS software band properties.

None
tags Optional[Dict[str, Any]]

Metadata tags stored in the TIFF. Example: {"source": "Sentinel-2", "date": "2024-01-15"}.

None
dir_tmpfiles str

Directory for temporary files when writing to cloud storage. Defaults to current directory.

'.'
blocksize int

Tile size in pixels (both width and height). Defaults to 256. Common values: 256, 512. Must be power of 2.

BLOCKSIZE_DEFAULT
fs Optional[Any]

fsspec filesystem object for cloud storage. Auto-detected from path prefix if not provided.

None

Returns:

Name Type Description
None None

File is written to disk/cloud.

Raises:

Type Description
NotImplementedError

If data_save has dimensions other than 2 or 3.

AssertionError

If descriptions length doesn't match band count.

FileNotFoundError

If temp file creation fails for remote writes.

Examples:

Save a simple GeoTensor to local file:

>>> import numpy as np
>>> from georeader.geotensor import GeoTensor
>>> from georeader import save
>>> from rasterio.transform import from_bounds
>>>
>>> # Create sample data
>>> data = np.random.rand(3, 512, 512).astype(np.float32)
>>> transform = from_bounds(-122.5, 37.0, -122.0, 37.5, 512, 512)
>>> gt = GeoTensor(data, transform=transform, crs="EPSG:4326")
>>>
>>> # Save with default settings
>>> save.save_tiled_geotiff(gt, "output.tif")

Save with custom compression and band names:

>>> save.save_tiled_geotiff(
...     gt,
...     "output_custom.tif",
...     profile_arg={"compress": "zstd"},
...     descriptions=["Red", "Green", "Blue"],
...     blocksize=512
... )

Save to Google Cloud Storage:

>>> save.save_tiled_geotiff(
...     gt,
...     "gs://my-bucket/rasters/output.tif",
...     dir_tmpfiles="/tmp"  # Use system temp for cloud uploads
... )
See Also

save_cog: For Cloud Optimized GeoTIFFs with overviews (recommended for most use cases).

Note
  • Tiled GeoTIFFs without overviews are fine for processing workflows
  • For visualization or web serving, use save_cog for better performance
  • Block size should match your typical read access patterns
Source code in georeader/save.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def save_tiled_geotiff(data_save:GeoData, path_tiff_save:str,
                       profile_arg:Optional[Dict[str, Any]]=None,
                       descriptions:Optional[List[str]] = None,
                       tags:Optional[Dict[str, Any]]=None,
                       dir_tmpfiles:str=".",
                       blocksize:int=BLOCKSIZE_DEFAULT,
                       fs:Optional[Any]=None) -> None:
    """
    Save a GeoData object as a tiled GeoTIFF file.

    Tiled GeoTIFFs store data in blocks (tiles) rather than strips, enabling
    efficient random access to subregions. This is the standard format for
    large rasters but does NOT include overviews. For cloud-optimized files
    with overviews, use :func:`save_cog` instead.

    The function handles both local and cloud storage paths (gs://, s3://, az://).
    For remote paths, data is written to a local temp file first, then uploaded.

    Args:
        data_save (GeoData): Raster data in (C, H, W) or (H, W) format with
            geospatial metadata (crs and transform). Can be a GeoTensor or
            any object implementing the AbstractGeoData protocol.
        path_tiff_save (str): Output file path. Supports local paths and cloud
            storage URIs: gs://, s3://, az://, abfs://, oss://.
        profile_arg (Optional[Dict[str, Any]]): Rasterio profile options to
            customize output. Common options:

            - ``compress``: Compression method ('lzw', 'deflate', 'zstd', 'none').
            - ``dtype``: Output data type (auto-detected if not provided).
            - ``nodata``: NoData value (uses fill_value_default if not set).

            The crs and transform are always set from data_save.
        descriptions (Optional[List[str]]): Band names/descriptions. Length must
            match number of bands. Shows in GIS software band properties.
        tags (Optional[Dict[str, Any]]): Metadata tags stored in the TIFF.
            Example: ``{"source": "Sentinel-2", "date": "2024-01-15"}``.
        dir_tmpfiles (str): Directory for temporary files when writing to
            cloud storage. Defaults to current directory.
        blocksize (int): Tile size in pixels (both width and height).
            Defaults to 256. Common values: 256, 512. Must be power of 2.
        fs (Optional[Any]): fsspec filesystem object for cloud storage.
            Auto-detected from path prefix if not provided.

    Returns:
        None: File is written to disk/cloud.

    Raises:
        NotImplementedError: If data_save has dimensions other than 2 or 3.
        AssertionError: If descriptions length doesn't match band count.
        FileNotFoundError: If temp file creation fails for remote writes.

    Examples:
        Save a simple GeoTensor to local file:

        >>> import numpy as np
        >>> from georeader.geotensor import GeoTensor
        >>> from georeader import save
        >>> from rasterio.transform import from_bounds
        >>>
        >>> # Create sample data
        >>> data = np.random.rand(3, 512, 512).astype(np.float32)
        >>> transform = from_bounds(-122.5, 37.0, -122.0, 37.5, 512, 512)
        >>> gt = GeoTensor(data, transform=transform, crs="EPSG:4326")
        >>>
        >>> # Save with default settings
        >>> save.save_tiled_geotiff(gt, "output.tif")

        Save with custom compression and band names:

        >>> save.save_tiled_geotiff(
        ...     gt,
        ...     "output_custom.tif",
        ...     profile_arg={"compress": "zstd"},
        ...     descriptions=["Red", "Green", "Blue"],
        ...     blocksize=512
        ... )

        Save to Google Cloud Storage:

        >>> save.save_tiled_geotiff(
        ...     gt,
        ...     "gs://my-bucket/rasters/output.tif",
        ...     dir_tmpfiles="/tmp"  # Use system temp for cloud uploads
        ... )

    See Also:
        save_cog: For Cloud Optimized GeoTIFFs with overviews (recommended
            for most use cases).

    Note:
        - Tiled GeoTIFFs without overviews are fine for processing workflows
        - For visualization or web serving, use save_cog for better performance
        - Block size should match your typical read access patterns
    """
    profile = PROFILE_TILED_GEOTIFF_DEFAULT.copy()
    profile.update({"blockxsize": blocksize, "blockysize": blocksize})
    if profile_arg is not None:
        profile.update(profile_arg)

    if len(data_save.shape) == 3:
        out_np = np.asanyarray(data_save.values)
    elif len(data_save.shape) == 2:
        out_np = np.asanyarray(data_save.values[np.newaxis])
    else:
        raise NotImplementedError(f"Expected data with 2 or 3 dimensions found: {data_save.shape}")

    profile["crs"] = data_save.crs
    profile["transform"] = data_save.transform

    if "nodata" not in profile:
        profile["nodata"] = data_save.fill_value_default

    if descriptions is not None:
        assert len(descriptions) == out_np.shape[0], f"Unexpected band descriptions {len(descriptions)} expected {out_np.shape[0]}"

    # Set count, height, width
    for idx, c in enumerate(["count", "height", "width"]):
        if c in profile:
            assert profile[c] == out_np.shape[idx], f"Unexpected shape: {profile[c]} {out_np.shape}"
        else:
            profile[c] = out_np.shape[idx]

    if "dtype" not in profile:
        profile["dtype"] = str(out_np.dtype)

    # check blocksize
    for idx, b in enumerate(["blockysize", "blockxsize"]):
        if b in profile:
            profile[b] = min(profile[b], out_np.shape[idx + 1])

    if (out_np.shape[1] > profile["blockysize"]) or (out_np.shape[2] > profile["blockxsize"]):
        profile["tiled"] = True

    profile["driver"] = "GTiff"
    is_remote_file = any((path_tiff_save.startswith(ext) for ext in REMOTE_FILE_EXTENSIONS))

    # Create a tempfile if is a remote file
    if is_remote_file:
        with tempfile.NamedTemporaryFile(dir=dir_tmpfiles, suffix=".tif", delete=True) as fileobj:
            name_save = fileobj.name
    else:
        name_save = path_tiff_save

    with rasterio.open(name_save, "w", **profile) as rst_out:
        if tags is not None:
            rst_out.update_tags(**tags)
        rst_out.write(out_np)
        if descriptions is not None:
            for i in range(1, out_np.shape[0] + 1):
                rst_out.set_band_description(i, descriptions[i - 1])

    if is_remote_file:
        if fs is None:
            import fsspec
            fs = fsspec.filesystem(path_tiff_save.split(":")[0])

        if not os.path.exists(name_save):
            raise FileNotFoundError(f"File {name_save} have not been created")

        fs.put_file(name_save, path_tiff_save, overwrite=True)
        if os.path.exists(name_save):
            os.remove(name_save)

save_cog(data_save, path_tiff_save, profile=None, descriptions=None, tags=None, dir_tmpfiles='.', fs=None)

Save a GeoData object as a Cloud Optimized GeoTIFF (COG).

COGs are the recommended format for cloud-native geospatial workflows. They include:

  • Internal tiling: Efficient random access to subregions
  • Overviews (pyramids): Fast rendering at multiple zoom levels
  • Optimized header placement: Enables HTTP range requests

This function automatically generates overviews using cubic spline resampling, which produces smooth results for continuous data.

Parameters:

Name Type Description Default
data_save GeoData

Raster data in (C, H, W) or (H, W) format with geospatial metadata (crs and transform). Accepts GeoTensor or any AbstractGeoData implementation.

required
path_tiff_save str

Output file path. Supports local paths and cloud storage URIs (gs://, s3://, az://, abfs://, oss://).

required
profile Optional[Dict[str, Any]]

Rasterio profile options. Common:

  • compress: Compression ('lzw', 'deflate', 'zstd'). Default: 'lzw'.
  • RESAMPLING: Overview resampling method. Default: 'CUBICSPLINE'.
  • dtype: Output dtype (auto-detected from data if not set).
  • nodata: NoData value (uses fill_value_default if not set).

CRS and transform are always taken from data_save.

None
descriptions Optional[List[str]]

Band names shown in GIS software. Length must equal number of bands in data_save.

None
tags Optional[Dict[str, Any]]

Metadata tags embedded in the TIFF. Example: {"source": "Sentinel-2", "acquisition_date": "2024-01-15"}.

None
dir_tmpfiles str

Temporary file directory for cloud storage writes. Defaults to current directory.

'.'
fs Optional[Any]

fsspec filesystem object for cloud storage. Auto-detected from path prefix if not provided.

None

Returns:

Name Type Description
None None

File is written to disk/cloud storage.

Raises:

Type Description
NotImplementedError

If data_save has dimensions other than 2 or 3.

AssertionError

If descriptions length doesn't match band count.

Examples:

Basic COG creation:

>>> import numpy as np
>>> from georeader.geotensor import GeoTensor
>>> from georeader import save
>>> import rasterio
>>>
>>> # Create 4-band raster
>>> img = np.random.randn(4, 256, 256).astype(np.float32)
>>> transform = rasterio.Affine(10, 0, 799980.0, 0, -10, 1900020.0)
>>> data = GeoTensor(img, crs="EPSG:32644", transform=transform)
>>>
>>> # Save as COG with band descriptions
>>> save.save_cog(
...     data,
...     "example.tif",
...     descriptions=["band1", "band2", "band3", "band4"]
... )

Save with high compression for archival:

>>> save.save_cog(
...     data,
...     "archived.tif",
...     profile={"compress": "zstd", "ZSTD_LEVEL": 9},
...     tags={"project": "climate-analysis", "version": "1.0"}
... )

Save classification result with nearest-neighbor overviews:

>>> classification = GeoTensor(
...     np.random.randint(0, 10, (256, 256), dtype=np.uint8),
...     transform=transform, crs="EPSG:32644"
... )
>>> save.save_cog(
...     classification,
...     "landcover.tif",
...     profile={"compress": "deflate", "RESAMPLING": "NEAREST"},
...     descriptions=["Land Cover Class"]
... )
See Also

save_tiled_geotiff: For tiled GeoTIFF without overviews (faster write, smaller file, but slower visualization).

Note
  • COG creation is slower than save_tiled_geotiff due to overview generation
  • Use 'NEAREST' resampling for categorical/classified data
  • Use 'CUBICSPLINE' or 'LANCZOS' for continuous imagery
  • Files can be directly served via HTTP range requests (e.g., via STAC)
Source code in georeader/save.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def save_cog(data_save:GeoData, path_tiff_save:str,
             profile:Optional[Dict[str, Any]]=None,
             descriptions:Optional[List[str]] = None, 
             tags:Optional[Dict[str, Any]]=None,
             dir_tmpfiles:str=".",
             fs:Optional[Any]=None) -> None:
    """
    Save a GeoData object as a Cloud Optimized GeoTIFF (COG).

    COGs are the recommended format for cloud-native geospatial workflows. They
    include:

    - **Internal tiling**: Efficient random access to subregions
    - **Overviews (pyramids)**: Fast rendering at multiple zoom levels
    - **Optimized header placement**: Enables HTTP range requests

    This function automatically generates overviews using cubic spline
    resampling, which produces smooth results for continuous data.

    Args:
        data_save (GeoData): Raster data in (C, H, W) or (H, W) format with
            geospatial metadata (crs and transform). Accepts GeoTensor or any
            AbstractGeoData implementation.
        path_tiff_save (str): Output file path. Supports local paths and cloud
            storage URIs (gs://, s3://, az://, abfs://, oss://).
        profile (Optional[Dict[str, Any]]): Rasterio profile options. Common:

            - ``compress``: Compression ('lzw', 'deflate', 'zstd'). Default: 'lzw'.
            - ``RESAMPLING``: Overview resampling method. Default: 'CUBICSPLINE'.
            - ``dtype``: Output dtype (auto-detected from data if not set).
            - ``nodata``: NoData value (uses fill_value_default if not set).

            CRS and transform are always taken from data_save.
        descriptions (Optional[List[str]]): Band names shown in GIS software.
            Length must equal number of bands in data_save.
        tags (Optional[Dict[str, Any]]): Metadata tags embedded in the TIFF.
            Example: ``{"source": "Sentinel-2", "acquisition_date": "2024-01-15"}``.
        dir_tmpfiles (str): Temporary file directory for cloud storage writes.
            Defaults to current directory.
        fs (Optional[Any]): fsspec filesystem object for cloud storage.
            Auto-detected from path prefix if not provided.

    Returns:
        None: File is written to disk/cloud storage.

    Raises:
        NotImplementedError: If data_save has dimensions other than 2 or 3.
        AssertionError: If descriptions length doesn't match band count.

    Examples:
        Basic COG creation:

        >>> import numpy as np
        >>> from georeader.geotensor import GeoTensor
        >>> from georeader import save
        >>> import rasterio
        >>>
        >>> # Create 4-band raster
        >>> img = np.random.randn(4, 256, 256).astype(np.float32)
        >>> transform = rasterio.Affine(10, 0, 799980.0, 0, -10, 1900020.0)
        >>> data = GeoTensor(img, crs="EPSG:32644", transform=transform)
        >>>
        >>> # Save as COG with band descriptions
        >>> save.save_cog(
        ...     data,
        ...     "example.tif",
        ...     descriptions=["band1", "band2", "band3", "band4"]
        ... )

        Save with high compression for archival:

        >>> save.save_cog(
        ...     data,
        ...     "archived.tif",
        ...     profile={"compress": "zstd", "ZSTD_LEVEL": 9},
        ...     tags={"project": "climate-analysis", "version": "1.0"}
        ... )

        Save classification result with nearest-neighbor overviews:

        >>> classification = GeoTensor(
        ...     np.random.randint(0, 10, (256, 256), dtype=np.uint8),
        ...     transform=transform, crs="EPSG:32644"
        ... )
        >>> save.save_cog(
        ...     classification,
        ...     "landcover.tif",
        ...     profile={"compress": "deflate", "RESAMPLING": "NEAREST"},
        ...     descriptions=["Land Cover Class"]
        ... )

    See Also:
        save_tiled_geotiff: For tiled GeoTIFF without overviews (faster write,
            smaller file, but slower visualization).

    Note:
        - COG creation is slower than save_tiled_geotiff due to overview generation
        - Use 'NEAREST' resampling for categorical/classified data
        - Use 'CUBICSPLINE' or 'LANCZOS' for continuous imagery
        - Files can be directly served via HTTP range requests (e.g., via STAC)
    """
    if profile is None:
        profile = {
            "compress": "lzw",
            "RESAMPLING": "CUBICSPLINE",  # for pyramids
        }
    if len(data_save.shape) == 3:
        np_data = np.asanyarray(data_save.values)
    elif len(data_save.shape) == 2:
        np_data = np.asanyarray(data_save.values[np.newaxis])
    else:
        raise NotImplementedError(f"Expected data with 2 or 3 dimensions found: {data_save.shape}")

    profile["crs"] = data_save.crs
    profile["transform"] = data_save.transform

    if "nodata" not in profile:
        profile["nodata"] = data_save.fill_value_default

    _save_cog(np_data,
              path_tiff_save, profile, descriptions=descriptions,
              tags=tags, dir_tmpfiles=dir_tmpfiles, fs=fs)