I need a way I can read the lines and extract the pixel info into some structure so I can use the putpixel function to create an image based on the ppm p3 file.
I'm working with Python Imaging Library (PIL) and I want to open a PPM image and display it as an image on the screen.
How can I do that using only PIL?
This is my ppm image. It's just a 7x1 image that I created.
P3
# size 7x1
7 1
255
0
0
0
201
24
24
24
201
45
24
54
201
201
24
182
24
201
178
104
59
14
And if you like working with np.array objects, just do this:
>>> from scipy.misc import imread
>>> img = imread(path_to_ppm_file)
>>> img.shape
>>> (234, 555, 3)
.ppm is one of the file formats in which image data is stored so that it is more human🕴 readable.
It stands for Portable PixMap format
These files are usually of the following format:
# Optional Comments likes this one
# The first line is the image header which contains the format followed by width and height
P3 7 1
# Second line contains the maximum value possible for each color point
255
# Third line onwards, it contains the pixels represented in rows(7) and columns(1)
0 0 0
201 24 24
24 201 45
24 54 201
201 24 182
24 201 178
104 59 14
Reference
So you can see that you have properly rewrite your PPM file (since RGB triplets are considered for each pixel in a color image)
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("\path to the image")
# Remember, opencv by default reads images in BGR rather than RGB
# So we fix that by the following
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
# Now, for small images like yours or any similar ones we use for example purpose to understand image processing operations or computer graphics
# Using opencv's cv2.imshow()
# Or google.colab.patches.cv2_imshow() [in case we are on Google Colab]
# Would not be of much use as the output would be very small to visualize
# Instead using matplotlib.pyplot.imshow() would give a decent visualization
plt.imshow(img)
Although the documentation states that we can directly open .ppm files using🤨:
from PIL import Image
img = Image.open("path_to_file")
Reference
However, when we inspect further we can see that they only support the binary version (otherwise called P6 for PPM)😫 and not the ASCII version (otherwise called P3 for PPM)😑.
Reference
Hence, for your use case using PIL would not be an ideal option❌.
The benefit of visualization🔭 using matplotlib.pyplot.imshow() shall hold true as above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With