import sys
def read_pgm(filename):
"""
Reads a PGM (P5) binary file and returns its width, height, max intensity, and pixel data.
"""
try:
with open(filename, "rb") as file:
# Read magic number
magic_number = file.readline().strip()
if magic_number != b"P5":
raise ValueError("File is not in P5 binary PGM format.")
# Read dimensions (width and height)
dimensions = file.readline().strip()
width, height = map(int, dimensions.split())
# Read maximum intensity value
max_intensity = int(file.readline().strip())
if max_intensity != 255:
raise ValueError("This program only supports max intensity of 255.")
# Read image data
pixel_data = file.read()
if len(pixel_data) != width * height:
raise ValueError("Mismatch between pixel data and image dimensions.")
return width, height, pixel_data
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
sys.exit(1)
except Exception as e:
print(f"Error: {str(e)}")
sys.exit(1)
def display_pgm_image(width, height, pixel_data):
"""
Displays PGM image pixel data as symbols based on intensity ranges.
"""
intensity_map = {
(200, 255): " ",
(150, 199): ".",
(100, 149): "-",
(50, 99): "=",
(0, 49): "#",
}
for y in range(height):
row = ""
for x in range(width):
intensity = pixel_data[y * width + x]
for range_min, range_max in intensity_map:
if range_min <= intensity <= range_max:
row += intensity_map[(range_min, range_max)]
break
print(row)
if __name__ == "__main__":
# Ensure the filename is provided as a command-line argument
if len(sys.argv) != 2:
print("Usage: python pgm_viewer.py ")
sys.exit(1)
# Read the PGM file
filename = sys.argv[1]
width, height, pixel_data = read_pgm(filename)
# Display the image
display_pgm_image(width, height, pixel_data)
Output
A binary PGM file with the following header:
P5
6 4
255
And pixel data (as binary values):
200 180 120 80 30 10
250 190 140 90 40 20
220 170 130 70 60 50
210 160 110 100 0 5
Execution:
python pgm_viewer.py example.pgm
Output:
. - = # #
. . - = # #
. . - = = =
. . - - # #