Exercise
Show BMP On Console
Objective
Develop Python program to decode and display a Netpbm image file
The Netpbm format is a family of image formats designed for simplicity rather than file size. These formats can represent color, grayscale, or black-and-white images using plain text, although binary versions also exist.
For instance, a black-and-white image encoded in ASCII uses the "P1" header.
The file may optionally contain a comment line starting with #.
Next, the image dimensions (width and height) are listed on the following line.
The remaining lines contain the pixel data: 1 represents black and 0 represents white. For example:
P1
This is an example bitmap of the letter "J"
6 10
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Create a Python program to decode this type of image file and display its content in the console. Note that the comment is optional.
Example Python Exercise
Show Python Code
# Python program to decode and display a Netpbm image (P1 format) from a file
def decode_netpbm(file_path):
try:
# Open the Netpbm file
with open(file_path, 'r') as file:
# Read the first line (P1 header)
header = file.readline().strip()
if header != 'P1':
print("Error: This is not a valid P1 Netpbm image.")
return
# Skip comment lines (if present)
while True:
line = file.readline().strip()
if line and not line.startswith('#'):
# This is the line with image dimensions (width and height)
width, height = map(int, line.split())
break
# Read and display the pixel data
print(f"Image dimensions: {width}x{height}")
print("Image Data:")
for _ in range(height):
row = file.readline().strip().split()
# Convert 0 to 'White' and 1 to 'Black' and display it
print(' '.join('Black' if pixel == '1' else 'White' for pixel in row))
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
except Exception as e:
print(f"Error: {str(e)}")
# Example usage
decode_netpbm('image.pbm')
Output
Example Input (image.pbm):
P1
# This is an example bitmap of the letter "J"
6 10
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Example Output:
Image dimensions: 6x10
Image Data:
White White White White Black White
White White White White Black White
White White White White Black White
White White White White Black White
White White White White Black White
White White White White Black White
Black White White White Black White
White Black Black Black White White
White White White White White White
White White White White White White
Share this Python Exercise