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

2024-05-16 06:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何从存在中删除此文件的前三行?在

下面是一个.ppm文件的示例,名为,微量.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个列表的列表,并删除所有这些文件的前三行。在

^{2}$

Tags: 文件代码信息示例内容列表files微量
2条回答

如果您想要更健壮的方法来读取图像并对其执行各种操作,我建议使用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

例如,可以裁剪图像:

^{pr2}$

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

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

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

但是,你更可能以这样的方式来读取多个文件:

^{pr2}$

编辑

如果要将所有文件的像素值混合到三个颜色通道列表中:

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]]

相关问题 更多 >