Coverage for pyguymer3/image/save_array_as_PGM.py: 14%
7 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
1#!/usr/bin/env python3
3# Define function ...
4def save_array_as_PGM(
5 img,
6 fname,
7 /,
8):
9 """
10 Save an array as a PGM image.
12 img -- a 2D NumPy array of type uint8 with shape (ny,nx)
13 fname -- output file name
14 """
16 # Find image size ...
17 ny, nx = img.shape
19 # Check image ...
20 if not img.dtype == "uint8":
21 raise TypeError("\"img\" must be a \"uint8\" array") from None
23 # Write out PGM ...
24 with open(fname, "wb") as fObj:
25 fObj.write(f"P5 {nx:d} {ny:d} 255 ".encode("utf-8"))
26 img.tofile(fObj)