0

我的程序要求用户输入 P6 .ppm 图像的文件名,然后我的程序将一个新文件作为 P5 .pgm 图像写入并将其转换为灰度。我的程序运行良好,除非正在打开的图像在标题中有注释。我不确定我的问题是在我的 Main() 还是我的 GetNum 函数中。任何帮助深表感谢!

我的主要开始看起来像这样

fileInput = raw_input("Enter the name of the original file including .ppm at the end: ")#P6 = .ppm
fileOutput = raw_input("Enter the file name for the new picture including .pgm at the end: ")#P5 = .pgm
readFile = open(fileInput, "rb")
writeFile = open(fileOutput, 'wb')
magicNumber1 = readFile.read(1)#MagicNumber 1 and 2 grabs the first two bytes for the header, which should be P6
magicNumber2 = readFile.read(1)

还是我的 GetNum 函数中存在我的问题?

def GetNum(f):

currentChar = f.read(1) #Reads through the file 1 byte at a time

while currentChar.isdigit() == False:
    while currentChar.isspace(): #Keep reading if the current character is a space
        currentChar = f.read(1)

    if currentChar == "#": #If a comment or new line keep reading
        while currentChar != "\n":
            currentChar = f.read(1)

num = currentChar
while currentChar.isdigit(): #If current character is a digit, add it onto Num
    currentChar = f.read(1)
    num = num + currentChar

num = num.strip()

return num
4

1 回答 1

0

问题出在GetNum(f).

在这个循环结束时

while currentChar != "\n":
    currentChar = f.read(1)

currentChar等于\n

这意味着num = currentChar 设置num\n

并且因为currentCharcontains永远不会进入\n下一个循环。while currentChar.isdigit()所以num不会添加任何数字,并去掉num = num.strip()\n包含的数字,因此GetNum(f)返回一个空字符串。

...

您是否有任何理由自己解析 PPM 文件,而不是使用库?我假设这是一个编程练习,因为 ppmtopgm 存在。

FWIW,我经常使用 NetPBM 文件,在 CI 中使用我自己的解析器,但在 Python 中我通常使用库来读取它们;有时我使用库来编写它们,但文件格式非常简单,我经常“手工”完成。

处理解析问题的一个好方法是使用状态机

我还应该提到 Python 模块 shlex 可以用来做这样的事情,但我想如果这是一个编程练习,你可能不应该使用 shlex。:)

于 2014-10-19T07:14:10.710 回答