如何提取每个ppm文件的前3行?

时间:2015-06-20 02:22:22

标签: python

我所做的就是打开小文件并将内容附加到名为files的列表中。文件包含微小ppm行的列表。

如何删除此文件的前三行?

以下是.ppm文件的示例,称为tiny.ppm。

P3
5 5
255
255 0 0
100 150 175
100 150 175
100 150 175
100 150 175
100 150 175
255 0 0
100 150 175
100 150 175
100 150 175
100 150 175
100 150 175
255 0 0
100 150 175
100 150 175
100 150 175
100 150 175
100 150 175
255 0 0
100 150 175
100 150 175
100 150 175
100 150 175
100 150 175
255 0 0

我的代码如下,但是,我希望“文件”最终包含9个列表,其中包含9个不同文件的信息,并删除所有这些信息的前三行。

def readFiles():
    files = []
    files.append(open('tiny.ppm','rU').readlines())
    print(files)

2 个答案:

答案 0 :(得分:1)

要阅读文件并跳过前三行:

def readFiles():
    files = []
    files.append(open('tiny.ppm','rU').readlines()[3:])
    print(files)

但你更有可能以这样的方式阅读多个文件:

def readFiles():
    from glob import glob
    files = []
    for f in glob('*.ppm'):
        content = open(f, 'rU').readlines()
        files.append(content[3:])

修改

如果您希望将所有文件的像素值拼凑成三个颜色通道列表:

r, g, b = [],[],[]
for filecontent in files:
    for line in filecontent:
        liner, lineg, lineb = line.split()
        r.append(liner)
        g.append(lineg)
        b.append(lineb)

(但为什么你要把它们分开'文件'?)

修改

哈哈,这太可怕了

>>> r, g, b = [],[],[]
>>> [(r.append(pr),g.append(pg),b.append(pb)) for (pr,pg,pb) in [tuple(l.split()) for l in f for f in fs]]

答案 1 :(得分:1)

如果你想要更健壮的东西来阅读图像并对它们进行各种操作,我推荐使用Python中的Pillow包。

from PIL import Image
from glob import glob

def readFiles():
    images = []
    for f in glob("*.ppm"):
        image = Image.open(f)
        image_pix = list(image.getdata())  # retrieve raw pixel values as a list
        images.append(image_pix)
    return images  # images is now a list of lists of pixel values

例如,您可以裁剪图像:

box = (100, 100, 400, 400)
region = image.crop(box)

此处有更多示例和教程:http://pillow.readthedocs.org/en/latest/handbook/tutorial.html