Writing PNG, NetCDF and GeoTIFF

Note

Download the executable 09_writing_output_formats.ipynb to run this tutorial in JupyterLab.

A DEFAIR dataset can be written out in several formats, and the choice matters more than it looks. GeoTIFF and NetCDF keep the physical values and the georeferencing in the file itself, so what you read back is the data. PNG and JPEG are pictures: the values are quantised for display, to 8 bits unless a wider type is asked for, and the georeferencing goes into a separate .aux.xml sidecar, so it is only there for as long as that file travels with the image.

This tutorial writes an MSG SEVIRI disc and a reprojected sea surface temperature field through the raster and tabular writers, then checks what each format kept: it opens the image and GeoTIFF files again with rasterio and the NetCDF file with xarray, prints the first lines of the CSV file, and shows the size of the HDF5 file. Zarr belongs to the pipeline tutorial, and Parquet to the coverage notebooks.

Before running this notebook, complete the shared setup in Tutorials.

Prerequisites

No. 1 Input data

The notebook reads these products from the public demo bucket of the DestinE Data Lake, without an account or credentials:

  • MSG SEVIRI native data

  • Metop global sea surface temperature

To use your own files instead, change the paths in MSG_URI and GLBSST_URI and follow Prepare data access for DEFAIR.

Set up the notebook

from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import rasterio
import xarray as xr

from defair_data.core import Dataset
from defair_data.writers import find_writer_for_path, list_writers
from defair.logging import setup_logging
from defair_data.dask_manager import close_dask_client

# Readers log every step at DEBUG. WARNING keeps this notebook's output to what the
# tutorial prints, and is the level to raise when a read does something unexpected.
setup_logging(log_level="WARNING")

# The public Data Lake demo bucket, which needs no credentials.
PUBLIC_S3 = {"endpoint_url": "https://s3.central.data.destination-earth.eu", "anon": True}
MSG_URI    = "s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20251016172744.081000000Z-NA_nat"
GLBSST_URI = "s3://datalake-demo-data/defair-notebook-data/osisaf-metop-glbsst/S-OSI_-FRA_-MTOP-GLBSST_FIELD-202508010000Z"

OUTPUT_DIR = Path("./output/raster_writers"); OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

print("writers:", list_writers())
# Extension -> writer (the registry's auto-detect, what `Dataset.to_file` would
# pick when called without an explicit `writer=` argument).
for ext in (".tif", ".tiff", ".png", ".jpg", ".jpeg"):
    print(f"  {ext:6s} -> {find_writer_for_path('out' + ext)}")
writers: ['csv', 'geoparquet', 'geotiff', 'hdf5', 'jpeg', 'netcdf4', 'parquet', 'png', 'zarrv2', 'zarrv3']
  .tif   -> geotiff
  .tiff  -> geotiff
  .png   -> png
  .jpg   -> jpeg
  .jpeg  -> jpeg

Helpers

reserved_nodata_normalizer is the interesting one. Quantising to 8 bits means picking which integer means “no data”, and reserving the top code for it, rather than letting a genuinely saturated pixel collide with the fill value.

def first_file(directory, suffix):
    files = sorted(Path(directory).rglob(f"*{suffix}"))
    if not files:
        raise FileNotFoundError(f"no *{suffix} under {directory}")
    return files[0]


def decode(src, step=1):
    """Band 1 as physical values: the codes through the file's own scale and offset.

    `step` reads every step-th pixel, for a preview that does not need them all.
    """
    band = src.read(1, masked=True, out_shape=(src.height // step, src.width // step)).astype("float64")
    return band * float(src.scales[0]) + float(src.offsets[0])


def short_crs(crs):
    if crs is None:
        return "-"
    epsg = crs.to_epsg()
    return f"EPSG:{epsg}" if epsg else f"proj:{crs.to_dict().get('proj', '?')}"


def reserved_nodata_normalizer(lo, hi, *, dtype="uint8"):
    """Build a lazy linear normalizer that reserves the top integer for nodata."""
    info = np.iinfo(dtype)
    nodata = int(info.max)
    valid_max = nodata - 1
    scale = (float(hi) - float(lo)) / valid_max
    if not scale > 0:
        raise ValueError(f"invalid normalization range: {(lo, hi)}")

    def normalize(array):
        encoded = ((array - lo) / scale).clip(0, valid_max)
        encoded = xr.where(np.isfinite(array), encoded, nodata).astype(dtype)
        attrs = dict(array.attrs)
        attrs.update(_FillValue=nodata, scale_factor=scale, add_offset=float(lo))
        return encoded.assign_attrs(attrs)

    return normalize


def raster_summary(path, *, nodata_code=None, reference=None):
    """Report what a written raster carries: geometry, type, nodata and physical range.

    With `nodata_code`, `reference` is the GeoTIFF written from the same array: its mask is
    where the source had data. Taking the valid pixels from the picture's own mask instead
    would exclude the nodata code by construction and make the check vacuous.
    """
    with rasterio.open(path) as src:
        scale, offset = float(src.scales[0]), float(src.offsets[0])
        band = src.read(1, masked=True)
        bounds, transform = src.bounds, src.transform
        physical = decode(src)
        print(f"  {Path(path).name}: CRS={short_crs(src.crs)} {src.width}x{src.height} "
              f"dtype={src.dtypes[0]} nodata={src.nodata}")
        print(f"    bounds=({bounds.left:.1f},{bounds.bottom:.1f},{bounds.right:.1f},{bounds.top:.1f}) "
              f"px=({transform.a:g},{transform.e:g}) scale={scale:g} offset={offset:g}")
        print(f"    physical=[{physical.min():.4g}, {physical.max():.4g}] "
              f"valid={band.count():,} nodata={band.size - band.count():,}")
        if nodata_code is not None:
            raw = src.read(1)
            written_valid = src.read_masks(1) != 0
            with rasterio.open(reference) as unquantised:
                source_valid = ~np.ma.getmaskarray(unquantised.read(1, masked=True))
            lost = int((source_valid & ~written_valid).sum())
            gained = int((~source_valid & written_valid).sum())
            collisions = int((raw[source_valid] == nodata_code).sum())
            print(f"    nodata mask against the source: {lost:,} lost, {gained:,} gained")
            print(f"    source-valid pixels encoded as {nodata_code}: {collisions}"
                  f", codes used {raw[source_valid].min()}..{raw[source_valid].max()}")
            # After the prints, so a failure still shows the counts. Without it the check only
            # reports: the notebook harness fails on exceptions, so a writer that dropped
            # pixels or reused the nodata code for real data would pass unnoticed.
            assert lost == gained == collisions == 0, (
                f"{Path(path).name}: {lost} lost, {gained} gained, {collisions} collisions"
            )


def preview_triplet(paths, title, cmap="gray"):
    """Plot the three writer outputs side by side, all on one physical range.

    Each file is decoded through its own scale and offset before it is drawn, and every
    panel takes the range of the first file, which is the unquantised GeoTIFF. Letting each
    panel autoscale its own codes would make equal colour mean equal code rather than equal
    physical value, which is the opposite of what a format comparison should show.
    """
    with rasterio.open(paths[0]) as reference:
        # A panel is about 700 pixels across, so a 7200x3600 global field is read at a
        # third of its resolution: three full float64 copies do not fit a 4 GB server.
        step = max(1, max(reference.width, reference.height) // 2000)
        reference_physical = decode(reference, step)
        reference_mask = np.ma.getmaskarray(reference_physical)
        vmin, vmax = np.nanpercentile(np.ma.filled(reference_physical, np.nan), [2, 98])
        # The figure follows the raster's shape: a 2:1 world map in a square panel leaves a
        # band of white as tall as the map itself.
        aspect = reference.height / reference.width
    # 7 inches a panel, so that a 2:1 world map is still about 700 pixels across when the
    # figure is saved at the default 100 dots per inch.
    fig, axes = plt.subplots(1, len(paths), figsize=(7 * len(paths), 7 * aspect + 1.0))
    fig.suptitle(title, fontsize=13)
    for ax, path in zip(axes, paths):
        with rasterio.open(path) as src:
            # Mask declared nodata before display scaling; fill pixels must not
            # dominate the contrast of sparse products such as GLB-SST. Use the
            # lossless GeoTIFF mask for all three previews because JPEG
            # compression does not preserve an exact numeric nodata sentinel.
            band, crs, dt = decode(src, step), src.crs, src.dtypes[0]
            origin = "lower" if src.transform.e > 0 else "upper"
        band = np.ma.array(band, mask=np.ma.getmaskarray(band) | reference_mask)
        ax.imshow(band, cmap=cmap, origin=origin, vmin=vmin, vmax=vmax)
        ax.set_title(f"{path.suffix[1:].upper()} ({dt})\nCRS={short_crs(crs)}", fontsize=10)
        ax.axis("off")
    plt.tight_layout()
    plt.show()

A geostationary disc

The disc is written straight out of its native geostationary projection. The GeoTIFF keeps float32 radiances; the PNG and JPEG quantise them to 8 bits. All three record the projection, the two pictures in the sidecar listed below rather than in the image.

# `channels` takes the documented channel names either way; use_channel_names=True also
# names the variable IR_108 rather than the raw band name ch9, and the writers below take
# their file names from the variable. The thermal infrared window channel is the one to
# look at here: it sees the whole disc by day and by night, where a visible channel at
# 17:27 UTC leaves most of the disc unlit.
msg = Dataset.from_source(MSG_URI, reader="msg15nat", source="s3", source_kwargs=PUBLIC_S3,
                          use_channel_names=True, channels=["IR_108"])
geo = OUTPUT_DIR / "geostationary"

msg.to_file(str(geo / "geotiff"), writer="geotiff", compression="lzw")
# The normalizer's range decides how much of the 8-bit scale the written file uses. This
# granule's radiances run to about 150 mW m-2 sr-1 (cm-1)-1, so a 0 to 150 range spreads them
# over the codes printed below; a 0 to 600 range would leave three quarters of the scale empty
# and quantise the picture four times more coarsely, and anything below the scene's own maximum
# would clip it. The channel itself is specified up to 335 K, about 180 in these units, which is
# where to start for a scene warmer than this one. Code 255 is reserved for nodata, which is
# why the range stops at 254: passing nodata_value=255 to the default full-range normalizer is
# not enough, because a saturated pixel would encode as 255 too.
msg_u8 = reserved_nodata_normalizer(0.0, 150.0)
msg.to_file(str(geo / "png"),  writer="png",  normalizer=msg_u8, nodata_value=255)
msg.to_file(str(geo / "jpeg"), writer="jpeg", normalizer=msg_u8, nodata_value=255, quality=85)

tif = first_file(geo / "geotiff", ".tif")
raster_summary(tif)
raster_summary(first_file(geo / "png", ".png"), nodata_code=255, reference=tif)
preview_triplet(
    [tif, first_file(geo / "png", ".png"), first_file(geo / "jpeg", ".jpg")],
    "MSG15 IR_108 written three ways: geotiff, png, jpeg",
    cmap="gray",
)
IR_108_20251016T171500.tif: CRS=proj:geos 3712x3712 dtype=float32 nodata=nan
  bounds=(-5570248.5,-5567248.1,5567248.1,5570248.5) px=(3000.4,-3000.4) scale=1 offset=0
  physical=[2.665, 149.9] valid=10,213,483 nodata=3,565,461
IR_108_20251016T171500.png: CRS=proj:geos 3712x3712 dtype=uint8 nodata=255.0
  bounds=(-5570248.5,-5567248.1,5567248.1,5570248.5) px=(3000.4,-3000.4) scale=0.590551 offset=0
  physical=[2.362, 149.4] valid=10,213,483 nodata=3,565,461
  nodata mask against the source: 0 lost, 0 gained
  source-valid pixels encoded as 255: 0, codes used 4..253
../../../../_images/09_writing_output_formats_5_1.png

A gridded polar-orbiter product

Sea surface temperature from Metop, content-filtered and written the same three ways plus a 16-bit PNG.

The product already arrives on a global 0.05 degree latitude and longitude grid, so the reprojection below resamples it onto a grid of the same shape and spacing: the bounds printed under it are exactly -180 to 180 and -90 to 90 at 0.05 degrees, which is the grid the product came on. A swath product is where the step would move data.

glb = (Dataset.from_source(GLBSST_URI, reader="metop_glbsst", source="s3", source_kwargs=PUBLIC_S3)
       .transform("content_filter", include_vars=["sea_surface_temperature"])
       .transform("reprojection", target="EPSG:4326", resolution=0.05, resampling="nearest",
                  bounds=(-180.0, -90.0, 180.0, 90.0)))
out = OUTPUT_DIR / "gridded_leo"

glb.to_file(str(out / "geotiff"), writer="geotiff", compression="lzw")
glb_u8 = reserved_nodata_normalizer(270.0, 320.0)
glb_u16 = reserved_nodata_normalizer(270.0, 320.0, dtype="uint16")
glb.to_file(str(out / "png"),  writer="png",  normalizer=glb_u8, nodata_value=255)
glb.to_file(str(out / "jpeg"), writer="jpeg", normalizer=glb_u8, nodata_value=255, quality=85)
glb.to_file(str(out / "png_u16"), writer="png", normalizer=glb_u16,
            target_dtype="uint16", nodata_value=65535)

tif = first_file(out / "geotiff", ".tif")
raster_summary(tif)
raster_summary(first_file(out / "png", ".png"), nodata_code=255, reference=tif)
preview_triplet(
    [tif, first_file(out / "png", ".png"), first_file(out / "jpeg", ".jpg")],
    "Metop GLB-SST written three ways: geotiff, png, jpeg",
    cmap="inferno",
)

# The same field at 16 bits: the wider type spreads 270 to 320 K over 65535 codes instead
# of 254, which is the difference between a picture and a quantised measurement.
raster_summary(first_file(out / "png_u16", ".png"), nodata_code=65535, reference=tif)
sea_surface_temperature_20250801T000000.tif: CRS=EPSG:4326 7200x3600 dtype=float64 nodata=nan
  bounds=(-180.0,-90.0,180.0,90.0) px=(0.05,-0.05) scale=1 offset=0
  physical=[270.1, 310.1] valid=6,696,585 nodata=19,223,415
sea_surface_temperature_20250801T000000.png: CRS=EPSG:4326 7200x3600 dtype=uint8 nodata=255.0
  bounds=(-180.0,-90.0,180.0,90.0) px=(0.05,-0.05) scale=0.19685 offset=270
  physical=[270, 310] valid=6,696,585 nodata=19,223,415
  nodata mask against the source: 0 lost, 0 gained
  source-valid pixels encoded as 255: 0, codes used 0..203
../../../../_images/09_writing_output_formats_7_1.png
sea_surface_temperature_20250801T000000.png: CRS=EPSG:4326 7200x3600 dtype=uint16 nodata=65535.0
  bounds=(-180.0,-90.0,180.0,90.0) px=(0.05,-0.05) scale=0.000762963 offset=270
  physical=[270.1, 310.1] valid=6,696,585 nodata=19,223,415
  nodata mask against the source: 0 lost, 0 gained
  source-valid pixels encoded as 65535: 0, codes used 196..52610

NetCDF

# NetCDF is the format most users of this data already have tooling for. It keeps the
# variables, the coordinates and the attributes exactly as DEFAIR built them.
netcdf_path = OUTPUT_DIR / "sst.nc"
glb.to_file(str(netcdf_path), writer="netcdf4")

# The writer takes a file or a directory; a directory holds one file per variable.
written_nc = first_file(netcdf_path, ".nc") if netcdf_path.is_dir() else netcdf_path
reopened = xr.open_dataset(written_nc)
print(reopened)
reopened.close()
<xarray.Dataset> Size: 207MB
Dimensions:                  (time: 1, lat: 3600, lon: 7200, bnds: 2)
Coordinates:
  * time                     (time) datetime64[ns] 8B 2025-08-01
  * lat                      (lat) float64 29kB 89.97 89.92 ... -89.93 -89.98
  * lon                      (lon) float64 58kB -180.0 -179.9 ... 179.9 180.0
    crs                      int64 8B ...
    time_bnds                (time, bnds) datetime64[ns] 16B ...
    spatial_ref              int64 8B ...
Dimensions without coordinates: bnds
Data variables:
    sea_surface_temperature  (time, lat, lon) float64 207MB ...
Attributes: (12/57)
    Conventions:                CF-1.13
    title:                      Sea Surface Temperature
    summary:                    The GLB L3C product derived from METOP B AVHR...
    references:                 Low Earth Orbiter Sea Surface Temperature Pro...
    institution:                OSISAF
    history:                    METEO-FRANCE/CMS LEOSAFO processor\n2026-10-0...
    ...                         ...
    filename:                   S-OSI_-FRA_-MTOP-GLBSST_FIELD-202508010000Z
    product_type:               SST
    timestamp:                  202508010000
    crs:                        EPSG:4326
    spatial_ref:                GEOGCRS["WGS 84",ENSEMBLE["World Geodetic Sys...
    defair_cdm:                 {"schema_version":3,"reader":"metopglbsst","p...

CSV and HDF5

# CSV and HDF5 round out the writer set. CSV flattens the dataset to a table, so it suits
# point and along-track products rather than a full disc; HDF5 keeps the n-dimensional
# shape, like NetCDF, with a different container.
table = (
    Dataset.from_source(GLBSST_URI, reader="metop_glbsst", source="s3", source_kwargs=PUBLIC_S3)
    .transform("content_filter", include_vars=["sea_surface_temperature"])
    # Bay of Biscay: the box has to be over water, or a sea surface temperature product
    # writes a table of nothing but fill values.
    .transform("spatial_filter", lat_min=44.0, lat_max=47.0, lon_min=-6.0, lon_max=-2.0)
)

table.to_file(str(OUTPUT_DIR / "sst.csv"), writer="csv")
table.to_file(str(OUTPUT_DIR / "sst.h5"), writer="hdf5")

for path in (OUTPUT_DIR / "sst.csv", OUTPUT_DIR / "sst.h5"):
    written = sorted(Path(str(path)).rglob("*")) if Path(str(path)).is_dir() else [Path(str(path))]
    for item in written:
        print(f"  {item.name}  ({item.stat().st_size:,} B)")

print("\nFirst lines of the CSV:")
csv_files = sorted(Path(str(OUTPUT_DIR / "sst.csv")).rglob("*.csv")) or [Path(str(OUTPUT_DIR / "sst.csv"))]
print("".join(csv_files[0].read_text().splitlines(keepends=True)[:5]))
  sst.csv  (513,925 B)
  sst.h5  (59,601 B)

First lines of the CSV:
"time","lat","lon","source_file","sea_surface_temperature"
2025-08-01 00:00:00.000000000Z,44.02539,-5.9746094,"S-OSI_-FRA_-MTOP-GLBSST_FIELD-202508010000Z",295.28999999999996
2025-08-01 00:00:00.000000000Z,44.02539,-5.9248047,"S-OSI_-FRA_-MTOP-GLBSST_FIELD-202508010000Z",289.4
2025-08-01 00:00:00.000000000Z,44.02539,-5.875,"S-OSI_-FRA_-MTOP-GLBSST_FIELD-202508010000Z",291.10999999999996
2025-08-01 00:00:00.000000000Z,44.02539,-5.8251953,"S-OSI_-FRA_-MTOP-GLBSST_FIELD-202508010000Z",293.13

What each file actually contains

The table below reopens every raster written above with rasterio and reports its real size, data type, coordinate reference system and bounds. This is the point of the tutorial: every row carries a CRS and real bounds, because the sidecar supplies them for the pictures. Only the GeoTIFF rows keep the values unquantised. The PNGs keep a clipped, quantised copy whose codes decode exactly through the scale and offset in their sidecar; the JPEG decodes the same way but its codes have been through a lossy compressor first, so what comes back is close rather than exact. The previews above decode all three before drawing.

for p in sorted((OUTPUT_DIR / "geostationary" / "png").iterdir()):
    print(f"  {p.name}  ({p.stat().st_size:,} B)")
IR_108_20251016T171500.png  (4,397,505 B)
IR_108_20251016T171500.png.aux.xml  (2,420 B)
print(f"{'file':<62} {'size':>11} {'dtype':>8}  {'CRS':<10}  bounds")
for path in sorted(OUTPUT_DIR.rglob("*")):
    if path.suffix.lower() not in {".png", ".jpg", ".tif"}:
        continue

    with rasterio.open(path) as src:
        w, h, dt, crs, b = src.width, src.height, src.dtypes[0], src.crs, src.bounds

    assert w > 0 and h > 0
    if path.suffix.lower() in {".png", ".jpg"} and "png_u16" not in path.parts:
        assert dt == "uint8"

    rel = path.relative_to(OUTPUT_DIR)
    print(f"{str(rel):<62} {f'{w}x{h}':>11} {dt:>8}  {short_crs(crs):<10}  "
          f"({b.left:.1f},{b.bottom:.1f},{b.right:.1f},{b.top:.1f})")
file                                                                  size    dtype  CRS         bounds
geostationary/geotiff/IR_108_20251016T171500.tif                 3712x3712  float32  proj:geos   (-5570248.5,-5567248.1,5567248.1,5570248.5)
geostationary/jpeg/IR_108_20251016T171500.jpg                    3712x3712    uint8  proj:geos   (-5570248.5,-5567248.1,5567248.1,5570248.5)
geostationary/png/IR_108_20251016T171500.png                     3712x3712    uint8  proj:geos   (-5570248.5,-5567248.1,5567248.1,5570248.5)
gridded_leo/geotiff/sea_surface_temperature_20250801T000000.tif   7200x3600  float64  EPSG:4326   (-180.0,-90.0,180.0,90.0)
gridded_leo/jpeg/sea_surface_temperature_20250801T000000.jpg     7200x3600    uint8  EPSG:4326   (-180.0,-90.0,180.0,90.0)
gridded_leo/png/sea_surface_temperature_20250801T000000.png      7200x3600    uint8  EPSG:4326   (-180.0,-90.0,180.0,90.0)
gridded_leo/png_u16/sea_surface_temperature_20250801T000000.png   7200x3600   uint16  EPSG:4326   (-180.0,-90.0,180.0,90.0)

What to do next

See Write a writer plugin for writing a new writer. The pipeline tutorial writes a Zarr cube, which is the format to reach for when the output is meant to be read back by a machine rather than looked at.

close_dask_client()