Skip to content

Pink PGM files

Pink and pink26 store images in an extension of the PGM format, for 2D and 3D images of uint8, int32, float32 or float64 pixels. digitopo.io.read and digitopo.io.write read and write these files as NumPy arrays. The parsing and the encoding are done in Rust. read accepts the files that pink26 accepts and gives the same arrays; write writes the same bytes as pink26.

Arrays use the NumPy axis order: a 2D image is (rows, columns), a 3D image is (depth, rows, columns).

dtype of the array Format written Read back as
uint8 P5 uint8
bool P5, False as 0 and True as 255 uint8
int32 P8 int32
float32 P9 float32
float64 PC float64

read also accepts the other formats of pink26 (P2, P7, PB, PA, PD); see Design of the API.

The code below is taken from docs/examples/scripts/pgm_files.py, which makes the figure. The whole script is at the end of the page.

Writing and reading

r, c = np.mgrid[:48, :64]
shape = ((r - 24) ** 2 / 20**2 + (c - 32) ** 2 / 28**2 <= 1) & ((r - 24) ** 2 + (c - 32) ** 2 > 36)
images = {
    "shape.pgm": shape,                                         # bool: written as 0/255
    "skeleton.pgm": skeleton.ultimate_skeleton(shape, 8).astype(np.uint8),
    "distance.pgm": distance.distance_map(shape),               # int32
    "volume.pgm": np.random.default_rng(0).random((4, 5, 6)).astype(np.float32),
}

folder = Path(tempfile.mkdtemp())
for name, image in images.items():
    digitopo.io.write(folder / name, image)
    back = digitopo.io.read(folder / name)
    header = (folder / name).read_bytes()[:2].decode("ascii")
    print(f"{name:13s} {image.dtype!s:8s} -> {header} -> {back.dtype!s:8s} "
          f"shape {back.shape}, size {(folder / name).stat().st_size} bytes")
shape.pgm     bool     -> P5 -> uint8    shape (48, 64), size 3085 bytes
skeleton.pgm  uint8    -> P5 -> uint8    shape (48, 64), size 3085 bytes
distance.pgm  int32    -> P8 -> int32    shape (48, 64), size 12308 bytes
volume.pgm    float32  -> P9 -> float32  shape (4, 5, 6), size 491 bytes

The files start with a short text header, followed by the raw pixels, little-endian: for shape.pgm, the 13 bytes P5, 64 48 (columns, rows), 255, each on its own line, then 48 x 64 bytes. A 3D header gives the columns, the rows and the depth, in this order.

Checking the round trip

back = digitopo.io.read(folder / "shape.pgm")
print("bool values read back:", np.unique(back).tolist())
print("int32 identical:", bool((digitopo.io.read(folder / "distance.pgm") == images["distance.pgm"]).all()))
print("float32 identical:", bool((digitopo.io.read(folder / "volume.pgm") == images["volume.pgm"]).all()))
bool values read back: [0, 255]
int32 identical: True
float32 identical: True

A bool image comes back as uint8 with the values 0 and 255; convert it with image != 0 if needed. The other dtypes come back unchanged.

Three images read back from PGM files: a shape (uint8, 0 and 255), its skeleton (uint8, 0 and 1) and its distance map (int32)

Errors

read raises FileNotFoundError (an OSError) when the file does not exist, and DigitopoError when the content is malformed, truncated or unsupported (for example 16-bit pixels). write raises TypeError for an unsupported dtype and ValueError for an array that is not 2D or 3D.

The whole script
# SPDX-License-Identifier: CECILL-2.1
# Figure of docs/examples/pgm-files.md. This script is the source of truth:
# the page includes parts of it with pymdownx.snippets. Run it from the
# repository root (the files are written to a temporary directory):
#     python docs/examples/scripts/pgm_files.py
import tempfile
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import digitopo
import matplotlib.pyplot as plt
import numpy as np
from digitopo import distance, skeleton

FIGURES = Path(__file__).resolve().parents[2] / "figures"
TEXT = "#222222"

r, c = np.mgrid[:48, :64]
shape = ((r - 24) ** 2 / 20**2 + (c - 32) ** 2 / 28**2 <= 1) & ((r - 24) ** 2 + (c - 32) ** 2 > 36)
images = {
    "shape.pgm": shape,                                         # bool: written as 0/255
    "skeleton.pgm": skeleton.ultimate_skeleton(shape, 8).astype(np.uint8),
    "distance.pgm": distance.distance_map(shape),               # int32
    "volume.pgm": np.random.default_rng(0).random((4, 5, 6)).astype(np.float32),
}

folder = Path(tempfile.mkdtemp())
for name, image in images.items():
    digitopo.io.write(folder / name, image)
    back = digitopo.io.read(folder / name)
    header = (folder / name).read_bytes()[:2].decode("ascii")
    print(f"{name:13s} {image.dtype!s:8s} -> {header} -> {back.dtype!s:8s} "
          f"shape {back.shape}, size {(folder / name).stat().st_size} bytes")

back = digitopo.io.read(folder / "shape.pgm")
print("bool values read back:", np.unique(back).tolist())
print("int32 identical:", bool((digitopo.io.read(folder / "distance.pgm") == images["distance.pgm"]).all()))
print("float32 identical:", bool((digitopo.io.read(folder / "volume.pgm") == images["volume.pgm"]).all()))

fig, axes = plt.subplots(1, 3, figsize=(7.6, 2.3), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
for ax, name in zip(axes, ("shape.pgm", "skeleton.pgm", "distance.pgm")):
    image = digitopo.io.read(folder / name)
    ax.imshow(image, cmap="gray", interpolation="nearest")
    ax.set_title(f"io.read('{name}'): {image.dtype}", fontsize=9, color=TEXT)
    ax.set_xticks([])
    ax.set_yticks([])
fig.tight_layout()
fig.savefig(FIGURES / "pgm-files.png", dpi=100)
plt.close(fig)