Skip to content

digitopo.io

Read and write Pink PGM images as NumPy arrays.

The Pink PGM format stores 2D and 3D images of uint8, int32, float32 or float64 pixels. Arrays use the NumPy axis order: a 2D image is (rows, columns), a 3D image is (depth, rows, columns).

The functions are those of pink26.io: read accepts the files that pink26 accepts and gives the same arrays, write writes the same bytes as pink26. The parsing and the encoding are done in Rust.

read

read(path: str | PathLike[str]) -> np.ndarray

Read a Pink PGM file into a NumPy array.

Parameters:

Name Type Description Default
path str or PathLike

Path of the file to read.

required

Returns:

Type Description
ndarray

A new array owned by the caller, with dtype uint8, int32, float32 or float64. Shape is (rows, columns) for a 2D image and (depth, rows, columns) for a 3D image. The array is the one that pink26.io.read returns.

Raises:

Type Description
OSError

If the file cannot be opened or read (FileNotFoundError if it does not exist).

DigitopoError

If the content is malformed, truncated or unsupported (for example 16-bit pixels).

UnicodeDecodeError

If the header holds bytes that are not text, as with pink26 (the file is not a PGM file).

Examples:

Write a small image in a temporary folder, then read it back:

>>> import os, tempfile
>>> import numpy as np, digitopo
>>> with tempfile.TemporaryDirectory() as folder:
...     path = os.path.join(folder, "example.pgm")
...     digitopo.io.write(path, np.zeros((5, 7), dtype=np.uint8))
...     image = digitopo.io.read(path)
>>> image.shape, image.dtype
((5, 7), dtype('uint8'))

write

write(path: str | PathLike[str], image: ArrayLike) -> None

Write a NumPy array as a Pink PGM file.

The file holds the same bytes as the one pink26.io.write writes: the raw formats P5 (uint8), P8 (int32), P9 (float32) and PC (float64), little-endian.

Parameters:

Name Type Description Default
path str or PathLike

Path of the file to create (an existing file is overwritten).

required
image ndarray

2D array (rows, columns) or 3D array (depth, rows, columns) of dtype uint8, int32, float32, float64 or bool. A bool array is saved as uint8 with False -> 0 and True -> 255. Non-contiguous arrays are accepted (they are copied).

required

Raises:

Type Description
ValueError

If image is not 2D or 3D, or has an axis of length zero.

TypeError

If the dtype is not one of the supported ones.

DigitopoError

If the image cannot be encoded.

OSError

If the file cannot be written.

Examples:

Write an image in a temporary folder, then read it back:

>>> import os, tempfile
>>> import numpy as np, digitopo
>>> image = np.zeros((5, 7), dtype=np.uint8)
>>> with tempfile.TemporaryDirectory() as folder:
...     path = os.path.join(folder, "zeros.pgm")
...     digitopo.io.write(path, image)
...     shape = digitopo.io.read(path).shape
>>> shape
(5, 7)