What is a PGM File?
A PGM (Portable GrayMap) file is a simple grayscale image format from the Netpbm family, created by Jef Poskanzer in the late 1980s. A PGM file has a short text header with the format code, width, height and maximum gray value, followed by one gray value for every pixel.
There are two variants: plain PGM (P2) stores the values as ASCII numbers, and raw PGM (P5) stores them as binary bytes, using two bytes per pixel when the maximum value is above 255. Because the format is so simple, PGM is popular in computer vision, image-processing courses and scientific software.
Download PGM Sample Files
Below are four 8-bit grayscale PGM images from 640 × 427 up to 4K.
PGM Sample File Details
| Sample | Header | Pixel data | File size |
|---|---|---|---|
| 640×427 | P5 640 427 255 | 273,280 bytes | 267 KB |
| 1280×853 | P5 1280 853 255 | 1,091,840 bytes | 1.04 MB |
| 1920×1280 | P5 1920 1280 255 | 2,457,600 bytes | 2.34 MB |
| 3840×2160 | P5 3840 2160 255 | 8,294,400 bytes | 7.91 MB |
All four are binary (P5) images with a maximum gray value of 255, so every pixel takes exactly one byte. Each file is a 15 to 17-byte header followed by width × height bytes of uncompressed pixel data.
What You Can Test With These PGM Files
- Image processing and computer vision: OpenCV, scikit-image and other libraries that read PGM.
- Parsers: reading the header and checking the pixel data length.
- Grayscale pipelines: filters, thresholding and edge detection.
- Uncompressed data: files up to 8 MB at 4K, easy to compare byte for byte.
- Format conversion: PGM to PNG, JPG or other formats.
How to Open or Convert a PGM File
# Show the header
head -c 20 sample-640x427.pgm
# Convert to PNG with ImageMagick
magick sample-640x427.pgm sample.png
# Read it in Python with OpenCV
import cv2
image = cv2.imread("sample-640x427.pgm", cv2.IMREAD_GRAYSCALE)
print(image.shape) # (427, 640)
GIMP, IrfanView, XnView and many other image viewers also open PGM files.






