如何将.pgm文件转换为其他表单

2024-03-29 11:55:00 发布

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

我有大约3000个.pgm文件,希望将它们转换成更有用的文件,以便将其作为视频查看,例如.avi或.mp4。我知道pil,我的顾问提供了下面的代码,但我不知道它在做什么,也不知道它为什么返回语法错误。 我在与.pgm文件位于同一目录的jupyter笔记本中工作,但glob2.glob似乎是问题所在(语法错误)。关于如何让这段代码工作有什么想法吗

根据另一个线程的建议,我尝试添加更多的括号。这似乎不起作用

import numpy as np
import glob2
from PIL import Image

def pgm_to_image ((glob2.glob("temp-09162019162411-0.pgm")):
with open((glob2.glob("temp-09162019162411-0.pgm")), 'rb') as f:
    mn = f.read(2)
    f.read(1)

    if mn == b'P2':
        dat = np.fromstring(f.read(), dtype='u2', sep=' ')
        width, height, maxval = dat[:3]
        dat = dat[3:].reshape(height, width)
        if maxval <= 255: dat = dat.astype('u1')

    else:
        raise ValueError('File format not supported.')

return Image.fromarray(dat)

if __name__ == "__main__":
img = pgm_to_image('temp-09162019162414-7.pgm')
# print(dat.shape, dat.dtype)
# print(dat[:20])
img.save('test.png')'

Tags: 文件to代码imageimportreadifas