古老的PPM/PGM/PBM图像格式

Last Updated: 2023-03-28 09:17:30 Tuesday

-- TOC --

PPM (Portable PixMap), PGM (Portable GreyMap), PBM (Portable BitMap) files. These formats are a convenient (simple) method of saving image data, they are equally easy to read in ones own applications.

They are very old, having been developed in the 80's, are not and probably never will be well supported, and certainly were never intended for higher bit depth images even though there have been binary variants (P5 and P6) since that do support higher bit depths.

PPM

PPM(Portable PixMap)图像格式是由Jef Poskanzer在1991年所创造的,它及其简单,主要存储RGB数据,它比bmp格式简单直接。

PPM文件分成4个部分:

  1. magic number(ASCII), P3 or P6
  2. width height (ASCII),
  3. 最大像素颜色值(ASCII),如果data precision大于8,这个值会超过255
  4. RGB data(ASCII or Binary)

前3部分还可以有由#开始的comments...

>>> f = open('1.ppm','rb')
>>> f.readline()
b'P6\n'
>>> f.readline()
b'4096 2160\n'
>>> f.readline()
b'255\n'
>>> f.read(3)
...

下面也是一些合法的PPM文件头格式示例:

---- Header example 1 ----
P6 1024 788 255

---- Header example 2 ----
P6 
1024 788 
# A comment
255

---- Header example 3 ----
P3
1024 # the image width
788 # the image height
# A comment
1023

如果P3,按ASCII存储image data:

The format of the image data itself depends on the magic PPM identifier. If it is P3 then the image is given as ASCII text, the numerical value of each pixel ranges from 0 to the maximum value given in the header. The lines should not be longer than 70 characters. 这个长度限制也适用于PGM和PBM,为啥有这个限制呢?

P3
# example from the man page
4 4
15
 0  0  0    0  0  0    0  0  0   15  0 15
 0  0  0    0 15  7    0  0  0    0  0  0
 0  0  0    0  0  0    0 15  7    0  0  0
15  0 15    0  0  0    0  0  0    0  0  0

如果P6,按Binary存储image data。就是直接R+G+B/pixel,packed!将RGB数据保存为PPM格式,比保存为BMP格式,要简单很多。就前面3行信息,然后就是RGB。

PGM

PGM (Portable GreyMap)

与PPM的区别:

一个PGM文件的例子:

P2
24 7
15
0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
0  3  3  3  3  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15 15 15 15  0
0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0 15  0
0  3  3  3  0  0  0  7  7  7  0  0  0 11 11 11  0  0  0 15 15 15 15  0
0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0  0  0
0  3  0  0  0  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15  0  0  0  0
0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0

PBM

PBM (Portable BitMap)

这是只有0(white)1(black)的图形数据文件。

一个示例:

P1
# PBM example 
24 7
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 1 1 1 0
0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0
0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 1 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 1 1 1 0 0 1 1 1 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

本文链接:https://cs.pynote.net/ag/image/202303231/

-- EOF --

-- MORE --