使用您的确切示例的一些背景概念:
# 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
参考
所以你可以看到你已经正确地重写了你的 PPM 文件(因为彩色图像中的每个像素都考虑了 RGB 三元组)
打开和可视化文件
OpenCV(做得很棒)
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)
枕头(或者我们称之为 PIL)
尽管文档声明我们可以.ppm
使用以下方法直接打开文件:
from PIL import Image
img = Image.open("path_to_file")
参考
但是,当我们进一步检查时,我们可以看到它们仅支持二进制版本(对于 PPM 也称为 P6),而不支持 ASCII 版本(对于 PPM 也称为 P3)。
参考
因此,对于您的用例,使用 PIL 不是一个理想的选择❌。
使用可视化的好处matplotlib.pyplot.imshow()
应如上所示。